<?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');

// Include database configuration
require 'config.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Helper function to sanitize inputs
    function sanitize($data) {
        return htmlspecialchars(stripslashes(trim($data)));
    }

    // Function to validate email
    function validate_email($email) {
        return filter_var($email, FILTER_VALIDATE_EMAIL);
    }

    // Generate unique application ID
    function generate_unique_id($con) {
        while (true) {
            $unique_number = rand(1000000, 9999999);
            $sql = $con->prepare("SELECT * FROM applications WHERE application_id = ?");
            $sql->bind_param("s", $unique_number);
            $sql->execute();
            if ($sql->get_result()->num_rows === 0) {
                return $unique_number;
            }
        }
    }

    // Sanitize and validate inputs
    $required_fields = [
        'user_id', 'auth', 'firstname', 'lastname', 'address', 'city', 'state', 
        'country_code', 'country', 'whatsapp', 'phone', 'email', 'gender', 
        'marital', 'qualification', 'high_school', 'grad_year', 'country_int', 
        'program', 'course_int1', 'intake', 'year', 'scholarship_int', 
        'student_loan', 'flight_ticket_promo', 'health_challenges', 'refused_visa'
    ];

    $inputs = [];
    foreach ($required_fields as $field) {
        if (empty($_POST[$field])) {
            echo json_encode([
                'status' => false,
                'success' => "Missing required field: $field"
            ]);
            exit();
        }
        $inputs[$field] = sanitize($_POST[$field]);
    }

    // Validate specific fields
    if (!validate_email($inputs['email'])) {
        echo json_encode(['status' => false, 'success' => 'Invalid email address']);
        exit();
    }

    if (!is_numeric($inputs['grad_year']) || strlen($inputs['grad_year']) !== 4) {
        echo json_encode(['status' => false, 'success' => 'Invalid graduation year']);
        exit();
    }

    // Check if user exists
    $check_user_query = $con->prepare("SELECT * FROM users WHERE user_id = ? AND auth = ?");
    $check_user_query->bind_param("ss", $inputs['user_id'], $inputs['auth']);
    $check_user_query->execute();
    if ($check_user_query->get_result()->num_rows === 0) {
        echo json_encode(['status' => false, 'success' => 'User does not exist']);
        exit();
    }

    // Generate application ID
    $application_id = generate_unique_id($con);

    // Set default variables
    $inputs['date_reg'] = date("Y-m-d H:i:s"); // Use standard datetime format
    $inputs['status'] = 'Pending';

    // Optional fields
    $optional_fields = ['uni_name', 'course', 'uni_grad_year', 'promo', 'others', 'course_int2', 'course_int3', 'country_visa_refusal'];
    foreach ($optional_fields as $field) {
        $inputs[$field] = isset($_POST[$field]) ? sanitize($_POST[$field]) : '';
    }

    // Promo Code Handling
    $promo = $inputs['promo'];
    $app_paid = '';
    $ad_paid = '';
    $visa_paid = '';

    if (!empty($promo)) {
        $promo_query = $con->prepare("SELECT promo_type FROM promo WHERE code = ?");
        $promo_query->bind_param("s", $promo);
        $promo_query->execute();
        $promo_result = $promo_query->get_result();

        if ($promo_result->num_rows > 0) {
            $promo_type = $promo_result->fetch_assoc()['promo_type'];
            if ($promo_type === "Application") {
                $app_paid = "Paid";
            } elseif ($promo_type === "Admission") {
                $ad_paid = "Paid";
            } elseif ($promo_type === "Visa") {
                $visa_paid = "Paid";
            }
        } else {
            echo json_encode(['status' => false, 'success' => 'Invalid promo code']);
            exit();
        }
    }

    // Insert data into the database
    $insert_query = $con->prepare("
        INSERT INTO applications (
            user_id, auth, application_id, firstname, 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, 
            program, course_int1, course_int2, course_int3, intake, year, scholarship_int, 
            student_loan, flight_ticket_promo, health_challenges, refused_visa, 
            country_visa_refusal, application_fee, admission_fee, visa_fee, status, date_reg
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    ");

    $insert_query->bind_param(
        "ssssssssssssssssssssssssssssssssssssssss",
        $inputs['user_id'], $inputs['auth'], $application_id, $inputs['firstname'], $inputs['lastname'], 
        $inputs['address'], $inputs['city'], $inputs['state'], $inputs['country_code'], $inputs['country'], 
        $inputs['whatsapp'], $inputs['phone'], $inputs['email'], $inputs['gender'], $inputs['marital'], 
        $inputs['qualification'], $inputs['high_school'], $inputs['grad_year'], $inputs['uni_name'], 
        $inputs['course'], $inputs['uni_grad_year'], $inputs['others'], $inputs['country_int'], 
        $inputs['program'], $inputs['course_int1'], $inputs['course_int2'], $inputs['course_int3'], 
        $inputs['intake'], $inputs['year'], $inputs['scholarship_int'], $inputs['student_loan'], 
        $inputs['flight_ticket_promo'], $inputs['health_challenges'], $inputs['refused_visa'], 
        $inputs['country_visa_refusal'], $app_paid, $ad_paid, $visa_paid, $inputs['status'], $inputs['date_reg']
    );

    if ($insert_query->execute()) {
        
         $sql2="SELECT * FROM fees where fee_type = 'Application'";
           $resulta = mysqli_query($con,$sql2) or die(mysqli_error($con));
           $rowa = mysqli_fetch_array($resulta);
           $amount = $rowa['amount'];
          $fee_type = $rowa['fee_type'];
           $payment_status = 'Due';
           $payment_type = $fee_type;
    
        echo json_encode([
            'status' => true,
            'success' => 'Application added successfully',
            'application_id' => $application_id, 
            'amount' =>  $amount,
            'payment_type' => 'Application'

        ]);
    } else {
        echo json_encode(['status' => false, 'success' => 'Database insert failed: ' . $insert_query->error]);
    }

    // Close resources
    $con->close();
} else {
    echo json_encode(['status' => false, 'success' => 'Invalid request method']);
}
?>
