<?php

namespace App\Http\Controllers;

use App\Http\Traits\ResponseTrait;
use App\Models\Certificate;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class CertificateController extends Controller
{
    use ResponseTrait;

    /**
     * Get user's certificates
     * GET /certificates
     */
    public function index(Request $request)
    {
        $user = $request->user();
        
        $certificates = Certificate::where('user_id', $user->id)
            ->orderBy('issued_date', 'desc')
            ->get()
            ->map(function ($certificate) {
                return [
                    'id' => $certificate->id,
                    'title' => $certificate->title,
                    'issuer' => $certificate->issuer,
                    'issued_date' => $certificate->issued_date,
                    'certificate_url' => $certificate->certificate_url,
                    'verification_code' => $certificate->verification_code,
                    'verified' => $certificate->verified,
                    'badge' => $certificate->badge,
                ];
            });

        return $this->successResponse($certificates, 'Certificates retrieved successfully');
    }

    /**
     * Get certificate details
     * GET /certificates/{id}
     */
    public function show(Request $request, Certificate $certificate)
    {
        $user = $request->user();

        // Verify ownership
        if ($certificate->user_id !== $user->id) {
            return $this->notFoundResponse();
        }

        $data = [
            'id' => $certificate->id,
            'title' => $certificate->title,
            'issuer' => $certificate->issuer,
            'issued_date' => $certificate->issued_date,
            'certificate_url' => $certificate->certificate_url,
            'verification_code' => $certificate->verification_code,
            'verified' => $certificate->verified,
            'exam' => $certificate->exam ? [
                'id' => $certificate->exam->id,
                'title' => $certificate->exam->title,
            ] : null,
            'score' => $certificate->score,
            'pdf_download_url' => $certificate->pdf_path ? Storage::url($certificate->pdf_path) : null,
        ];

        return $this->successResponse($data, 'Certificate details retrieved successfully');
    }

    /**
     * Download certificate PDF
     * GET /certificates/{id}/download
     */
    public function download(Request $request, Certificate $certificate)
    {
        $user = $request->user();

        // Verify ownership
        if ($certificate->user_id !== $user->id) {
            return $this->notFoundResponse();
        }

        if (!$certificate->pdf_path || !Storage::exists($certificate->pdf_path)) {
            return $this->errorResponse('Certificate PDF not found');
        }

        return Storage::download($certificate->pdf_path, $certificate->title . '.pdf');
    }
}
