<?php

namespace App\Services;

use App\Models\Order;
use Carbon\Carbon;
use Illuminate\Support\Facades\Log;

class DeviceFingerprintService
{
    /**
     * Generate a unique device fingerprint hash
     * 
     * @param array $deviceData Array containing ip, userAgent, screenResolution
     * @return string 64-character hash
     */
    public function generateFingerprint(array $deviceData): string
    {
        $ip = $deviceData['ip'] ?? 'unknown';
        $userAgent = $deviceData['userAgent'] ?? 'unknown';
        $screenResolution = $deviceData['screenResolution'] ?? 'unknown';
        
        // Combine device data
        $combined = $ip . '|' . $userAgent . '|' . $screenResolution;
        
        // Generate SHA-256 hash
        return hash('sha256', $combined);
    }
    
    /**
     * Check if device has submitted an order in the last 24 hours
     * 
     * @param string $fingerprint Device fingerprint hash
     * @return bool True if duplicate found, false otherwise
     */
    public function isDuplicateSubmission(string $fingerprint): bool
    {
        $twentyFourHoursAgo = Carbon::now()->subHours(24);
        
        $recentOrder = Order::where('device_fingerprint', $fingerprint)
            ->where('created_at', '>=', $twentyFourHoursAgo)
            ->first();
        
        return $recentOrder !== null;
    }
    
    /**
     * Get the most recent order for a device fingerprint
     * 
     * @param string $fingerprint Device fingerprint hash
     * @return Order|null
     */
    public function getRecentOrder(string $fingerprint): ?Order
    {
        $twentyFourHoursAgo = Carbon::now()->subHours(24);
        
        return Order::where('device_fingerprint', $fingerprint)
            ->where('created_at', '>=', $twentyFourHoursAgo)
            ->orderBy('created_at', 'desc')
            ->first();
    }
    
    /**
     * Clear device fingerprint (admin override)
     * 
     * @param string $fingerprint Device fingerprint hash to clear
     * @return int Number of orders updated
     */
    public function clearFingerprint(string $fingerprint): int
    {
        return Order::where('device_fingerprint', $fingerprint)
            ->update(['device_fingerprint' => null]);
    }
    
    /**
     * Clear all device fingerprints older than 24 hours
     * 
     * @return int Number of orders updated
     */
    public function clearExpiredFingerprints(): int
    {
        $twentyFourHoursAgo = Carbon::now()->subHours(24);
        
        return Order::whereNotNull('device_fingerprint')
            ->where('created_at', '<', $twentyFourHoursAgo)
            ->update(['device_fingerprint' => null]);
    }
    
    /**
     * Get all active device fingerprints with order counts
     * 
     * @return array
     */
    public function getActiveFingerprints(): array
    {
        $twentyFourHoursAgo = Carbon::now()->subHours(24);
        
        return Order::whereNotNull('device_fingerprint')
            ->where('created_at', '>=', $twentyFourHoursAgo)
            ->selectRaw('device_fingerprint, COUNT(*) as order_count, MAX(created_at) as last_order_at, MAX(student_name) as student_name')
            ->groupBy('device_fingerprint')
            ->orderBy('last_order_at', 'desc')
            ->get()
            ->toArray();
    }
    
    /**
     * Log device fingerprint activity
     * 
     * @param string $fingerprint
     * @param string $action
     * @param array $context
     */
    public function logActivity(string $fingerprint, string $action, array $context = []): void
    {
        Log::info("Device Fingerprint: {$action}", array_merge([
            'fingerprint' => $fingerprint,
            'timestamp' => now()->toDateTimeString(),
        ], $context));
    }
}


