<?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 = "mpayuofsedu_nusuuser";
$password = "]7kVl65q)b?E8zJC";
$dbname = "mpayuofsedu_nusu";

$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']);

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

    // Validate phone number (digits only, 10–15 characters)
    if (!preg_match("/^\d{10,15}$/", $phone_number)) {
        die("Error: Invalid phone number format.");
    }

    // Validate amount
    if (!is_numeric($amount) || $amount <= 0) {
        die("Error: Invalid amount.");
    }

    // 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()) {
        header("Location: confirmation.php?reference=$reference&amount=$amount&name=" . urlencode($name));
        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();
?>