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

if (!isset($_SESSION['user'])) {
    header("Location: login.php");
    exit;
}
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']);

    // Basic validation
    if ($first_name == "" || $last_name == "") {
        $errors[] = "Please enter first and last name.";
    }

    // Check hardcopy file
    if (!isset($_FILES['hardcopy_file']) || $_FILES['hardcopy_file']['error'] != 0) {
        $errors[] = "Please upload hard copy file (PDF, JPG, PNG).";
    }

    // Validate file allowed types
    $allowed_types = ['pdf', 'jpg', 'jpeg', 'png'];
    $file_ext = strtolower(pathinfo($_FILES['hardcopy_file']['name'], PATHINFO_EXTENSION));

    if (!in_array($file_ext, $allowed_types)) {
        $errors[] = "Invalid file format. Allowed: PDF, JPG, JPEG, PNG";
    }

    // If all good → save file
    if (empty($errors)) {

        $uploadDir = "petitionpdf/";
        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0755, true);
        }

        $newFileName = "hardcopy_" . time() . "_" . rand(1000,9999) . "." . $file_ext;
        $targetPath = $uploadDir . $newFileName;

        if (!move_uploaded_file($_FILES['hardcopy_file']['tmp_name'], $targetPath)) {
            $errors[] = "File upload failed! Check folder permissions.";
        }

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

            $first = $conn->real_escape_string($first_name);
            $last  = $conn->real_escape_string($last_name);

            // signature_file is NULL for hardcopy upload
            $sig   = "NULL";

            // pdf_file_path stores uploaded file name
            $pdfp  = $conn->real_escape_string($newFileName);

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

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

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

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

<div class="container mt-5 mb-5">
    <div class="card p-4 shadow-lg">
        <h3 class="mb-4">Upload Hard Copy Petition</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 ?></div>
        <?php endif; ?>

        <form method="POST" enctype="multipart/form-data">

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

            <!-- HARD COPY UPLOAD -->
            <div class="mb-3">
                <label>Upload Hard Copy (PDF / JPG / PNG)</label>
                <input type="file" name="hardcopy_file" class="form-control" required>
            </div>

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

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

<!-- jQuery UI (kept as per your file) -->
<script src="https://code.jquery.com/ui/1.13.2/jquery-ui.min.js"></script>

</body>
</html>
