<?php

namespace App\Http\Controllers\Mentorship;

use App\Http\Controllers\Controller;
use App\Models\Mentorship\Certificate;
use App\Models\Mentorship\Assignment;
use App\Services\Mentorship\CertificateService;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Storage;

class CertificateController extends Controller
{
    protected CertificateService $certificateService;

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

    /**
     * Display a listing of certificates.
     */
    public function index(Request $request)
    {
        abort_unless(auth()->user()->can('view mentorship certificates'), 403);

        $filters = [
            'status' => $request->get('status'),
            'programme_id' => $request->get('programme_id'),
            'user_id' => $request->get('user_id'),
            'search' => $request->get('search'),
            'sort_by' => $request->get('sort_by', 'generated_at'),
            'sort_order' => $request->get('sort_order', 'desc'),
        ];

        $certificates = $this->certificateService->getCertificates($filters);

        return view('mentorship.certificates.index', compact('certificates', 'filters'));
    }

    /**
     * Display certificates for the current user.
     */
    public function myCertificates(Request $request)
    {
        $filters = [
            'status' => $request->get('status'),
            'search' => $request->get('search'),
        ];

        $certificates = $this->certificateService->getForUser(auth()->id());

        return view('mentorship.certificates.my-certificates', compact('certificates', 'filters'));
    }

    /**
     * Display the specified certificate.
     */
    public function show(Certificate $certificate)
    {
        abort_unless(
            auth()->user()->can('view mentorship certificates') ||
            $certificate->user_id === auth()->id(),
            403
        );

        $certificate->load(['user', 'programme', 'assignment.mentor']);

        return view('mentorship.certificates.show', compact('certificate'));
    }

    /**
     * Generate a certificate for an assignment.
     */
    public function generate(Assignment $assignment)
    {
        abort_unless(auth()->user()->can('generate mentorship certificates'), 403);

        try {
            $certificate = $this->certificateService->generate($assignment, auth()->id());

            return redirect()
                ->route('mentorship.certificates.show', $certificate)
                ->with('success', 'Certificate generated successfully.');
        } catch (\Exception $e) {
            return back()->withErrors(['error' => $e->getMessage()]);
        }
    }

    /**
     * Download certificate PDF.
     */
    public function download(Certificate $certificate)
    {
        abort_unless(
            auth()->user()->can('download mentorship certificates') ||
            $certificate->user_id === auth()->id(),
            403
        );

        if ($certificate->status !== Certificate::STATUS_ACTIVE) {
            return back()->withErrors(['error' => 'This certificate is not available for download.']);
        }

        try {
            $path = $this->certificateService->getDownloadPath($certificate);

            if (!$path || !Storage::exists($path)) {
                return back()->withErrors(['error' => 'Certificate file not found.']);
            }

            return Storage::download($path, $certificate->file_name ?? 'certificate.pdf');
        } catch (\Exception $e) {
            return back()->withErrors(['error' => $e->getMessage()]);
        }
    }

    /**
     * Verify certificate by verification code.
     */
    public function verify(string $code)
    {
        $certificate = $this->certificateService->verifyByCode($code);

        if (!$certificate) {
            return view('mentorship.certificates.verify', [
                'found' => false,
                'message' => 'Certificate not found. Please check the verification code.',
            ]);
        }

        return view('mentorship.certificates.verify', [
            'found' => true,
            'certificate' => $certificate,
            'isValid' => $certificate->isValidForVerification(),
        ]);
    }

    /**
     * Show verification page.
     */
    public function verifyPage()
    {
        return view('mentorship.certificates.verify-page');
    }

    /**
     * Revoke a certificate.
     */
    public function revoke(Request $request, Certificate $certificate)
    {
        abort_unless(auth()->user()->can('revoke mentorship certificates'), 403);

        $request->validate([
            'reason' => 'required|string|max:1000',
        ]);

        try {
            $this->certificateService->revoke($certificate, auth()->id(), $request->reason);

            return redirect()
                ->route('mentorship.certificates.show', $certificate)
                ->with('success', 'Certificate revoked.');
        } catch (\Exception $e) {
            return back()->withErrors(['error' => $e->getMessage()]);
        }
    }

    /**
     * Regenerate certificate PDF.
     */
    public function regenerate(Certificate $certificate)
    {
        abort_unless(auth()->user()->can('generate mentorship certificates'), 403);

        try {
            $this->certificateService->regeneratePdf($certificate);

            return redirect()
                ->route('mentorship.certificates.show', $certificate)
                ->with('success', 'Certificate PDF regenerated.');
        } catch (\Exception $e) {
            return back()->withErrors(['error' => $e->getMessage()]);
        }
    }

    /**
     * Bulk generate certificates for a programme.
     */
    public function bulkGenerate(Request $request)
    {
        abort_unless(auth()->user()->can('generate mentorship certificates'), 403);

        $request->validate([
            'programme_id' => 'required|exists:mentorship_programmes,id',
        ]);

        try {
            $result = $this->certificateService->bulkGenerate(
                $request->programme_id,
                auth()->id()
            );

            return response()->json([
                'success' => true,
                'message' => "Generated {$result['generated']->count()} certificates.",
                'generated' => count($result['generated']),
                'failed' => count($result['failed']),
                'total' => $result['total'],
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => $e->getMessage(),
            ], 422);
        }
    }

    /**
     * Preview certificate template.
     */
    public function preview(Assignment $assignment)
    {
        abort_unless(auth()->user()->can('view mentorship certificates'), 403);

        // Create a sample certificate data for preview
        $certificateData = [
            'certificate_number' => 'PREVIEW',
            'verification_code' => 'PREVIEW',
            'recipient_name' => $assignment->mentee->name,
            'programme_name' => $assignment->programme->title,
            'organization_name' => config('app.name', 'Mentorship Platform'),
            'mentor_name' => $assignment->mentor->name,
            'completion_date' => now()->toDateString(),
            'issue_date' => now()->toDateString(),
            'orientation' => $assignment->programme->certificate_orientation ?? 'landscape',
        ];

        return view('mentorship.certificates.preview', compact('certificateData'));
    }
}
