<?php
include("includes/config.php");
require_once('tcpdf/tcpdf.php');  // TCPDF include

// --- GET FORM VALUES ---
$first_name      = mysqli_real_escape_string($conn, $_POST['first_name']);
$last_name       = mysqli_real_escape_string($conn, $_POST['last_name']);
$boys            = (int)$_POST['boys'];
$girls           = (int)$_POST['girls'];
$signature_text  = mysqli_real_escape_string($conn, $_POST['signature_text']);

// --- INSERT INTO DATABASE ---
$sql = "INSERT INTO petitions (first_name, last_name, boys, girls, signature_text, created_at) 
        VALUES ('$first_name', '$last_name', '$boys', '$girls', '$signature_text', NOW())";

if (mysqli_query($conn, $sql)) {

    // GET LAST INSERT ID
    $petition_id = mysqli_insert_id($conn);

    // === PDF FOLDER PATH ===
    $pdf_folder = __DIR__ . "/pdfs/";
    if (!file_exists($pdf_folder)) {
        mkdir($pdf_folder, 0777, true);
    }

    // === PDF FILE PATH ===
    $pdf_file = $pdf_folder . "petition_" . $petition_id . ".pdf";
    $relative_path = "pdfs/petition_" . $petition_id . ".pdf";

    // SAVE PDF PATH IN DATABASE
    mysqli_query($conn, "
        UPDATE petitions 
        SET pdf_path = '$relative_path' 
        WHERE id = $petition_id
    ");

    // === TCPDF PDF GENERATION ===
    $pdf = new TCPDF();
    $pdf->SetCreator('Petition System');
    $pdf->SetAuthor('School Petition');
    $pdf->SetTitle('Petition Form');
    $pdf->AddPage();

    $html = '
<h2 style="text-align:center; margin-bottom:15px;">School Petition</h2>

<table border="1" cellpadding="8" cellspacing="0" width="100%" style="border-collapse:collapse; font-size:14px;">
    <tr>
        <td width="30%"><strong>Name</strong></td>
        <td>'.$first_name.' '.$last_name.'</td>
    </tr>
    <tr>
        <td><strong>Boys</strong></td>
        <td>'.$boys.'</td>
    </tr>
    <tr>
        <td><strong>Girls</strong></td>
        <td>'.$girls.'</td>
    </tr>
    <tr>
        <td><strong>Signature</strong></td>
        <td>'.$signature_text.'</td>
    </tr>
    <tr>
        <td><strong>Date</strong></td>
        <td>'.date("d-m-Y").'</td>
    </tr>
</table>

<br><br>
<p style="text-align:center; font-size:12px;">Thank you for submitting the petition.</p>
';

    $pdf->writeHTML($html, true, false, true, false, '');

    // SAVE PDF
    $pdf->Output($pdf_file, 'F');

    echo "
    <div style='padding:20px; font-family:Arial;'>
        <h3>Petition Submitted Successfully!</h3>
        <p>PDF Saved: <b>$relative_path</b></p>
        <a href='index.php'>Go Back</a>
    </div>";

} else {
    echo 'Error: ' . mysqli_error($conn);
}

mysqli_close($conn);
?>
