<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\LastCertificate;
use App\User;
use App\Services\CertificateGeneratorService;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\View\View;
use Illuminate\Http\RedirectResponse;

class CertificateGeneratorController extends Controller
{
    protected $certificateService;

    public function __construct(CertificateGeneratorService $certificateService)
    {
        $this->certificateService = $certificateService;
    }

    /**
     * Display a listing of users for certificate generation.
     */
    public function index(Request $request): View
    {
        $this->authorize('admin_certificate_list');

        $query = User::where('role_name', 'user')
            ->select('id', 'full_name', 'email', 'serial_number');

        // Add search functionality
        if ($request->has('search') && !empty($request->search)) {
            $searchTerm = $request->search;
            $query->where(function($q) use ($searchTerm) {
                $q->where('full_name', 'LIKE', "%{$searchTerm}%")
                  ->orWhere('email', 'LIKE', "%{$searchTerm}%")
                  ->orWhere('serial_number', 'LIKE', "%{$searchTerm}%");
            });
        }

        $users = $query->orderBy('full_name')->paginate(20);

        $recentCertificates = LastCertificate::with('user')
            ->orderBy('generated_at', 'desc')
            ->limit(10)
            ->get();

        $stats = $this->certificateService->getCertificateStats();

        return view('admin.certificate-generator.index', compact(
            'users',
            'recentCertificates',
            'stats'
        ));
    }

    /**
     * Show the certificate generation form for a specific user.
     */
    public function create(User $user): View
    {
        $this->authorize('admin_certificate_create');

        $userData = $this->certificateService->getUserDataForCertificate($user);
        $templates = $this->certificateService->getAvailableTemplates();

        return view('admin.certificate-generator.create', compact(
            'user',
            'userData',
            'templates'
        ));
    }

    /**
     * Generate a certificate for a user.
     */
    public function store(Request $request, User $user): JsonResponse
    {
        $this->authorize('admin_certificate_create');

        try {
            $certificate = $this->certificateService->generateCertificate($user, $request);

            return response()->json([
                'success' => true,
                'message' => 'Certificate generated successfully!',
                'certificate' => [
                    'id' => $certificate->id,
                    'image_url' => $certificate->image_url,
                    'generated_at' => $certificate->generated_at->format('Y-m-d H:i:s'),
                ]
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => $e->getMessage(),
            ], 422);
        }
    }

    /**
     * Display the generated certificates list.
     */
    public function certificates(): View
    {
        $this->authorize('admin_certificate_list');

        $certificates = LastCertificate::with('user')
            ->orderBy('generated_at', 'desc')
            ->paginate(20);

        return view('admin.certificate-generator.certificates', compact('certificates'));
    }

    /**
     * Show a specific certificate.
     */
    public function show(LastCertificate $certificate): View
    {
        $this->authorize('admin_certificate_list');

        $certificate->load('user');

        return view('admin.certificate-generator.show', compact('certificate'));
    }

    /**
     * Download a certificate.
     */
    public function download(LastCertificate $certificate)
    {
        $this->authorize('admin_certificate_list');

        $filePath = $certificate->storage_path;

        if (!file_exists($filePath)) {
            abort(404, 'Certificate file not found');
        }

        return response()->download($filePath, 'certificate_' . $certificate->user->full_name . '.png');
    }

    /**
     * Delete a certificate.
     */
    public function destroy(LastCertificate $certificate): JsonResponse
    {
        $this->authorize('admin_certificate_delete');

        try {
            $success = $this->certificateService->deleteCertificate($certificate);

            if ($success) {
                return response()->json([
                    'success' => true,
                    'message' => 'Certificate deleted successfully!',
                ]);
            } else {
                return response()->json([
                    'success' => false,
                    'message' => 'Failed to delete certificate.',
                ], 500);
            }

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => $e->getMessage(),
            ], 500);
        }
    }

    /**
     * Get user data for AJAX requests.
     */
    public function getUserData(User $user): JsonResponse
    {
        $this->authorize('admin_certificate_create');

        $userData = $this->certificateService->getUserDataForCertificate($user);

        return response()->json([
            'success' => true,
            'data' => $userData,
        ]);
    }

    /**
     * Get available templates for AJAX requests.
     */
    public function getTemplates(): JsonResponse
    {
        $templates = $this->certificateService->getAvailableTemplates();

        return response()->json([
            'success' => true,
            'templates' => $templates,
        ]);
    }
}
