<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Certificate;
use App\Models\NewCertificate;
use App\Models\LastCertificate;
use App\Services\UserSerialGenerator;
use App\User;
use Illuminate\Http\Request;

class CertificateSearchController extends Controller
{
    /**
     * Search certificates by user serial number
     */
    public function searchBySerial(Request $request)
    {
        $this->authorize('admin_certificate_list');

        $search = $request->get('serial_number');
        $certificates = collect();
        $user = null;
        $error = null;

        if (!empty($search)) {
            // Validate serial number format
            if (!UserSerialGenerator::isValidAndUnique($search) && !UserSerialGenerator::getUserBySerial($search)) {
                $error = 'Invalid serial number format. Expected format: USR-YYYY-NNNNNN';
            } else {
                $user = UserSerialGenerator::getUserBySerial($search);
                
                if ($user) {
                    $certificates = $user->getAllCertificates();
                } else {
                    // Also search for certificates directly by serial number in all certificate tables
                    $certificates = $this->searchCertificatesBySerial($search);
                    if ($certificates->isEmpty()) {
                        $error = 'No user or certificates found with this serial number: ' . $search;
                    }
                }
            }
        }

        $data = [
            'pageTitle' => 'Search Certificates by Serial Number',
            'search' => $search,
            'user' => $user,
            'certificates' => $certificates,
            'error' => $error,
            'certificateCount' => $certificates->count()
        ];

        return view('admin.certificates.search_by_serial', $data);
    }

    /**
     * Search users by partial serial number
     */
    public function searchUsersBySerial(Request $request)
    {
        $this->authorize('admin_certificate_list');

        $search = $request->get('serial_number');
        $users = collect();

        if (!empty($search) && strlen($search) >= 3) {
            $users = UserSerialGenerator::searchUsersBySerial($search);
        }

        $data = [
            'pageTitle' => 'Search Users by Serial Number',
            'search' => $search,
            'users' => $users,
            'userCount' => $users->count()
        ];

        return view('admin.certificates.search_users_by_serial', $data);
    }

    /**
     * Get user details and certificates by serial number (API endpoint)
     */
    public function getUserBySerial(Request $request)
    {
        $this->authorize('admin_certificate_list');

        $serialNumber = $request->get('serial_number');
        
        if (empty($serialNumber)) {
            return response()->json([
                'success' => false,
                'message' => 'Serial number is required'
            ], 400);
        }

        $user = UserSerialGenerator::getUserBySerial($serialNumber);
        
        if (!$user) {
            return response()->json([
                'success' => false,
                'message' => 'User not found with serial number: ' . $serialNumber
            ], 404);
        }

        $certificates = $user->getAllCertificates();

        return response()->json([
            'success' => true,
            'user' => [
                'id' => $user->id,
                'full_name' => $user->full_name,
                'email' => $user->email,
                'serial_number' => $user->serial_number,
                'created_at' => $user->created_at
            ],
            'certificates' => $certificates->map(function ($certificate) {
                return [
                    'id' => $certificate->id,
                    'type' => $certificate->type,
                    'created_at' => $certificate->created_at,
                    'quiz_title' => $certificate->quiz->title ?? null,
                    'webinar_title' => $certificate->webinar->title ?? null,
                    'user_grade' => $certificate->user_grade ?? null
                ];
            }),
            'certificate_count' => $certificates->count()
        ]);
    }

    /**
     * Search certificates by serial number across all certificate tables
     */
    private function searchCertificatesBySerial($serialNumber)
    {
        $allCertificates = collect();

        // Search in old certificates table
        $oldCertificates = Certificate::where('serial_number', $serialNumber)
            ->with(['quiz.webinar', 'webinar', 'student'])
            ->get();
        
        foreach ($oldCertificates as $cert) {
            $cert->certificate_type = 'old';
            $allCertificates->push($cert);
        }

        // Search in new certificates table
        $newCertificates = NewCertificate::where('serial_number', $serialNumber)
            ->with('template')
            ->get();
        
        foreach ($newCertificates as $cert) {
            $cert->certificate_type = 'new';
            $allCertificates->push($cert);
        }

        // Search in last certificates table (if it has serial number field)
        // Note: LastCertificate might not have serial_number field, so we'll search by user
        $users = User::where('serial_number', $serialNumber)->get();
        foreach ($users as $user) {
            $lastCertificates = LastCertificate::where('user_id', $user->id)->get();
            foreach ($lastCertificates as $cert) {
                $cert->certificate_type = 'last';
                $allCertificates->push($cert);
            }
        }

        return $allCertificates;
    }
} 