<?php
/**
 * API Pencarian Nomor Perkara dari SQLite
 * Alternative API yang menggunakan database SQLite lokal
 */

require '../auth.php';
require_login();

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET');
header('Access-Control-Allow-Headers: Content-Type');

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

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

$sqlite_path = '../data/sipp_sync.sqlite';

try {
    // Check if SQLite database exists
    if (!file_exists($sqlite_path)) {
        throw new Exception('Database SQLite belum ada. Lakukan sinkronisasi terlebih dahulu.');
    }
    
    // Connect to SQLite
    $sqlite_pdo = new PDO("sqlite:$sqlite_path", null, null, [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
    ]);
    
    // Search query
    $searchQuery = "%$query%";
    
    $sql = "SELECT 
                nomor_perkara,
                nomor_arsip,
                no_ruang,
                no_lemari,
                no_rak,
                no_berkas
            FROM arsip 
            WHERE nomor_perkara LIKE :query 
            ORDER BY nomor_perkara ASC 
            LIMIT 20";
    
    $stmt = $sqlite_pdo->prepare($sql);
    $stmt->bindValue(':query', $searchQuery, PDO::PARAM_STR);
    
    if ($stmt->execute()) {
        $results = $stmt->fetchAll();
        
        // Format results
        $formatted_results = array_map(function($row) {
            return [
                'nomor_perkara' => $row['nomor_perkara'] ?? '',
                'nomor_arsip' => $row['nomor_arsip'] ?? '',
                'no_ruang' => $row['no_ruang'] ?? '',
                'no_lemari' => $row['no_lemari'] ?? '',
                'no_rak' => $row['no_rak'] ?? '',
                'no_berkas' => $row['no_berkas'] ?? ''
            ];
        }, $results);
        
        echo json_encode($formatted_results);
        
    } else {
        throw new Exception("Query execution failed");
    }
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'error' => $e->getMessage(),
        'source' => 'sqlite'
    ]);
}
?>
