<?php
/**
 * Debug API for Nomor Perkara Autocomplete (No Auth Required)
 * For testing purposes only
 */

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

// Debug mode - no auth required
$debug_mode = true;

if (!$debug_mode) {
    require '../auth.php';
    require_login();
}

try {
    // Get search query
    $query = isset($_GET['q']) ? trim($_GET['q']) : '';
    
    if (empty($query)) {
        echo json_encode([]);
        exit;
    }
    
    // Debug info
    error_log("Debug API: Searching for '$query'");
    
    // Include SIPP database connection
    require '../sipp_db.php';
    
    // Get SIPP database connection
    $sipp_pdo = connectSipp();
    
    if ($sipp_pdo === null) {
        throw new Exception('SIPP database connection failed');
    }
    
    // Prepare search query
    $searchQuery = "%$query%";
    
    // SQL query with LIMIT for performance
    $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 = $sipp_pdo->prepare($sql);
    $stmt->bindValue(':query', $searchQuery, PDO::PARAM_STR);
    
    if ($stmt->execute()) {
        $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        // Debug info
        error_log("Debug API: Found " . count($results) . " results");
        
        // Format results for autocomplete
        $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 {
        $errorInfo = $stmt->errorInfo();
        throw new Exception("Database query failed: " . $errorInfo[2]);
    }
    
} catch (Exception $e) {
    error_log("Debug API Error: " . $e->getMessage());
    
    echo json_encode([
        'error' => $e->getMessage(),
        'debug' => [
            'query' => $query ?? 'Not set',
            'file' => __FILE__,
            'line' => __LINE__
        ]
    ]);
}
?>
