<?php
// Constants
define("STUDENT_PRICE", 450);
define("STAFF_PRICE", 750);
define("VISITOR_PRICE", 100);
define("MAX_CAPACITY", 100);

// Start session to store data across submissions
session_start();

// Initialize arrays if not set
if (!isset($_SESSION['permitTypes'])) {
    $_SESSION['permitTypes'] = [];
    $_SESSION['permitPrices'] = [];
}

// Handle form submission
if ($_SERVER["REQUEST_METHOD"] == "POST") {

    $age = $_POST['age'];
    $type = $_POST['type'];

    if ($age < 18) {
        $message = "❌ Permit denied: Must be 18 or older.";
    } else if (count($_SESSION['permitTypes']) >= MAX_CAPACITY) {
        $message = "❌ Parking capacity reached.";
    } else {

        switch ($type) {
            case "Student":
                $_SESSION['permitTypes'][] = "Student";
                $_SESSION['permitPrices'][] = STUDENT_PRICE;
                break;

            case "Staff":
                $_SESSION['permitTypes'][] = "Staff";
                $_SESSION['permitPrices'][] = STAFF_PRICE;
                break;

            case "Visitor":
                $_SESSION['permitTypes'][] = "Visitor";
                $_SESSION['permitPrices'][] = VISITOR_PRICE;
                break;
        }

        $message = "✅ Permit issued successfully!";
    }
}

// Calculate summary
$studentCount = 0;
$staffCount = 0;
$visitorCount = 0;
$totalRevenue = 0;

for ($i = 0; $i < count($_SESSION['permitTypes']); $i++) {
    $type = $_SESSION['permitTypes'][$i];
    $price = $_SESSION['permitPrices'][$i];

    if ($type == "Student") $studentCount++;
    if ($type == "Staff") $staffCount++;
    if ($type == "Visitor") $visitorCount++;

    $totalRevenue += $price;
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Parking Permit System</title>
</head>
<body>

<h2>Parking Permit Application</h2>

<form method="post">
    Age: <input type="number" name="age" required><br><br>

    Permit Type:
    <select name="type">
        <option value="Student">Student (R450)</option>
        <option value="Staff">Staff (R750)</option>
        <option value="Visitor">Visitor (R100)</option>
    </select><br><br>

    <input type="submit" value="Apply">
</form>

<p><?php if (isset($message)) echo $message; ?></p>

<h3>Summary</h3>
<p>Student Permits Sold: <?php echo $studentCount; ?></p>
<p>Staff Permits Sold: <?php echo $staffCount; ?></p>
<p>Visitor Permits Sold: <?php echo $visitorCount; ?></p>
<p>Total Revenue: R<?php echo $totalRevenue; ?></p>

</body>
</html>