<?php
require_once __DIR__ . '/../includes/auth.php';
requireLoginApi();
header('Content-Type: application/json');

$pdo = getPDO();
$type = $_GET['type'] ?? '';
$q = trim($_GET['q'] ?? '');
$qLike = '%' . $q . '%';

$results = [];

if ($type === 'school') {
    // Scoped to one CLRC at a time — 5,000+ schools district-wide, never dump them all into one dropdown.
    $clrccode = $_GET['clrccode'] ?? '';
    if ($clrccode === '') { echo json_encode([]); exit; }
    $stmt = $pdo->prepare('SELECT schcd, schname, schcat_id FROM school WHERE clrccode = ? AND schname LIKE ? ORDER BY schname LIMIT 50');
    $stmt->execute([$clrccode, $qLike]);
    foreach ($stmt->fetchAll() as $r) {
        $results[] = ['value' => $r['schcd'], 'label' => $r['schname'], 'sublabel' => 'UDISE: ' . $r['schcd'], 'schcat_id' => $r['schcat_id']];
    }
} elseif ($type === 'awc') {
    $stmt = $pdo->prepare('SELECT awc_no, awc_name FROM awc WHERE awc_name LIKE ? OR awc_no LIKE ? ORDER BY awc_name LIMIT 50');
    $stmt->execute([$qLike, $qLike]);
    foreach ($stmt->fetchAll() as $r) {
        $results[] = ['value' => $r['awc_no'], 'label' => $r['awc_name'], 'sublabel' => 'AWC No: ' . $r['awc_no']];
    }
} elseif ($type === 'ifsc') {
    $stmt = $pdo->prepare(
        'SELECT DISTINCT bb.ifsc, b.bank_name FROM bank_branch bb
         JOIN bank b ON b.bank_id = bb.bank_id
         WHERE bb.ifsc LIKE ? ORDER BY bb.ifsc LIMIT 50'
    );
    $stmt->execute([$qLike]);
    foreach ($stmt->fetchAll() as $r) {
        $results[] = ['value' => $r['ifsc'], 'label' => $r['ifsc'], 'sublabel' => $r['bank_name']];
    }
} elseif ($type === 'class') {
    // Classes available for a given school (via its category).
    $schcat = $_GET['schcat_id'] ?? '';
    if ($schcat === '') { echo json_encode([]); exit; }
    $stmt = $pdo->prepare('SELECT DISTINCT sclass FROM class WHERE schcat_id = ? ORDER BY id');
    $stmt->execute([$schcat]);
    foreach ($stmt->fetchAll() as $r) {
        $results[] = ['value' => $r['sclass'], 'label' => $r['sclass']];
    }
} elseif ($type === 'branches_for_ifsc') {
    $ifsc = $_GET['ifsc'] ?? '';
    $stmt = $pdo->prepare(
        'SELECT bb.ifsc_id, bb.branch_name, bb.micr, bb.bank_id, b.bank_name FROM bank_branch bb
         JOIN bank b ON b.bank_id = bb.bank_id
         WHERE bb.ifsc = ?'
    );
    $stmt->execute([$ifsc]);
    foreach ($stmt->fetchAll() as $r) {
        $results[] = [
            'value' => $r['branch_name'], 'label' => $r['branch_name'],
            'sublabel' => $r['micr'] ? ('MICR: ' . $r['micr']) : null,
            'micr' => $r['micr'], 'bank_id' => $r['bank_id'], 'bank_name' => $r['bank_name'],
        ];
    }
}

echo json_encode($results);
