<?php
require 'vendor/autoload.php';

use PhpOffice\PhpSpreadsheet\IOFactory;
use setasign\Fpdi\Fpdi;

if (!file_exists('uploads')) mkdir('uploads');
if (!file_exists('output')) mkdir('output');
if (!file_exists('output/participanti')) mkdir('output/participanti');

function convert($text) {
    return iconv('UTF-8', 'windows-1250//TRANSLIT', $text);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['excel_file'])) {
    $x = floatval($_POST['x'] ?? 0);
    $y = floatval($_POST['y'] ?? 100);
    $templatePath = 'templates/' . basename($_POST['template']);
    $tmpPath = $_FILES['excel_file']['tmp_name'];
    $excelPath = 'uploads/' . uniqid() . '.xlsx';
    move_uploaded_file($tmpPath, $excelPath);

    $spreadsheet = IOFactory::load($excelPath);
    $rows = $spreadsheet->getActiveSheet()->toArray();

    $emailList = [];

    foreach ($rows as $i => $row) {
        if ($i === 0) continue; // skip header

        $nr = trim($row[0] ?? '');
        $nume = trim($row[1] ?? '');
        $email = trim($row[7] ?? ''); // Coloana H

        if ($nr === '' || $nume === '') continue;

        $pdf = new Fpdi();
        $pdf->AddPage('L', 'A4');
        $pdf->setSourceFile($templatePath);
        $tplIdx = $pdf->importPage(1);
        $pdf->useTemplate($tplIdx);

        $pdf->SetFont('Times', 'B', 26);
        $pdf->SetTextColor(17, 45, 78);
        $text = convert(strtoupper($nume));
        $pdf->SetXY(0, $y);
        $pdf->Cell(297, 10, $text, 0, 0, 'C');

        $pdf->SetFont('Times', '', 12);
        $pdf->SetTextColor(0, 0, 0);
        $pdf->SetXY(35, 175);
        $pdf->Cell(0, 10, convert("Nr. {$nr} / 21.06.2025"), 0, 0, 'L');

        $safeName = preg_replace('/[\/\\\\:*?"<>|]/u', '_', $nume);
        $pdfPath = "output/lectori/{$safeName}.pdf";
        $pdf->Output('F', $pdfPath);

        // Validare și colectare email
        if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $emailList[] = [
                'name' => $nume,
                'email' => $email,
                'pdf' => $pdfPath
            ];
        }
    }

    // Salvăm lista de emailuri pentru trimitere ulterioară
    file_put_contents('output/email_list.json', json_encode($emailList));

    // Redirecționează către pagina cu loader
    header('Location: email_process_loader.php');
    exit;
}
