<?php

namespace App\Http\Controllers\Web;

use App\Http\Controllers\Controller;
use App\Models\LastCertificate;
use App\Models\NewCertificate;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Log;

class CertificateController extends Controller
{
    /**
     * Download a new certificate
     */
    public function downloadNewCertificate($id)
    {
        $certificate = NewCertificate::findOrFail($id);

        $this->authorizeNewCertificateDownload($certificate);

        if (!$certificate->generated_image_path) {
            abort(404, 'Certificate image not found');
        }

        $fullPath = resolvePublicStorageFilePath($certificate->generated_image_path);

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

        $extension = File::extension($fullPath) ?: 'jpg';
        $fileName = 'certificate_' . preg_replace('/\s+/', '_', (string) ($certificate->student_name ?? $certificate->id)) . '.' . $extension;

        return response()->download($fullPath, $fileName);
    }

    /**
     * Download a last (auto-generated) certificate
     */
    public function downloadLastCertificate($id)
    {
        $certificate = LastCertificate::with('user')->findOrFail($id);

        $this->authorizeLastCertificateDownload($certificate);

        if (!$certificate->image_path) {
            abort(404, 'Certificate image not found');
        }

        $fullPath = resolvePublicStorageFilePath($certificate->image_path);

        if (!$fullPath) {
            Log::warning('Last certificate file not found for download', [
                'certificate_id' => $certificate->id,
                'image_path' => $certificate->image_path,
                'user_id' => $certificate->user_id,
            ]);

            abort(404, 'Certificate file not found');
        }

        $extension = File::extension($fullPath) ?: 'png';
        $userName = $certificate->user->full_name ?? ('certificate_' . $certificate->id);
        $fileName = 'certificate_' . preg_replace('/\s+/', '_', $userName) . '.' . $extension;

        return response()->download($fullPath, $fileName);
    }

    private function authorizeLastCertificateDownload(LastCertificate $certificate): void
    {
        if (!auth()->check()) {
            abort(403);
        }

        $user = auth()->user();

        if (method_exists($user, 'isAdmin') && $user->isAdmin()) {
            return;
        }

        if ((int) $certificate->user_id !== (int) $user->id) {
            abort(403);
        }
    }

    private function authorizeNewCertificateDownload(NewCertificate $certificate): void
    {
        if (!auth()->check()) {
            abort(403);
        }

        $user = auth()->user();

        if (method_exists($user, 'isAdmin') && $user->isAdmin()) {
            return;
        }

        $ownsCertificate = (int) ($certificate->student_id ?? 0) === (int) $user->id
            || (!empty($certificate->student_email) && strcasecmp($certificate->student_email, (string) $user->email) === 0);

        if (!$ownsCertificate) {
            abort(403);
        }
    }
}
