<?php

namespace App\Http\Controllers;

use App\Models\ComplianceCertificate;
use App\Mail\ComplianceReminderMail;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Storage;

class ComplianceCertificateController extends Controller
{
    public function index(Request $request)
    {
        $query = ComplianceCertificate::query()->with(['project', 'uploader'])->latest();

        if ($request->filled('project_id')) {
            $query->where('project_id', $request->project_id);
        }

        $certificates = $query->get();

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

    public function store(Request $request)
    {
        $request->validate([
            'project_id' => 'required|exists:projects,id',
            'file' => 'required|file|mimes:pdf,jpg,jpeg,png,doc,docx|max:10240',
            'issued_by' => 'nullable|string|max:255',
            'issued_date' => 'nullable|date',
            'expires_date' => 'nullable|date|after_or_equal:issued_date',
            'notes' => 'nullable|string',
        ]);

        $file = $request->file('file');
        $path = $file->store('compliance', 'public');

        $certificate = ComplianceCertificate::create([
            'project_id' => $request->project_id,
            'file_path' => $path,
            'file_name' => $file->getClientOriginalName(),
            'issued_by' => $request->issued_by,
            'issued_date' => $request->issued_date,
            'expires_date' => $request->expires_date,
            'notes' => $request->notes,
            'uploaded_by_id' => auth('api')->id(),
        ]);

        $certificate->load(['project', 'uploader']);

        return response()->json([
            'data' => $certificate,
        ], 201);
    }

    public function destroy($id)
    {
        $certificate = ComplianceCertificate::find($id);

        if (!$certificate) {
            return response()->json(['message' => 'Compliance certificate not found'], 404);
        }

        if ($certificate->file_path) {
            Storage::disk('public')->delete($certificate->file_path);
        }

        $certificate->delete();

        return response()->json([
            'message' => 'Compliance certificate deleted successfully',
        ]);
    }

    public function sendReminder(Request $request, $id)
    {
        $certificate = ComplianceCertificate::with(['project', 'uploader'])->find($id);

        if (!$certificate) {
            return response()->json(['message' => 'Compliance certificate not found'], 404);
        }

        $request->validate([
            'to_email'   => 'required|email|max:255',
            'to_name'    => 'nullable|string|max:100',
            'message'    => 'nullable|string|max:3000',
        ]);

        $now = now();
        $expiresDate = $certificate->expires_date ? \Carbon\Carbon::parse($certificate->expires_date) : null;
        $isExpired = $expiresDate && $expiresDate->isPast();
        $expiresSoon = $expiresDate && !$isExpired && $expiresDate->diffInDays($now) <= 30;

        $certData = [
            'project'      => $certificate->project->name ?? 'Unknown Project',
            'name'         => $certificate->file_name ?? 'Compliance Certificate',
            'issued_by'    => $certificate->issued_by,
            'issued_date'  => $certificate->issued_date ? \Carbon\Carbon::parse($certificate->issued_date)->format('d M Y') : null,
            'expires_date' => $expiresDate ? $expiresDate->format('d M Y') : null,
            'notes'        => $certificate->notes,
            'is_expired'   => $isExpired,
            'expires_soon' => $expiresSoon,
        ];

        $senderName = auth('api')->user()->name ?? 'CMS Team';
        $certName   = $certData['name'];
        $subject    = $isExpired
            ? "URGENT: Expired Compliance Certificate — {$certName}"
            : "Action Required: Compliance Certificate Reminder — {$certName}";

        Mail::to($request->to_email, $request->to_name ?? '')
            ->send(new ComplianceReminderMail(
                emailSubject: $subject,
                recipientName: $request->to_name ?? '',
                certData: $certData,
                customMessage: $request->message ?? '',
                senderName: $senderName,
            ));

        return response()->json(['message' => 'Reminder email sent successfully']);
    }
}
