<?php
// Enable error reporting (for debugging)
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Database connection
$servername = "localhost";
$username = "uofsedu_Rmn";
$password = "Almnsi@27";
$dbname = "uofsedu_nahrain";
$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$conn->set_charset("utf8mb4");

// Handle form submission
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $name = trim($_POST['name']);
    $phone_number = trim($_POST['phone_number']);
    $amount = trim($_POST['amount']);
    $notes = trim($_POST['notes']);

    // Static values
    $fee_type_id = 2024;
    $reference = generateReference($conn);
    $is_paid = 0;
    $user_id = 8;
    $payment_currency = 'SDG';
    $stamp = 0;
    $order_status = 0;

    // Prepare SQL statement
    $sql = "INSERT INTO other_fees 
            (name, phone_number, fee_type_id, reference, is_paid, amount, user_id, created_at, updated_at, payment_currency, stamp, order_status, notes) 
            VALUES (?, ?, ?, ?, ?, ?, ?, NOW(), NOW(), ?, ?, ?, ?)";

    $stmt = $conn->prepare($sql);

    if ($stmt === false) {
        die("Database Error (prepare): " . $conn->error);
    }

    // Correct bind_param types
    $stmt->bind_param("ssiisidisds", 
        $name, 
        $phone_number, 
        $fee_type_id, 
        $reference, 
        $is_paid, 
        $amount, 
        $user_id, 
        $payment_currency, 
        $stamp, 
        $order_status, 
        $notes
    );

    // Execute and redirect
    if ($stmt->execute()) {
        // Redirect to confirmation.php with ONLY the reference
        header("Location: confirmation.php?reference=" . urlencode($reference));
        exit();
    } else {
        die("Error executing statement: " . $stmt->error);
    }

    $stmt->close();
}

function generateReference($conn) {
    do {
        $reference = "1170" . str_pad(rand(0, 999999), 8, '0', STR_PAD_LEFT);
        $stmt = $conn->prepare("SELECT COUNT(*) FROM other_fees WHERE reference = ?");
        $stmt->bind_param("s", $reference);
        $stmt->execute();
        $stmt->bind_result($check);
        $stmt->fetch();
        $stmt->close();
    } while ($check > 0);
    return $reference;
}

$conn->close();
?>