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

if (!isset($_SESSION['user'])) {
    echo "Unauthorized!";
    exit;
}

$petition_id = intval($_POST['petition_id']);

if ($petition_id <= 0) {
    die("Invalid Petition ID!");
}

// Ensure petition exists
$check = mysqli_query($conn, "SELECT id FROM petitions WHERE id = $petition_id LIMIT 1");
if (mysqli_num_rows($check) == 0) {
    die("Invalid Petition ID!");
}

// File upload check
if ($_FILES['hardcopy']['error'] !== 0) {
    die("File upload error!");
}

$folder = "hardcopies/";
if (!file_exists($folder)) {
    mkdir($folder, 0777, true);
}

$ext = strtolower(pathinfo($_FILES['hardcopy']['name'], PATHINFO_EXTENSION));
$allowed = ['pdf','jpg','jpeg','png'];

if (!in_array($ext, $allowed)) {
    die("Only PDF/JPG/PNG allowed!");
}

$filename = "hardcopy_" . $petition_id . "." . $ext;
$path = $folder . $filename;

if (move_uploaded_file($_FILES['hardcopy']['tmp_name'], $path)) {

    mysqli_query($conn,
        "UPDATE petitions SET hardcopy_path='$path' WHERE id=$petition_id"
    );

    echo "<script>
        alert('Hard Copy Uploaded!');
        window.location='index.php';
    </script>";

} else {
    echo "Upload failed!";
}
?>
