<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Batch;
use App\Models\Peserta;
use Barryvdh\DomPDF\Facade\Pdf;
use SimpleSoftwareIO\QrCode\Facades\QrCode;

class GeneratorController extends Controller
{
    public function index()
    {
        return view('generator.index');
    }

    public function generate(Request $request)
    {
        $request->validate([
            'judul' => 'required|string|max:255',
            'tanggal' => 'required|string|max:255',
            'background' => 'required|image|mimes:jpeg,png,jpg|max:2048',
            'nama_peserta' => 'required|string',
        ]);

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

        $batch = Batch::create([
            'judul' => $request->judul,
            'tanggal' => $request->tanggal,
            'background_path' => $path,
        ]);

        $namaArray = explode("\n", str_replace("\r", "", $request->nama_peserta));
        $namaArray = array_filter(array_map('trim', $namaArray));

        foreach ($namaArray as $index => $nama) {
            $batch->pesertas()->create([
                'nama' => $nama,
                'nomor_sertifikat' => sprintf('%03d/AL-ON/%s/%s', $index + 1, date('m'), date('Y')), // Example format
            ]);
        }

        return redirect()->route('generator.result', $batch->id)->with('success', 'Berhasil generate sertifikat untuk ' . count($namaArray) . ' peserta.');
    }

    public function result(Batch $batch)
    {
        $batch->load('pesertas');
        return view('generator.result', compact('batch'));
    }

    public function download(Peserta $peserta)
    {
        $batch = $peserta->batch;
        
        $qrUrl = route('generator.download', $peserta->id);
        $qrCode = QrCode::size(150)->margin(0)->generate($qrUrl);
        $qrCodeBase64 = 'data:image/svg+xml;base64,' . base64_encode($qrCode);

        $bg_image = null;
        if ($batch->background_path) {
            $path = storage_path('app/public/' . $batch->background_path);
            if (file_exists($path)) {
                $type = pathinfo($path, PATHINFO_EXTENSION);
                $data = file_get_contents($path);
                $bg_image = 'data:image/' . $type . ';base64,' . base64_encode($data);
            }
        }

        $pdf = Pdf::loadView('template_pdf', compact('peserta', 'batch', 'qrCodeBase64', 'bg_image'));
        $pdf->setPaper([0, 0, 1200, 800], 'landscape');

        return $pdf->stream('Sertifikat_' . $peserta->nama . '.pdf');
    }
}
