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

include "connection.php";

// Clear any output buffer
ob_clean();

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

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

try {
    // Get POSTed JSON input
    $json = file_get_contents("php://input");
    $data = json_decode($json, true);
    $text = trim($data['text'] ?? "");

    // Sanitize search text to prevent SQL injection
    Database::setUpConnection();
    if (Database::$connection && !empty($text)) {
        $text = mysqli_real_escape_string(Database::$connection, $text);
    }

    // Build SQL - explicitly select student columns to avoid ambiguous id
    if (!empty($text)) {
        $sql = "
        SELECT 
            student.id,
            student.firstName,
            student.lastName,
            student.nic,
            student.mobile,
            student.email,
            student.password,
            student.registerd_date,
            student.student_status_id,
            student_status.value AS status
        FROM `student` 
        INNER JOIN `student_status` ON `student`.`student_status_id` = `student_status`.`id`
        WHERE student.firstName LIKE '%$text%'
        OR student.lastName LIKE '%$text%'
        OR student.email LIKE '%$text%'
        OR student.nic LIKE '%$text%'
        ";
    } else {
        $sql = "
        SELECT 
            student.id,
            student.firstName,
            student.lastName,
            student.nic,
            student.mobile,
            student.email,
            student.password,
            student.registerd_date,
            student.student_status_id,
            student_status.value AS status
        FROM `student` 
        INNER JOIN `student_status` ON `student`.`student_status_id` = `student_status`.`id`
        ";
    }

    $student_rs = Database::search($sql);

    if ($student_rs->num_rows > 0) {
        while ($row = $student_rs->fetch_assoc()) {
            $response['data'][] = [
                'id' => intval($row['id']), // Ensure it's an integer
                'firstName' => $row['firstName'],
                'lastName' => $row['lastName'],
                'nic' => $row['nic'],
                'mobile' => $row['mobile'],
                'email' => $row['email'],
                'password' => $row['password'],
                'registerd_date' => $row['registerd_date'],
                'status' => $row['status'], // Using the aliased column name
                'student_status_id' => intval($row['student_status_id'])
            ];
        }
        $response['status'] = true;
    } else {
        $response['message'] = "No students found.";
    }
} catch (Exception $e) {
    $response['message'] = "Error: " . $e->getMessage();
}

echo json_encode($response);
exit;