<?php
namespace App\Http\Controllers;

use App\Models\Athlete;
use App\Models\Competition;
use App\Models\CertificateTemplate;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use ZipArchive;

class CertificateController extends Controller
{
    // Manage template UI
    public function index(Competition $competition)
    {
        $template = $competition->certificateTemplate;
        $athletes = $competition->athletes()->orderBy('last_name')->get();
        return view('certificates.index', compact('competition', 'template', 'athletes'));
    }

    // Save / update template
    public function storeTemplate(Competition $competition, Request $request)
    {
        $data = $request->validate([
            'title' => 'required|string|max:200',
            'background' => 'nullable|image|mimes:png,jpg,jpeg|max:4096',
            'custom_fields' => 'nullable|array',
            'style' => 'nullable|array',
        ]);

        $template = $competition->certificateTemplate ?: new CertificateTemplate(['competition_id' => $competition->id]);
        $template->title = $data['title'];
        $template->custom_fields = $data['custom_fields'] ?? [];
        $template->style = $data['style'] ?? [];

        if ($request->hasFile('background')) {
            $file = $request->file('background');
            $filename = time() . '_' . $file->getClientOriginalName();

            // Move to public/certificates/
            $file->move(public_path('certificates'), $filename);

            // Save relative path (for asset() helper)
            $template->background_path = 'certificates/' . $filename;
        }

        $template->save();
        return back()->with('success', 'Certificate template saved.');
    }

    // Quick on-screen preview (single athlete)
    public function preview(Competition $competition, Request $request)
    {
        $athlete = $competition->athletes()->first();
        $template = $competition->certificateTemplate;
        abort_unless($template, 404, 'No template yet.');
        return view('certificates.preview', compact('competition', 'template', 'athlete'));
    }

    // Export selected IDs -> single PDF file
    public function exportSelected(Competition $competition, Request $request)
    {
        $ids = collect($request->input('athlete_ids', []))->filter()->unique()->values();
        abort_if($ids->isEmpty(), 422, 'No athletes selected.');

        $athletes = $competition->athletes()->whereIn('athletes.id', $ids)->get();
        return $this->renderPdf($competition, $athletes, filename: 'certificates_selected.pdf');
    }

    // Export all athletes -> batch & zip when large
    public function exportAll(Competition $competition, Request $request)
    {
        $batchSize = (int) $request->input('batch_size', 40);
        $athletes = $competition->athletes()->orderBy('last_name')->get();
        if ($athletes->count() <= $batchSize) {
            return $this->renderPdf($competition, $athletes, filename: 'certificates_all.pdf');
        }

        // Split into chunks and zip
        $tmpDir = storage_path('app/tmp/' . Str::uuid());
        if (!is_dir($tmpDir)) {
            mkdir($tmpDir, 0775, true);
        }

        $chunks = $athletes->chunk($batchSize);
        $index = 1;
        foreach ($chunks as $chunk) {
            $pdf = \PDF::loadView('certificates.pdf', [
                'competition' => $competition,
                'template' => $competition->certificateTemplate,
                'athletes' => $chunk,
            ])->setPaper('a4', 'landscape');
            $filename = sprintf('certificates_%02d.pdf', $index++);
            file_put_contents($tmpDir . '/' . $filename, $pdf->output());
        }

        $zipPath = storage_path('app/tmp/' . Str::uuid() . '.zip');
        $zip = new ZipArchive();
        $zip->open($zipPath, ZipArchive::CREATE | ZipArchive::OVERWRITE);
        foreach (scandir($tmpDir) as $f) {
            if ($f === '.' || $f === '..') {
                continue;
            }
            $zip->addFile($tmpDir . '/' . $f, $f);
        }
        $zip->close();

        // Cleanup directory after response finishes
        return response()->download($zipPath, 'certificates_batches.zip')->deleteFileAfterSend(true);
    }

    // Core renderer (multi-page PDF; one athlete per page)
    protected function renderPdf(Competition $competition, $athletes, string $filename)
    {
        $template = $competition->certificateTemplate;
        abort_unless($template, 404, 'No certificate template configured.');

        $pdf = \PDF::loadView('certificates.pdf', [
            'competition' => $competition,
            'template' => $template,
            'athletes' => $athletes,
        ])->setPaper('a4', 'landscape');

        return $pdf->download($filename);
    }
}
