<?php
session_start();
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
header("Access-Control-Allow-Headers: X-Requested-With");
header('Content-Type: application/json; charset=utf-8');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    include 'config.php';

    function check_input($par) {
        return htmlspecialchars(stripslashes(trim($par)));
    }

    // Required fields
    $required_fields = [
        'user_id', 'auth', 'exam_type', 'firstname', 'lastname', 'address',
        'city', 'state', 'country_code', 'country', 'whatsapp', 'phone', 'email', 'gender', 'marital',
        'qualification', 'high_school', 'grad_year', 'country_int', 'reason', 'exam_month', 'english_period', 'scholarship_int',
        'student_loan', 'health_challenges', 'refused_visa'
    ];

    $missing_fields = [];
    $inputs = [];

    // Validate and sanitize inputs
    foreach ($required_fields as $field) {
        if (!isset($_POST[$field]) || trim($_POST[$field]) === '') {
            $missing_fields[] = $field;
        } else {
            $inputs[$field] = check_input($_POST[$field]);
        }
    }

    if (!empty($missing_fields)) {
        echo json_encode([
            'status' => false,
            'message' => 'Missing required fields: ' . implode(', ', $missing_fields)
        ]);
        exit();
    }

    extract($inputs);

    // Check if the user exists
    $check_user_query = $con->prepare("SELECT * FROM users WHERE user_id = ? AND auth = ?");
    if (!$check_user_query) {
        echo json_encode(['status' => false, 'message' => 'Database error: ' . $con->error]);
        exit();
    }

    $check_user_query->bind_param("ss", $user_id, $auth);
    $check_user_query->execute();
    $user_result = $check_user_query->get_result();

    if ($user_result->num_rows === 0) {
        echo json_encode(['status' => false, 'message' => 'User does not exist']);
        exit();
    }

    // Generate a unique application ID
    function generate_unique_id($con) {
        $unique_number = rand(1000000, 9999999);
        $check_query = $con->query("SELECT 1 FROM exam_applications WHERE application_id = '$unique_number'");
        return ($check_query && $check_query->num_rows > 0) ? generate_unique_id($con) : $unique_number;
    }

    $application_id = generate_unique_id($con);

    // Get current date and time
    date_default_timezone_set("Africa/Lagos");
    $date_reg = date("Y-m-d\TH:i:s"); // ISO 8601 format

    // Insert application data
    $insert_query = $con->prepare("
        INSERT INTO exam_applications (
            user_id, auth, application_id, exam_type, firstname, midname, lastname,
            address, city, state, country_code, country, whatsapp, phone, 
            email, gender, marital, qualification, high_school, grad_year, 
            uni_name, course, uni_grad_year, others, country_int, reason_writing,
            exam_month, english_study_time, scholarship_int, student_loan, 
            health_challenges, refused_visa, country_visa_refusal, status, date_reg
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    ");

    if (!$insert_query) {
        echo json_encode(['status' => false, 'message' => 'Database error: ' . $con->error]);
        exit();
    }

    $others = check_input($_POST['others']);
    $country_visa_refusal = check_input($_POST['country_visa_refusal']);
    $uni_name = check_input($_POST['uni_name']);
    $course = check_input($_POST['course']);
    $midname = check_input($_POST['midname']);
    $unigrad_year = check_input($_POST['unigrad_year']);

    $status = 'Pending';
    $insert_query->bind_param(
        "sssssssssssssssssssssssssssssssssss",
        $user_id, $auth, $application_id, $exam_type, $firstname, $midname, $lastname,
        $address, $city, $state, $country_code, $country, $whatsapp, $phone, $email,
        $gender, $marital, $qualification, $high_school, $grad_year,
        $uni_name, $course, $unigrad_year, $others, $country_int, $reason,
        $exam_month, $english_period, $scholarship_int, $student_loan,
        $health_challenges, $refused_visa, $country_visa_refusal, $status, $date_reg
    );

    $sql = "SELECT * FROM fees WHERE fee_type = '$exam_type'";
    $resulta = mysqli_query($con, $sql) or die(mysqli_error($con));
    $num = mysqli_num_rows($resulta);

    if ($num == 0) {
        $message = "No Fee Available at the moment";
    } else {
        $rowa = mysqli_fetch_array($resulta);
        $amount = $rowa['amount'];
        $message = "Application added successfully";
    }

    if ($insert_query->execute()) {
        echo json_encode([
            'status' => true,
            'message' => $message,
            'application_id' => $application_id,
            'amount' => $amount,
            'payment_type' => $exam_type
        ]);
    } else {
        echo json_encode([
            'status' => false,
            'message' => 'Insert failed: ' . $insert_query->error
        ]);
    }

    $check_user_query->close();
    $insert_query->close();
    $con->close();
} else {
    echo json_encode(['status' => false, 'message' => 'Invalid request method']);
}
?>
