<?php
header('Content-Type: application/json');
require '../auth.php';
require '../db.php';

// Check if user is logged in
if (!is_logged_in()) {
    http_response_code(401);
    echo json_encode(['error' => 'Unauthorized']);
    exit;
}

// Get search query
$query = trim($_GET['q'] ?? '');

if (strlen($query) < 2) {
    echo json_encode([]);
    exit;
}

// Konfigurasi database SIPP
$sipp_config = [
    'host' => '192.168.1.240',
    'dbname' => 'sippbaco',
    'username' => 'pnwtp',
    'password' => 'pnwtp2019',
    'port' => 3306
];

$results = [];

try {
    // Koneksi ke database SIPP
    $dsn = "mysql:host={$sipp_config['host']};port={$sipp_config['port']};dbname={$sipp_config['dbname']};charset=utf8mb4";
    $sipp_db = new PDO($dsn, $sipp_config['username'], $sipp_config['password']);
    $sipp_db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    // Search nomor perkara in arsip table
    $sql = "SELECT DISTINCT nomor_perkara, nomor_arsip, no_ruang, no_lemari, no_rak, no_berkas 
            FROM arsip 
            WHERE nomor_perkara LIKE ? AND nomor_perkara != '' 
            ORDER BY nomor_perkara ASC 
            LIMIT 10";
    
    $stmt = $sipp_db->prepare($sql);
    $stmt->execute(['%' . $query . '%']);
    $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(['error' => 'Database error']);
    exit;
}

echo json_encode($results);
?>
