<?php

namespace App\Http\Controllers;

use App\Models\DisplayDevice;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
// use SimpleSoftwareIO\QrCode\Facades\QrCode; // Not available without GD extension

class DisplayPairingController extends Controller
{
    /**
     * Show pairing page for TV (when accessing short link on TV)
     */
    public function showPairingPage($deviceToken)
    {
        $display = DisplayDevice::where('device_token', $deviceToken)->first();
        
        if (!$display) {
            abort(404, 'Display not found');
        }
        
        // Generate pairing session ID if not exists
        if (!$display->pairing_session_id) {
            $display->update([
                'pairing_session_id' => Str::random(16), // Shorter session ID for QR compatibility
                'pairing_started_at' => now(),
                'pairing_status' => 'waiting'
            ]);
        }
        
        // Generate QR code for mobile authentication
        $mobileAuthUrl = url('/mobile/auth/' . $display->device_token . '/' . $display->pairing_session_id);
        
        // Use QR Server API as alternative (free service)
        $qrCodeUrl = 'https://api.qrserver.com/v1/create-qr-code/?size=250x250&data=' . urlencode($mobileAuthUrl);
        $qrCode = '<img src="' . $qrCodeUrl . '" alt="QR Code" style="max-width: 250px; height: auto; border: 2px solid #e2e8f0; border-radius: 8px;">';
        
        return view('display.pairing', [
            'display' => $display,
            'qrCode' => $qrCode,
            'mobileAuthUrl' => $mobileAuthUrl
        ]);
    }
    
    /**
     * Show mobile authentication page (when scanning QR code)
     */
    public function showMobileAuth($deviceToken, $sessionId)
    {
        $display = DisplayDevice::where('device_token', $deviceToken)
            ->where('pairing_session_id', $sessionId)
            ->first();
            
        if (!$display) {
            abort(404, 'Pairing session not found or expired');
        }
        
        // Check if session is too old (expired after 10 minutes)
        if ($display->pairing_started_at && $display->pairing_started_at->lt(now()->subMinutes(10))) {
            return view('display.pairing-expired');
        }
        
        // Update status to in_progress
        $display->update([
            'pairing_status' => 'in_progress',
            'pairing_user_agent' => request()->userAgent()
        ]);
        
        return view('display.mobile-auth', [
            'display' => $display,
            'deviceToken' => $deviceToken,
            'sessionId' => $sessionId
        ]);
    }
    
    /**
     * Process mobile authentication
     */
    public function processMobileAuth(Request $request, $deviceToken, $sessionId)
    {
        $display = DisplayDevice::where('device_token', $deviceToken)
            ->where('pairing_session_id', $sessionId)
            ->first();
            
        if (!$display) {
            return response()->json([
                'success' => false,
                'message' => 'Pairing session not found or expired'
            ], 404);
        }
        
        $request->validate([
            'email' => 'required|email',
            'password' => 'required'
        ]);
        
        // Attempt authentication
        $credentials = $request->only('email', 'password');
        
        if (Auth::attempt($credentials)) {
            $user = Auth::user();
            
            // Complete the pairing
            $display->update([
                'tenant_id' => $user->tenant_id,
                'is_authorized' => 'oui', // French: yes
                'paired_at' => now(),
                'pairing_status' => 'completed',
                'last_ip' => request()->ip()
            ]);
            
            // Log the user out (since this is just for pairing)
            Auth::logout();
            
            return response()->json([
                'success' => true,
                'message' => 'Display paired successfully!',
                'display_name' => $display->name
            ]);
        } else {
            return response()->json([
                'success' => false,
                'message' => 'Invalid credentials. Please try again.'
            ], 401);
        }
    }
    
    /**
     * Check pairing status (for TV to poll)
     */
    public function checkPairingStatus($deviceToken)
    {
        $display = DisplayDevice::where('device_token', $deviceToken)->first();
        
        if (!$display) {
            return response()->json([
                'success' => false,
                'status' => 'not_found'
            ]);
        }
        
        return response()->json([
            'success' => true,
            'status' => $display->pairing_status,
            'is_authorized' => $display->is_authorized,
            'paired_at' => $display->paired_at,
            'should_redirect' => $display->pairing_status === 'completed' && $display->is_authorized === 'oui'
        ]);
    }
    
    /**
     * Reset pairing session (start over)
     */
    public function resetPairingSession($deviceToken)
    {
        $display = DisplayDevice::where('device_token', $deviceToken)->first();
        
        if (!$display) {
            abort(404, 'Display not found');
        }
        
        $display->update([
            'pairing_session_id' => Str::random(16), // Shorter session ID for QR compatibility
            'pairing_started_at' => now(),
            'pairing_status' => 'waiting',
            'pairing_user_agent' => null
        ]);
        
        return redirect()->route('display.pairing', $deviceToken);
    }
}
