<?php
// Database connection
$servername = "localhost";  // Your server name
$username = "uofsedu_Rmn";  // Your MySQL username
$password = "Almnsi@27";  // Your MySQL password
$dbname = "uofsedu_registration";  // Your MySQL database name

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

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

// Set charset to utf8mb4 to support Arabic characters
$conn->set_charset("utf8mb4");

// Insert Data into the Database
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Get form inputs and trim whitespace
    $name = trim($_POST['name']);
    $phone_number = trim($_POST['phone_number']);
    $amount = trim($_POST['amount']);

    // Validate that the name contains at least four words
    if (substr_count($name, ' ') < 3) {
        die("Error: Name must contain at least four words.");
    }

    $fee_type_id = 2024; // Default value
    $reference = generateReference($conn); // Call function to generate reference
    $is_paid = 0; // Default value
    $user_id = 8; // Default value
    $payment_currency = 'SDG'; // Default value
    $stamp = 0; // Default value
    $order_stsus = 0; // Default value for 'order_stsus'

    // Prepare the 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_stsus) 
            VALUES (?, ?, ?, ?, ?, ?, ?, NOW(), NOW(), ?, ?, ?)";
    
    $stmt = $conn->prepare($sql);

    // Check if statement preparation was successful
    if ($stmt === false) {
        die("Error preparing statement: " . $conn->error);
    }

    // Bind the parameters to the statement
    $stmt->bind_param("ssissdssis", $name, $phone_number, $fee_type_id, $reference, $is_paid, $amount, $user_id, $payment_currency, $stamp, $order_stsus);

    // Execute the statement
    if ($stmt->execute()) {
        // Redirect to confirmation page with reference, amount, and name
        header("Location: confirmation.php?reference=$reference&amount=$amount&name=" . urlencode($name));
        exit();
    } else {
        // Output detailed error message if execution fails
        echo "Error executing statement: " . $stmt->error;
    }

    // Close the statement
    $stmt->close();
}

// Function to generate unique reference number
function generateReference($conn) {
    do {
        $reference = "1170" . str_pad(rand(0, 999999), 8, '0', STR_PAD_LEFT);
        $check = $conn->query("SELECT COUNT(*) FROM other_fees WHERE reference='$reference'")->fetch_row()[0];
    } while ($check > 0);
    return $reference;
}

// Close the database connection
$conn->close();
?>
