<?php
include("includes/config.php"); 

// 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");
// If admin is logged in
if (isset($_SESSION['user'])) {
    include("includes/uselink.php");     // SHOW FULL ADMIN MENU
} else {
    // Parent view (no menu, only brand)
    ?>
    <nav class="navbar navbar-dark bg-dark px-3">
        <span class="navbar-brand mb-0 h4 text-white">MCS</span>
    </nav>
    <?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 =============
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 )
            // =========================
            $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);

            // ===  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");

                $pdf->SetXY(62, 218);
                $pdf->Write(0, "$day");
                $pdf->SetXY(90, 218);
                $pdf->Write(0, "$month");

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

            // 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">

<div class="container mt-5 mb-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>
            </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><br>
                <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>
