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

session_start();
include "connection.php";
include "validation.php";

// Clear any output buffer
ob_clean();

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

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

try {
    // Get search text if provided
    $json = file_get_contents("php://input");
    $data = json_decode($json, true);
    $searchText = isset($data['text']) ? trim($data['text']) : "";
    
    // Build WHERE clause for search
    $whereClause = "";
    if (!empty($searchText)) {
        $whereClause = "WHERE s.firstName LIKE '%$searchText%'
                        OR s.nic LIKE '%$searchText%'
                        OR s.email LIKE '%$searchText%'
                        OR s.mobile LIKE '%$searchText%'
                        OR sub.title LIKE '%$searchText%'";
    }
    
    // Only show pending requests (request_status_id = 1)
    if (!empty($whereClause)) {
        $whereClause .= " AND sr.request_status_id = '1'";
    } else {
        $whereClause = "WHERE sr.request_status_id = '1'";
    }
    
    $rs = Database::search("
        SELECT sr.id AS request_id, 
               s.firstName, 
               s.nic, 
               s.mobile, 
               s.email, 
               sub.title AS subject, 
               sr.request_status_id
        FROM subject_requests sr
        INNER JOIN student s ON sr.student_id = s.id
        INNER JOIN subject sub ON sr.subject_id = sub.id
        $whereClause
        ORDER BY sr.requested_at DESC
    ");

    $data = [];
    while ($row = $rs->fetch_assoc()) {
        $data[] = $row;
    }

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

echo json_encode($response);
exit;
