<?php
// Suppress any output before JSON
ob_start();

include "connection.php";
include "validation.php";

// Clear any output buffer
ob_clean();

header("Content-Type: application/json");

$response = [
    "status" => false,
    "message" => ""
];

try {
    $json = file_get_contents("php://input");
    $data = json_decode($json, true);

    if (!$data) {
        $response["message"] = "Invalid request data.";
        echo json_encode($response);
        exit;
    }

    $fname = isset($data["fname"]) ? trim($data["fname"]) : "";
    $lname = isset($data["lname"]) ? trim($data["lname"]) : "";
    $email = isset($data["email"]) ? trim($data["email"]) : "";
    $nic = isset($data["nic"]) ? trim($data["nic"]) : "";
    $mobile = isset($data["mobile"]) ? trim($data["mobile"]) : "";
    $password = isset($data["password"]) ? trim($data["password"]) : "";


if (empty($fname)) {
    $response["message"] = "Please Enter First Name";
} else if (strlen($fname) > 10) {
    $response["message"] = "First name must be less than 10 characters";
} else if (empty($lname)) {
    $response["message"] = "Please Enter Last Name";
} else if (strlen($lname) > 45) {
    $response["message"] = "Last name must be less than 45 characters";
} else if (empty($email)) {
    $response["message"] = "Please Enter Email";
} else if (!isValidEmail($email)) {
    $response["message"] = "Please Enter Valid Email";
} else if (empty($nic)) {
    $response["message"] = "Please Enter NIC Number";
} else if (!isValidNic($nic)) {
    $response["message"] = "Please Enter Valid NIC Number";
} else if (empty($mobile)) {
    $response["message"] = "Please Enter Mobile Number";
} else if (!isValidMobile($mobile)) {
    $response["message"] = "Please Enter Valid Mobile Number";
} else if (empty($password)) {
    $response["message"] = "Please Enter Password";
} else if (!isValidPassword($password)) {
    $response["message"] = "Your Password Must Be min 8 chars, at least 1 uppercase, 1 lowercase, 1 number, 1 special character";
} else {
    // Ensure database connection is established
    Database::setUpConnection();
    
    // Sanitize inputs to prevent SQL injection
    if (Database::$connection) {
        $fname = mysqli_real_escape_string(Database::$connection, $fname);
        $lname = mysqli_real_escape_string(Database::$connection, $lname);
        $email = mysqli_real_escape_string(Database::$connection, $email);
        $nic = mysqli_real_escape_string(Database::$connection, $nic);
        $mobile = mysqli_real_escape_string(Database::$connection, $mobile);
        $password = mysqli_real_escape_string(Database::$connection, $password);
    }

    // Check for existing user (using OR instead of ||)
    $rs = Database::search("SELECT * FROM `student` WHERE `email` = '" . $email . "' OR `nic` = '" . $nic . "'");
    
    if ($rs === false) {
        $response["message"] = "Database error occurred.";
        echo json_encode($response);
        exit;
    }

    $rows = $rs->num_rows;

    if ($rows > 0) {
        $response["message"] = "This Student Already Registered";
    } else {
            $d = new DateTime();
            $tz = new DateTimeZone("Asia/Colombo");
            $d->setTimezone($tz);
            $date = $d->format("Y-m-d H:i:s");

            Database::iud("INSERT INTO `student`(`firstName`,`lastName`,`email`,`nic`,`mobile`,`password`,`verification_code`,`registerd_date`,`student_status_id`) 
            VALUES('" . $fname . "','" . $lname . "','" . $email . "','" . $nic . "','" . $mobile . "','" . $password . "','12345678','" . $date . "','1') ");

            $response["status"] = true;
            $response["message"] = "User Register Success!";
        }
    }

} catch (Exception $e) {
    $response["message"] = "Error: " . $e->getMessage();
} catch (Error $e) {
    $response["message"] = "Error: " . $e->getMessage();
}

echo json_encode($response);
exit;
