<?php
include("includes/config.php"); // contains $conn (mysqli)

// USE FPDI + FPDF
use setasign\Fpdi\Fpdi;
use setasign\Fpdi\PdfReader;

require_once('fpdf/fpdf.php');
require_once('fpdf/fpdf_merge.php');
require_once('FPDI/src/autoload.php');

include("includes/header.php");

// ================= PROCESS FORM SUBMISSION ===================
$errors = [];
$success = "";

if ($_SERVER['REQUEST_METHOD'] == 'POST') {

    $first_name = trim($_POST['first_name']);
    $last_name  = trim($_POST['last_name']);
    $boys       = intval($_POST['boys']);
    $girls      = intval($_POST['girls']);
    $signature_dataurl = trim($_POST['signature']);

    if ($first_name == "" || $last_name == "") {
        $errors[] = "Please enter first and last name.";
    }
    if ($signature_dataurl == "") {
        $errors[] = "Please sign before submitting.";
    }

    if (empty($errors)) {

        // FOLDERS
        $signDir = __DIR__ . "/petition_signs/";
        $pdfDir  = __DIR__ . "/petitionpdf/";

        if (!is_dir($signDir)) mkdir($signDir, 0755, true);
        if (!is_dir($pdfDir)) mkdir($pdfDir, 0755, true);

        // ============ SAVE SIGNATURE PNG ============
        $signature_file = null;

        if (preg_match('/^data:image\/png;base64,/', $signature_dataurl)) {

            $signature_base64 = str_replace("data:image/png;base64,", "", $signature_dataurl);
            $signature_base64 = str_replace(" ", "+", $signature_base64);
            $signature_decoded = base64_decode($signature_base64);

            if ($signature_decoded !== false) {
                $signature_file = "sig_" . time() . "_" . rand(1000,9999) . ".png";
                $signature_path = $signDir . $signature_file;
                file_put_contents($signature_path, $signature_decoded);
            } else {
                $errors[] = "Signature decode error.";
            }

        } else {
            $errors[] = "Invalid signature data.";
        }

        // ============ GENERATE PDF =============
// ============ GENERATE PDF =============
if (empty($errors)) {

    $templatePDF = "use_petition.pdf"; // template
    if (!file_exists($templatePDF)) {
        $errors[] = "Template PDF file 'use_petition.pdf' not found.";
    } else {

        try {
            $pdf = new FPDI();

            // Load template
            $pageCount = $pdf->setSourceFile($templatePDF);

            // =========================
            // PAGE 1 (NO changes)
            // =========================
            $tpl1 = $pdf->importPage(1);
            $size1 = $pdf->getTemplateSize($tpl1);

            $orientation1 = $size1['width'] > $size1['height'] ? 'L' : 'P';
            $pdf->AddPage($orientation1, [$size1['width'], $size1['height']]);
            $pdf->useTemplate($tpl1);

            // =========================
            // PAGE 2 (Add data here)
            // =========================
            $tpl2 = $pdf->importPage(2);
            $size2 = $pdf->getTemplateSize($tpl2);

            $orientation2 = $size2['width'] > $size2['height'] ? 'L' : 'P';
            $pdf->AddPage($orientation2, [$size2['width'], $size2['height']]);
            $pdf->useTemplate($tpl2);

            // === Overlay text on PAGE 2 ===
            $pdf->SetFont('Helvetica', '', 12);
            $pdf->SetTextColor(0,0,0);

            // Adjust these XY coordinates according to your PDF
            $pdf->SetXY(40, 90);
            $pdf->Write(0, $first_name . " " . $last_name);

            $pdf->SetXY(40, 100);
            $pdf->Write(0, "Boys: $boys   Girls: $girls");

            // DATE
            $pdf->SetXY(140, 20);
            $pdf->Write(0, date("F j, Y"));

            // === Insert signature ONLY on page 2 ===
            $sig_x = 40;
            $sig_y = 140;
            $sig_w = 40;

            if (file_exists($signature_path)) {
                $pdf->Image($signature_path, $sig_x, $sig_y, $sig_w, 0, 'PNG');
            }

            // Output final PDF
            $pdf_filename = "petition_" . time() . "_" . rand(1000,9999) . ".pdf";
            $pdf_fullpath = $pdfDir . $pdf_filename;
            $pdf->Output("F", $pdf_fullpath);

        } catch (Exception $e) {
            $errors[] = "PDF Error: " . $e->getMessage();
        }
    }
}


        // ============ SAVE TO DATABASE =============
        if (empty($errors)) {

            $first = $conn->real_escape_string($first_name);
            $last  = $conn->real_escape_string($last_name);
            $sig   = $conn->real_escape_string($signature_file);
            $pdfp  = $conn->real_escape_string($pdf_filename);

            $sql = "INSERT INTO petitions (first_name, last_name, boys, girls, signature_file, pdf_file_path, created_at)
                    VALUES ('$first', '$last', $boys, $girls, '$sig', '$pdfp', NOW())";

            if ($conn->query($sql)) {
                $success = "Petition Successfully Saved!";
            } else {
                $errors[] = "DB Insert Error: " . $conn->error;
            }
        }
    }
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>School Petition</title>
    <link rel="stylesheet" href="css/jquery.signature.css">
</head>

<body class="bg-light">
<?php include("uselink.php"); ?>

<div class="container mt-5">
    <div class="card p-4 shadow-lg">
        <h3 class="mb-4">School Petition Form</h3>

        <?php if (!empty($errors)): ?>
            <div class="alert alert-danger">
                <?php foreach ($errors as $e) echo "<div>$e</div>"; ?>
            </div>
        <?php endif; ?>

        <?php if ($success): ?>
            <div class="alert alert-success">
                <?= $success ?><br>
                PDF saved: <b>petitionpdf/<?= htmlspecialchars($pdf_filename) ?></b>
            </div>
        <?php endif; ?>

        <form method="POST" id="petitionForm">

            <div class="row">
                <div class="col-md-6 mb-3">
                    <label>First Name</label>
                    <input name="first_name" type="text" class="form-control" required>
                </div>

                <div class="col-md-6 mb-3">
                    <label>Last Name</label>
                    <input name="last_name" type="text" class="form-control" required>
                </div>
            </div>

            <div class="row">
                <div class="col-md-6 mb-3">
                    <label>Boys</label>
                    <input type="number" name="boys" class="form-control" value="0">
                </div>

                <div class="col-md-6 mb-3">
                    <label>Girls</label>
                    <input type="number" name="girls" class="form-control" value="0">
                </div>
            </div>

            <!-- SIGNATURE -->
            <div class="mb-3">
                <label>Signature</label><br>
                <div id="signaturePad" style="border:1px solid #ccc; width:300px; height:120px;"></div>
                <textarea id="signature" name="signature" style="display:none;"></textarea>
                <button type="button" id="clearSignature" class="btn btn-danger btn-sm mt-2">Clear</button>
            </div>

            <button class="btn btn-primary mt-3">Submit Petition</button>

        </form>
    </div>
</div>


<!--<script src="js/jquery-3.6.0.min.js"></script>-->

<!-- jQuery UI REQUIRED -->
<script src="https://code.jquery.com/ui/1.13.2/jquery-ui.min.js"></script>

<!--<script src="js/jquery.ui.touch-punch.min.js"></script>
<script src="js/jquery.signature.js"></script>-->

<script>
$(function(){

    // Signature pad
    var sig = $('#signaturePad').signature({
        syncField: '#signature',
        syncFormat: 'PNG'
    });

    $('#clearSignature').click(function(){
        sig.signature('clear');
        $('#signature').val('');
    });

    $('#petitionForm').submit(function(e){
        if($('#signature').val() == ""){
            alert("Please sign the form.");
            e.preventDefault();
        }
    });

});
</script>

</body>
</html>
