<?php
session_start();
include('includes/config.php');

// Security check
if (strlen($_SESSION['alogin']) == 0) {
    http_response_code(403);
    echo json_encode(['status' => 'error', 'message' => 'Unauthorized']);
    exit;
}

$type = $_GET['type'] ?? '';
$q = trim($_GET['q'] ?? '');

$results = [];

switch ($type) {
    case 'category':
        $results[] = ['id' => 'nocat', 'text' => 'No Category'];
        $sql = "SELECT id, CategoryName AS name 
                FROM tblcategory 
                WHERE CategoryName LIKE :search AND is_deleted = 0
                ORDER BY CategoryName ASC 
                LIMIT 20";
        break;

    case 'rack':
        // We want to return rack_no as the value (so client sends rack_no, not id)
        $results[] = ['id' => 'norack', 'text' => 'No Cupboard'];

        // Return distinct rack_no values (deduped). `name` = rack_no.
        $sql = "SELECT DISTINCT rack_no AS name
                FROM tbl_racks
                WHERE rack_no LIKE :search
                ORDER BY rack_no ASC
                LIMIT 50";
        break;

    case 'author':
        $results[] = ['id' => 'noauthor', 'text' => 'No Author'];
        $sql = "SELECT id, AuthorName AS name 
                FROM tblauthors 
                WHERE AuthorName LIKE :search AND is_deleted = 0
                ORDER BY AuthorName ASC 
                LIMIT 20";
        break;

    case 'department':
        $results[] = ['id' => 'nodept', 'text' => 'No Department'];
        $sql = "SELECT department_id AS id, department_name AS name 
                FROM tbldepartment 
                WHERE department_name LIKE :search AND is_deleted = 0
                ORDER BY department_name ASC 
                LIMIT 20";
        break;

    case 'degree':
        $results[] = ['id' => 'nodegree', 'text' => 'No Degree'];
        $sql = "SELECT degree_id AS id, degree_name AS name 
                FROM tbldegree 
                WHERE degree_name LIKE :search AND is_deleted = 0
                ORDER BY degree_name ASC 
                LIMIT 20";
        break;

    default:
        echo json_encode([]);
        exit;
}

$query = $dbh->prepare($sql);
$search = "%$q%";
$query->bindParam(':search', $search, PDO::PARAM_STR);
$query->execute();
$data = $query->fetchAll(PDO::FETCH_ASSOC);

foreach ($data as $row) {
    // For rack case 'name' is rack_no; we want id = rack_no so client sends rack_no
    $results[] = ['id' => $row['name'], 'text' => $row['name']];
}

header('Content-Type: application/json');
echo json_encode($results);

?>