<?php
/**
 * Global Search API
 * Returns JSON results for global search functionality
 */

require_once __DIR__ . '/config/auth.php';
requireLogin();

header('Content-Type: application/json');

$db = getDB();
$query = $_GET['q'] ?? '';
$results = [];

if (strlen($query) >= 2) {
    $searchTerm = '%' . $query . '%';
    
    try {
        // Search in anggota (members)
        $stmt = $db->prepare("
            SELECT id, nama_lengkap, nik, no_anggota 
            FROM anggota 
            WHERE nama_lengkap LIKE ? OR nik LIKE ? OR no_anggota LIKE ?
            LIMIT 5
        ");
        if ($stmt) {
            $stmt->execute([$searchTerm, $searchTerm, $searchTerm]);
            $anggota = $stmt->fetchAll();
            
            foreach ($anggota as $a) {
                $results[] = [
                    'type' => 'anggota',
                    'title' => $a['nama_lengkap'],
                    'subtitle' => 'No. Anggota: ' . $a['no_anggota'] . ' | NIK: ' . $a['nik'],
                    'icon' => 'user',
                    'url' => APP_URL . '/anggota.php?search=' . urlencode($a['no_anggota'])
                ];
            }
        }
    } catch (Exception $e) {
        // Silently skip if anggota table doesn't exist
    }
    
    try {
        // Search in simpanan (savings transactions)
        $stmt = $db->prepare("
            SELECT s.id, s.kode_transaksi, s.jumlah, a.nama_lengkap, s.tanggal
            FROM simpanan s
            LEFT JOIN anggota a ON s.anggota_id = a.id
            WHERE s.kode_transaksi LIKE ? OR a.nama_lengkap LIKE ?
            ORDER BY s.tanggal DESC
            LIMIT 3
        ");
        if ($stmt) {
            $stmt->execute([$searchTerm, $searchTerm]);
            $simpanan = $stmt->fetchAll();
            
            foreach ($simpanan as $s) {
                $results[] = [
                    'type' => 'simpanan',
                    'title' => 'Simpanan: ' . $s['kode_transaksi'],
                    'subtitle' => $s['nama_lengkap'] . ' - Rp ' . number_format($s['jumlah'], 0, ',', '.'),
                    'icon' => 'piggy-bank',
                    'url' => APP_URL . '/simpanan.php?search=' . urlencode($s['kode_transaksi'])
                ];
            }
        }
    } catch (Exception $e) {
        // Silently skip if simpanan table doesn't exist
    }
    
    try {
        // Search in pinjaman (loans)
        $stmt = $db->prepare("
            SELECT p.id, p.kode_pinjaman, p.jumlah_pinjaman, a.nama_lengkap, p.status
            FROM pinjaman p
            LEFT JOIN anggota a ON p.anggota_id = a.id
            WHERE p.kode_pinjaman LIKE ? OR a.nama_lengkap LIKE ?
            ORDER BY p.tanggal DESC
            LIMIT 3
        ");
        if ($stmt) {
            $stmt->execute([$searchTerm, $searchTerm]);
            $pinjaman = $stmt->fetchAll();
            
            foreach ($pinjaman as $p) {
                $statusLabel = $p['status'] == 'lunas' ? 'Lunas' : 'Belum Lunas';
                $results[] = [
                    'type' => 'pinjaman',
                    'title' => 'Pinjaman: ' . $p['kode_pinjaman'],
                    'subtitle' => $p['nama_lengkap'] . ' - Rp ' . number_format($p['jumlah_pinjaman'], 0, ',', '.') . ' (' . $statusLabel . ')',
                    'icon' => 'hand-holding-usd',
                    'url' => APP_URL . '/pinjaman.php?search=' . urlencode($p['kode_pinjaman'])
                ];
            }
        }
    } catch (Exception $e) {
        // Silently skip if pinjaman table doesn't exist
    }
    
    // Limit total results
    $results = array_slice($results, 0, 10);
}

echo json_encode($results);?>