<?php
session_start();

//include("includes/config.php"); // $conn

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');

$errors = [];
$success = "";

$templatePDF = "use_petition.pdf"; // template path
// ============================================================
// PROCESS FORM BEFORE ANY HTML OUTPUT
// ============================================================
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_data = trim($_POST['signature']);

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

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

    if (empty($errors)) {

        // DIRECTORIES
        $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_data)) {
            $data = str_replace("data:image/png;base64,", "", $signature_data);
            $data = str_replace(" ", "+", $data);
            $decoded = base64_decode($data);

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

        // IF STILL NO ERRORS → GENERATE PDF
        if (empty($errors)) {
            try {
                $pdf = new FPDI();

                // IMPORT 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 (With data) ===============
                $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);

                // WRITE TEXT on PAGE 2
                $pdf->SetFont('Helvetica', '', 12);
                $pdf->SetTextColor(0, 0, 0);

                // Name
                $pdf->SetXY(50, 194);
                $pdf->Write(0, $first_name . " " . $last_name);

                // Boys / Girls
                $total = $boys + $girls;

                $pdf->SetXY(113, 77);
                $pdf->Write(0, "$total");
                $day = date("j");
                $month = date("F");

// Example XY values — adjust as needed for your PDF location
                $pdf->SetXY(62, 218);
                $pdf->Write(0, "$day");
                $pdf->SetXY(90, 218);
                $pdf->Write(0, "$month");

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

                // SIGNATURE
                $sig_x = 130;
                $sig_y = 223;
                $sig_w = 50; // small

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

                // PREVIEW MODE (Inline PDF for X/Y testing)
                if (isset($_POST['preview'])) {
                    if (ob_get_length())
                        ob_end_clean();
                    header("Content-Type: application/pdf");
                    $pdf->Output("I", "preview.pdf");
                    exit;
                }

                // NORMAL SAVE MODE
                $pdf_filename = "petition_" . time() . "_" . rand(1000, 9999) . ".pdf";
                $pdf_fullpath = $pdfDir . $pdf_filename;

                $pdf->Output("F", $pdf_fullpath);

                // SAVE TO DB
                $fn = $conn->real_escape_string($first_name);
                $ln = $conn->real_escape_string($last_name);
                $sig = $conn->real_escape_string($signature_file);
                $pf = $conn->real_escape_string($pdf_filename);

                $sql = "INSERT INTO petitions (first_name, last_name, boys, girls, signature_file, pdf_file_path, created_at) 
                        VALUES ('$fn', '$ln', $boys, $girls, '$sig', '$pf', NOW())";

                if ($conn->query($sql)) {
                    $success = "Petition saved successfully!";
                } else {
                    $errors[] = "DB Error: " . $conn->error;
                }
            } catch (Exception $e) {
                $errors[] = "PDF Error: " . $e->getMessage();
            }
        }
    }
}

// ============================================================
// NOW SAFE TO OUTPUT HTML
// ============================================================
include("includes/header.php");
?>

<!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 at: <b>petitionpdf/<?= $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 type="text" name="first_name" required class="form-control">
                        </div>

                        <div class="col-md-6 mb-3">
                            <label>Last Name</label>
                            <input type="text" name="last_name" required class="form-control">
                        </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 & Save</button>

                    <button name="preview" value="1" class="btn btn-warning mt-3" onclick="return confirm('Preview PDF? It will NOT save data.');">
                        Preview PDF (X/Y Test)
                    </button>

                </form>

            </div>
        </div>

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

        <!-- Required jQuery UI -->
        <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 () {

                            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 petition.");
                                    e.preventDefault();
                                }
                            });

                        });
        </script>

    </body>
</html>
