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

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

    // Get and sanitize POST variables
    $required_fields = [
        'user_id', 'auth', 'firstname', 'lastname', 'address',
        'city', 'state', 'country', 'country_code', 'phone', 'email', 
        'country_int1', 'program_type', 
        'course_int1', 'course_int2'
    ];

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

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

    // If any required field is missing, return an error response
    if (!empty($missing_fields)) {
        echo json_encode([
            'status' => false,
            'success' => 'Missing required fields: ' . implode(', ', $missing_fields)
        ]);
        exit();
    }

    $user_id = mysqli_real_escape_string($con, $inputs['user_id']);
    $auth = mysqli_real_escape_string($con, $inputs['auth']);
    $firstname = $inputs['firstname'];
    $lastname = $inputs['lastname'];
    $address = $inputs['address'];
    $city = $inputs['city'];
    $state = $inputs['state'];
    $country = $inputs['country'];
    $country_code = $inputs['country_code'];
    $phone = $inputs['phone'];
    $email = $inputs['email'];
    $country_int1 = $inputs['country_int1'];
    $country_int2 = $inputs['country_int2'];
    $program_type = $inputs['program_type'];
    $course_int1 = $inputs['course_int1'];
    $course_int2 = $inputs['course_int2'];
    $midname = check_input($_POST['midname'] ?? '');
    $whatsapp = check_input($_POST['whatsapp'] ?? '');
    $country_int2 = "None";

    // Check if the user already exists
    $check_user_query = $con->prepare("SELECT * FROM students WHERE phone = ? AND email = ?");
    if (!$check_user_query) {
        echo json_encode(['status' => false, 'success' => 'Database error: ' . $con->error]);
        exit();
    }
    $check_user_query->bind_param("ss", $phone, $email);
    $check_user_query->execute();
    $user_result = $check_user_query->get_result();

    if ($user_result->num_rows > 0) {
        echo json_encode(['status' => false, 'success' => 'Student profile already exists']);
        exit();
    }

    // Generate a unique student ID
    function generate_unique_id($con) {
        $unique_number = rand(1000000, 9999999);
        $sql = $con->query("SELECT * FROM students WHERE student_id = '$unique_number'");
        if ($sql && $sql->num_rows > 0) {
            return generate_unique_id($con);
        }
        return $unique_number;
    }

    $student_id = generate_unique_id($con);

    // Get the current date and time
    date_default_timezone_set("Africa/Lagos");
    $date_reg = date("d-M-Y h:i:s a");

    // Prepare the SQL insert query
    $insert_query = $con->prepare("
        INSERT INTO students (
            user_id, auth, student_id, firstname, lastname, midname, 
            address, city, state, country, country_code, whatsapp, phone, 
            email, country_int, country_int2, program_type, 
            course_int, course_int2, date_reg
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    ");

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

    // Bind parameters
    $insert_query->bind_param(
        "ssssssssssssssssssss",
        $user_id,
        $auth,
        $student_id,
        $firstname,
        $lastname,
        $midname,
        $address,
        $city,
        $state,
        $country,
        $country_code,
        $whatsapp,
        $phone,
        $email,
        $country_int1,
        $country_int2,
        $program_type,
        $course_int1,
        $course_int2,
        $date_reg
    );

    // Execute the insert query
    if ($insert_query->execute()) {
        echo json_encode([
            'status' => true,
            'success' => 'Student added successfully',
            'user_id' => $user_id,
            'student_id' => $student_id,
            'auth' => $auth
        ]);
    } else {
        echo json_encode([
            'status' => false,
            'success' => 'Insert failed: ' . $insert_query->error
        ]);
    }

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