<?php
// Start session
session_start();

// Include database connection
require_once "../config/connection.php";

// Check if account is active
$admin_id = $_SESSION['user_id'];
$stmt = $conn->prepare("SELECT status FROM admin_users_surabaya WHERE id = ?");
$stmt->bind_param("i", $admin_id);
$stmt->execute();
$admin_data = $stmt->get_result()->fetch_assoc();
$stmt->close();

// Set JSON header for regular requests
header('Content-Type: application/json');

try {
    // Check if status data requested (untuk pop-up cards)
    if (isset($_GET['status_data'])) {
        $status_type = $_GET['status_data'];
        
        if ($status_type === 'dipinjam') {
            $query = "
                SELECT 
                    csi.kode_barang,
                    csi.stock_number,
                    csi.rack_no,
                    mcp.code_color,
                    b.nama_buyer,
                    cc.component_name,
                    bu.nama_borrower,
                    bu.nik,
                    bu.lokasi_posisi,
                    st.reservation_number,
                    st.tanggal_transaksi,
                    st.tanggal_pengembalian,
                    DATEDIFF(NOW(), st.tanggal_pengembalian) as hari_terlambat
                FROM color_stock_items_surabaya csi
                JOIN master_color_panel_surabaya mcp ON csi.color_id = mcp.id
                JOIN buyers_surabaya b ON mcp.buyer_id = b.id
                JOIN color_components_surabaya cc ON csi.component_id = cc.id
                JOIN transaction_items_surabaya ti ON csi.id = ti.stock_item_id
                JOIN stock_transactions_surabaya st ON ti.transaction_id = st.id
                JOIN borrower_users_surabaya bu ON st.borrower_id = bu.id
                WHERE csi.status = 'Dipinjam' 
                AND ti.dikembalikan = 0
                ORDER BY st.tanggal_pengembalian ASC
            ";
            
            $result = $conn->query($query);
            $total = $result->num_rows;
            
            $html = '<div class="space-y-4">';
            
            if ($total > 0) {
                while ($row = $result->fetch_assoc()) {
                    // Calculate if overdue
                    $is_overdue = $row['hari_terlambat'] > 0;
                    $card_class = $is_overdue ? 'border-l-4 border-red-500 bg-red-50' : 'border-l-4 border-orange-500 bg-orange-50';
                    
                    $html .= '<div class="' . $card_class . ' p-4 rounded-lg border">';
                    $html .= '<div class="grid grid-cols-1 md:grid-cols-3 gap-4">';
                    
                    // Informasi Barang
                    $html .= '<div>';
                    $html .= '<h4 class="font-semibold text-gray-800 mb-2"><i class="fas fa-box mr-2 text-blue-600"></i>Informasi Barang</h4>';
                    $html .= '<div class="text-sm space-y-1">';
                    $html .= '<div><span class="font-medium">Kode:</span> <span class="font-mono font-bold text-blue-600">' . htmlspecialchars($row['kode_barang']) . '</span></div>';
                    $html .= '<div><span class="font-medium">Stock #:</span> ' . $row['stock_number'] . '</div>';
                    $html .= '<div><span class="font-medium">Barang:</span> ' . htmlspecialchars($row['nama_buyer'] . ' ' . $row['code_color']) . '</div>';
                    $html .= '<div><span class="font-medium">Component:</span> ' . htmlspecialchars($row['component_name']) . '</div>';
                    $html .= '<div><span class="font-medium">Rack:</span> ' . htmlspecialchars($row['rack_no']) . '</div>';
                    $html .= '</div>';
                    $html .= '</div>';
                    
                    // Informasi Peminjam
                    $html .= '<div>';
                    $html .= '<h4 class="font-semibold text-gray-800 mb-2"><i class="fas fa-user mr-2 text-green-600"></i>Peminjam</h4>';
                    $html .= '<div class="text-sm space-y-1">';
                    $html .= '<div><span class="font-medium">Nama:</span> ' . htmlspecialchars($row['nama_borrower']) . '</div>';
                    $html .= '<div><span class="font-medium">NIK:</span> ' . htmlspecialchars($row['nik']) . '</div>';
                    $html .= '<div><span class="font-medium">Lokasi:</span> ' . htmlspecialchars($row['lokasi_posisi']) . '</div>';
                    $html .= '<div><span class="font-medium">No. Reservasi:</span> <span class="font-mono">' . htmlspecialchars($row['reservation_number']) . '</span></div>';
                    $html .= '</div>';
                    $html .= '</div>';
                    
                    // Timeline & Status
                    $html .= '<div>';
                    $html .= '<h4 class="font-semibold text-gray-800 mb-2"><i class="fas fa-clock mr-2 text-purple-600"></i>Timeline</h4>';
                    $html .= '<div class="text-sm space-y-1">';
                    $html .= '<div><span class="font-medium">Dipinjam:</span> ' . date('d/m/Y H:i', strtotime($row['tanggal_transaksi'])) . '</div>';
                    $html .= '<div><span class="font-medium">Target Kembali:</span> ' . date('d/m/Y H:i', strtotime($row['tanggal_pengembalian'])) . '</div>';
                    
                    if ($is_overdue) {
                        $html .= '<div class="text-red-600 font-bold bg-red-100 p-2 rounded">';
                        $html .= '<i class="fas fa-exclamation-triangle mr-1"></i>';
                        $html .= 'Terlambat ' . $row['hari_terlambat'] . ' hari';
                        $html .= '</div>';
                    } else {
                        $hari_tersisa = -$row['hari_terlambat'];
                        $html .= '<div class="text-green-600 font-medium bg-green-100 p-2 rounded">';
                        $html .= '<i class="fas fa-clock mr-1"></i>';
                        $html .= 'Sisa ' . $hari_tersisa . ' hari';
                        $html .= '</div>';
                    }
                    $html .= '</div>';
                    $html .= '</div>';
                    
                    $html .= '</div>';
                    $html .= '</div>';
                }
            } else {
                $html .= '<div class="text-center text-gray-500 py-8">';
                $html .= '<i class="fas fa-check-circle text-4xl mb-2 text-green-400"></i>';
                $html .= '<p class="text-lg font-medium">Tidak ada barang yang sedang dipinjam</p>';
                $html .= '<p class="text-sm">Semua barang sudah dikembalikan</p>';
                $html .= '</div>';
            }
            
            $html .= '</div>';
            
        } elseif ($status_type === 'bermasalah') {
            $query = "
                SELECT 
                    csi.kode_barang,
                    csi.stock_number,
                    csi.rack_no,
                    csi.status,
                    csi.tanggal_kedaluwarsa,
                    mcp.code_color,
                    b.nama_buyer,
                    cc.component_name,
                    (SELECT bu.nama_borrower FROM transaction_items_surabaya ti 
                     JOIN stock_transactions_surabaya st ON ti.transaction_id = st.id 
                     JOIN borrower_users_surabaya bu ON st.borrower_id = bu.id 
                     WHERE ti.stock_item_id = csi.id 
                     ORDER BY st.tanggal_transaksi DESC LIMIT 1) as peminjam_terakhir,
                    (SELECT ti.tanggal_kembali FROM transaction_items_surabaya ti 
                     JOIN stock_transactions_surabaya st ON ti.transaction_id = st.id 
                     WHERE ti.stock_item_id = csi.id AND ti.dikembalikan = 1 
                     ORDER BY ti.tanggal_kembali DESC LIMIT 1) as terakhir_dikembalikan,
                    (SELECT ti.kondisi_kembali FROM transaction_items_surabaya ti 
                     JOIN stock_transactions_surabaya st ON ti.transaction_id = st.id 
                     WHERE ti.stock_item_id = csi.id AND ti.dikembalikan = 1 
                     ORDER BY ti.tanggal_kembali DESC LIMIT 1) as kondisi_terakhir
                FROM color_stock_items_surabaya csi
                JOIN master_color_panel_surabaya mcp ON csi.color_id = mcp.id
                JOIN buyers_surabaya b ON mcp.buyer_id = b.id
                JOIN color_components_surabaya cc ON csi.component_id = cc.id
                WHERE csi.status IN ('Rusak', 'Expired', 'Hilang')
                ORDER BY 
                    CASE 
                        WHEN csi.status = 'Hilang' THEN 1
                        WHEN csi.status = 'Rusak' THEN 2
                        WHEN csi.status = 'Expired' THEN 3
                    END,
                    csi.kode_barang ASC
            ";
            
            $result = $conn->query($query);
            $total = $result->num_rows;
            
            $html = '<div class="space-y-4">';
            
            if ($total > 0) {
                while ($row = $result->fetch_assoc()) {
                    // Set card styling based on status
                    $card_class = '';
                    $status_icon = '';
                    $status_color = '';
                    
                    switch($row['status']) {
                        case 'Hilang':
                            $card_class = 'border-l-4 border-yellow-500 bg-yellow-50';
                            $status_icon = 'fas fa-question-circle text-yellow-600';
                            $status_color = 'bg-yellow-100 text-yellow-800';
                            break;
                        case 'Rusak':
                            $card_class = 'border-l-4 border-red-500 bg-red-50';
                            $status_icon = 'fas fa-exclamation-triangle text-red-600';
                            $status_color = 'bg-red-100 text-red-800';
                            break;
                        case 'Expired':
                            $card_class = 'border-l-4 border-purple-500 bg-purple-50';
                            $status_icon = 'fas fa-calendar-times text-purple-600';
                            $status_color = 'bg-purple-100 text-purple-800';
                            break;
                    }
                    
                    $html .= '<div class="' . $card_class . ' p-4 rounded-lg border">';
                    $html .= '<div class="grid grid-cols-1 md:grid-cols-3 gap-4">';
                    
                    // Informasi Barang
                    $html .= '<div>';
                    $html .= '<div class="flex items-center mb-2">';
                    $html .= '<i class="' . $status_icon . ' mr-2"></i>';
                    $html .= '<h4 class="font-semibold text-gray-800">Informasi Barang</h4>';
                    $html .= '</div>';
                    $html .= '<div class="text-sm space-y-1">';
                    $html .= '<div><span class="font-medium">Kode:</span> <span class="font-mono font-bold text-blue-600">' . htmlspecialchars($row['kode_barang']) . '</span></div>';
                    $html .= '<div><span class="font-medium">Stock #:</span> ' . $row['stock_number'] . '</div>';
                    $html .= '<div><span class="font-medium">Barang:</span> ' . htmlspecialchars($row['nama_buyer'] . ' ' . $row['code_color']) . '</div>';
                    $html .= '<div><span class="font-medium">Component:</span> ' . htmlspecialchars($row['component_name']) . '</div>';
                    $html .= '<div><span class="font-medium">Rack:</span> ' . htmlspecialchars($row['rack_no']) . '</div>';
                    $html .= '<div>';
                    $html .= '<span class="font-medium">Status:</span> ';
                    $html .= '<span class="inline-flex px-2 py-1 text-xs font-semibold rounded-full ' . $status_color . '">' . htmlspecialchars($row['status']) . '</span>';
                    $html .= '</div>';
                    $html .= '</div>';
                    $html .= '</div>';
                    
                    // Informasi Tanggal
                    $html .= '<div>';
                    $html .= '<h4 class="font-semibold text-gray-800 mb-2"><i class="fas fa-calendar mr-2 text-blue-600"></i>Informasi Tanggal</h4>';
                    $html .= '<div class="text-sm space-y-1">';
                    if ($row['status'] == 'Expired') {
                        $html .= '<div><span class="font-medium">Kedaluwarsa:</span> ' . date('d/m/Y', strtotime($row['tanggal_kedaluwarsa'])) . '</div>';
                        $hari_expired = floor((strtotime('now') - strtotime($row['tanggal_kedaluwarsa'])) / (60*60*24));
                        $html .= '<div class="text-red-600 bg-red-100 p-2 rounded"><span class="font-medium">Expired:</span> ' . $hari_expired . ' hari yang lalu</div>';
                    }
                    
                    if ($row['terakhir_dikembalikan']) {
                        $html .= '<div><span class="font-medium">Terakhir Dikembalikan:</span> ' . date('d/m/Y H:i', strtotime($row['terakhir_dikembalikan'])) . '</div>';
                        
                        if ($row['kondisi_terakhir']) {
                            $kondisi_color = '';
                            switch($row['kondisi_terakhir']) {
                                case 'Baik': $kondisi_color = 'text-green-600'; break;
                                case 'Rusak': $kondisi_color = 'text-red-600'; break;
                                case 'Hilang': $kondisi_color = 'text-yellow-600'; break;
                            }
                            $html .= '<div><span class="font-medium">Kondisi Saat Dikembalikan:</span> <span class="' . $kondisi_color . ' font-bold">' . htmlspecialchars($row['kondisi_terakhir']) . '</span></div>';
                        }
                    }
                    $html .= '</div>';
                    $html .= '</div>';
                    
                    // Peminjam Terakhir & Rekomendasi Admin
                    $html .= '<div>';
                    $html .= '<h4 class="font-semibold text-gray-800 mb-2"><i class="fas fa-user-clock mr-2 text-green-600"></i>Peminjam & Tindakan</h4>';
                    $html .= '<div class="text-sm space-y-2">';
                    if ($row['peminjam_terakhir']) {
                        $html .= '<div class="bg-white p-2 rounded border">';
                        $html .= '<span class="font-medium">Peminjam Terakhir:</span><br>';
                        $html .= htmlspecialchars($row['peminjam_terakhir']);
                        $html .= '</div>';
                    } else {
                        $html .= '<div class="text-gray-500 italic bg-gray-100 p-2 rounded">Belum pernah dipinjam</div>';
                    }
                    
                    // Rekomendasi action dengan styling khusus admin
                    $html .= '<div class="bg-blue-50 border border-blue-200 p-3 rounded">';
                    $html .= '<span class="font-medium text-blue-800"><i class="fas fa-lightbulb mr-1"></i>Rekomendasi Admin:</span><br>';
                    switch($row['status']) {
                        case 'Hilang':
                            $html .= '<span class="text-yellow-700 text-sm">• Lakukan investigasi mendalam<br>• Kontak peminjam terakhir<br>• Pertimbangkan penggantian</span>';
                            break;
                        case 'Rusak':
                            $html .= '<span class="text-red-700 text-sm">• Evaluasi tingkat kerusakan<br>• Tentukan biaya perbaikan vs penggantian<br>• Update status di sistem</span>';
                            break;
                        case 'Expired':
                            $html .= '<span class="text-purple-700 text-sm">• Segera buang barang expired<br>• Buat jadwal produksi baru<br>• Review cycle time</span>';
                            break;
                    }
                    $html .= '</div>';
                    $html .= '</div>';
                    $html .= '</div>';
                    
                    $html .= '</div>';
                    $html .= '</div>';
                }
            } else {
                $html .= '<div class="text-center text-gray-500 py-8">';
                $html .= '<i class="fas fa-check-circle text-4xl mb-2 text-green-400"></i>';
                $html .= '<p class="text-lg font-medium">Tidak ada barang bermasalah</p>';
                $html .= '<p class="text-sm">Semua barang dalam kondisi baik</p>';
                $html .= '</div>';
            }
            
            $html .= '</div>';
        }
        
        echo json_encode([
            'success' => true,
            'html' => $html,
            'total' => $total
        ]);
        exit();
    }

    // Check if only stats requested
    if (isset($_GET['stats_only']) && $_GET['stats_only'] == '1') {
        $stats_query = "
            SELECT 
                COUNT(*) as total_barang,
                SUM(CASE WHEN status = 'Tersedia' THEN 1 ELSE 0 END) as tersedia,
                SUM(CASE WHEN status = 'Dipinjam' THEN 1 ELSE 0 END) as dipinjam,
                SUM(CASE WHEN status IN ('Rusak', 'Expired', 'Hilang') THEN 1 ELSE 0 END) as bermasalah
            FROM color_stock_items_surabaya
        ";

        $stats_result = $conn->query($stats_query);
        $stats = $stats_result->fetch_assoc();

        echo json_encode([
            'success' => true,
            'stats' => $stats
        ]);
        exit();
    }

    // Check if detail requested
    if (isset($_GET['detail_id'])) {
        $detail_id = intval($_GET['detail_id']);
        
        $detail_query = "
            SELECT 
                csi.*,
                mcp.code_color,
                mcp.deskripsi as color_description,
                b.nama_buyer,
                cc.component_name,
                (SELECT COUNT(*) FROM transaction_items_surabaya ti 
                 JOIN stock_transactions_surabaya st ON ti.transaction_id = st.id 
                 WHERE ti.stock_item_id = csi.id) as total_peminjaman,
                (SELECT MAX(ti.tanggal_kembali) FROM transaction_items_surabaya ti 
                 JOIN stock_transactions_surabaya st ON ti.transaction_id = st.id 
                 WHERE ti.stock_item_id = csi.id AND ti.dikembalikan = 1) as terakhir_dikembalikan
            FROM color_stock_items_surabaya csi
            JOIN master_color_panel_surabaya mcp ON csi.color_id = mcp.id
            JOIN buyers_surabaya b ON mcp.buyer_id = b.id
            JOIN color_components_surabaya cc ON csi.component_id = cc.id
            WHERE csi.id = ?
        ";

        $detail_stmt = $conn->prepare($detail_query);
        $detail_stmt->bind_param("i", $detail_id);
        $detail_stmt->execute();
        $detail_result = $detail_stmt->get_result();

        if ($detail_result->num_rows > 0) {
            $detail = $detail_result->fetch_assoc();
            
            // Get last borrower info
            $last_borrower_query = "
                SELECT 
                    bu.nama_borrower,
                    bu.nik,
                    bu.lokasi_posisi,
                    st.tanggal_transaksi,
                    st.tanggal_pengembalian,
                    ti.tanggal_kembali,
                    ti.kondisi_kembali,
                    ti.catatan,
                    ti.foto_bukti,
                    ti.foto_pengembalian,
                    ti.status_waktu,
                    st.reservation_number
                FROM transaction_items_surabaya ti
                JOIN stock_transactions_surabaya st ON ti.transaction_id = st.id
                JOIN borrower_users_surabaya bu ON st.borrower_id = bu.id
                WHERE ti.stock_item_id = ?
                ORDER BY st.tanggal_transaksi DESC
                LIMIT 1
            ";

            $last_stmt = $conn->prepare($last_borrower_query);
            $last_stmt->bind_param("i", $detail_id);
            $last_stmt->execute();
            $last_result = $last_stmt->get_result();
            $last_borrower = $last_result->num_rows > 0 ? $last_result->fetch_assoc() : null;

            // Generate detail HTML with Admin enhancements
            $html = '<div class="grid grid-cols-1 lg:grid-cols-2 gap-6">';
            
            // Informasi Barang
            $html .= '<div class="space-y-4">';
            $html .= '<h4 class="text-lg font-semibold text-gray-800 border-b pb-2"><i class="fas fa-box mr-2 text-blue-600"></i>Informasi Barang</h4>';
            
            $html .= '<div class="bg-gray-50 p-4 rounded-lg border">';
            $html .= '<div class="grid grid-cols-2 gap-4 text-sm">';
            $html .= '<div><span class="font-medium text-gray-600">Kode Barang:</span><br><span class="text-lg font-mono font-bold text-blue-600">' . htmlspecialchars($detail['kode_barang']) . '</span></div>';
            $html .= '<div><span class="font-medium text-gray-600">Stock Number:</span><br><span class="text-lg font-bold">' . $detail['stock_number'] . '</span></div>';
            $html .= '<div><span class="font-medium text-gray-600">Buyer:</span><br>' . htmlspecialchars($detail['nama_buyer']) . '</div>';
            $html .= '<div><span class="font-medium text-gray-600">Color Code:</span><br>' . htmlspecialchars($detail['code_color']) . '</div>';
            $html .= '<div><span class="font-medium text-gray-600">Component:</span><br>' . htmlspecialchars($detail['component_name']) . '</div>';
            $html .= '<div><span class="font-medium text-gray-600">Lokasi:</span><br>' . htmlspecialchars($detail['lokasi']) . '</div>';
            $html .= '<div><span class="font-medium text-gray-600">Rack:</span><br>' . htmlspecialchars($detail['rack_no']) . '</div>';
            
            // Status badge with admin info
            $status_color = '';
            $status_icon = '';
            switch($detail['status']) {
                case 'Tersedia': 
                    $status_color = 'bg-green-100 text-green-800'; 
                    $status_icon = 'fas fa-check-circle';
                    break;
                case 'Dipinjam': 
                    $status_color = 'bg-orange-100 text-orange-800'; 
                    $status_icon = 'fas fa-hand-holding';
                    break;
                case 'Rusak': 
                    $status_color = 'bg-red-100 text-red-800'; 
                    $status_icon = 'fas fa-exclamation-triangle';
                    break;
                case 'Expired': 
                    $status_color = 'bg-yellow-100 text-yellow-800'; 
                    $status_icon = 'fas fa-calendar-times';
                    break;
                case 'Hilang': 
                    $status_color = 'bg-purple-100 text-purple-800'; 
                    $status_icon = 'fas fa-question-circle';
                    break;
                default: 
                    $status_color = 'bg-gray-100 text-gray-800';
                    $status_icon = 'fas fa-circle';
            }
            
            $html .= '<div><span class="font-medium text-gray-600">Status:</span><br>';
            $html .= '<span class="inline-flex items-center px-2 py-1 text-xs font-semibold rounded-full ' . $status_color . '">';
            $html .= '<i class="' . $status_icon . ' mr-1"></i>' . htmlspecialchars($detail['status']);
            $html .= '</span></div>';
            $html .= '</div>';
            $html .= '</div>';

            // Tanggal informasi dengan admin insights
            $html .= '<div class="bg-blue-50 border border-blue-200 p-4 rounded-lg">';
            $html .= '<h5 class="font-medium text-gray-800 mb-2"><i class="fas fa-calendar mr-2 text-blue-600"></i>Informasi Tanggal</h5>';
            $html .= '<div class="text-sm space-y-1">';
            $html .= '<div><span class="font-medium">Dibuat:</span> ' . date('d/m/Y', strtotime($detail['tanggal_pembuatan'])) . '</div>';
            $html .= '<div><span class="font-medium">Kedaluwarsa:</span> ' . date('d/m/Y', strtotime($detail['tanggal_kedaluwarsa'])) . '</div>';
            
            // Calculate days until expiry
            $days_until_expiry = floor((strtotime($detail['tanggal_kedaluwarsa']) - strtotime('now')) / (60*60*24));
            if ($days_until_expiry < 0) {
                $html .= '<div class="text-red-600 font-medium bg-red-100 p-2 rounded">⚠️ Sudah expired ' . abs($days_until_expiry) . ' hari</div>';
            } elseif ($days_until_expiry <= 30) {
                $html .= '<div class="text-yellow-600 font-medium bg-yellow-100 p-2 rounded">⚠️ Akan expired dalam ' . $days_until_expiry . ' hari</div>';
            } else {
                $html .= '<div class="text-green-600 bg-green-100 p-2 rounded">✓ Masih valid ' . $days_until_expiry . ' hari lagi</div>';
            }
            
            if ($detail['terakhir_dikembalikan']) {
                $html .= '<div><span class="font-medium">Terakhir Dikembalikan:</span> ' . date('d/m/Y H:i', strtotime($detail['terakhir_dikembalikan'])) . '</div>';
            }
            $html .= '<div class="bg-white p-2 rounded border">';
            $html .= '<span class="font-medium">Total Peminjaman:</span> <span class="text-lg font-bold text-purple-600">' . $detail['total_peminjaman'] . '</span> kali';
            $html .= '</div>';
            $html .= '</div>';
            $html .= '</div>';

            $html .= '</div>';

            // Informasi Peminjam Terakhir dengan admin details
            $html .= '<div class="space-y-4">';
            $html .= '<h4 class="text-lg font-semibold text-gray-800 border-b pb-2"><i class="fas fa-user-clock mr-2 text-green-600"></i>Peminjam Terakhir</h4>';
            
            if ($last_borrower) {
                $html .= '<div class="bg-gray-50 border p-4 rounded-lg">';
                $html .= '<div class="grid grid-cols-1 gap-4 text-sm">';
                $html .= '<div class="flex justify-between items-start">';
                $html .= '<div><span class="font-medium text-gray-600">Nama Peminjam:</span><br><span class="text-lg font-bold">' . htmlspecialchars($last_borrower['nama_borrower']) . '</span></div>';
                $html .= '<div><span class="font-medium text-gray-600">NIK:</span><br><span class="font-mono">' . htmlspecialchars($last_borrower['nik']) . '</span></div>';
                $html .= '</div>';
                $html .= '<div><span class="font-medium text-gray-600">Lokasi Posisi:</span><br>' . htmlspecialchars($last_borrower['lokasi_posisi']) . '</div>';
                $html .= '<div class="bg-white p-2 rounded border">';
                $html .= '<span class="font-medium text-gray-600">No. Reservasi:</span><br><span class="font-mono text-blue-600">' . htmlspecialchars($last_borrower['reservation_number']) . '</span>';
                $html .= '</div>';
                $html .= '</div>';
                $html .= '</div>';

                // Timeline peminjaman dengan admin styling
                $html .= '<div class="bg-indigo-50 border border-indigo-200 p-4 rounded-lg">';
                $html .= '<h5 class="font-medium text-gray-800 mb-3"><i class="fas fa-history mr-2 text-indigo-600"></i>Timeline Peminjaman</h5>';
                $html .= '<div class="space-y-3">';
                
                // Tanggal pinjam
                $html .= '<div class="flex items-center">';
                $html .= '<div class="w-3 h-3 bg-blue-500 rounded-full mr-3"></div>';
                $html .= '<div class="text-sm">';
                $html .= '<span class="font-medium">Dipinjam:</span> ' . date('d/m/Y H:i', strtotime($last_borrower['tanggal_transaksi']));
                $html .= '</div>';
                $html .= '</div>';
                
                // Tanggal seharusnya kembali
                if ($last_borrower['tanggal_pengembalian']) {
                    $html .= '<div class="flex items-center">';
                    $html .= '<div class="w-3 h-3 bg-yellow-500 rounded-full mr-3"></div>';
                    $html .= '<div class="text-sm">';
                    $html .= '<span class="font-medium">Seharusnya Kembali:</span> ' . date('d/m/Y H:i', strtotime($last_borrower['tanggal_pengembalian']));
                    $html .= '</div>';
                    $html .= '</div>';
                }
                
                // Tanggal aktual kembali
                if ($last_borrower['tanggal_kembali']) {
                    $kondisi_color = '';
                    switch($last_borrower['kondisi_kembali']) {
                        case 'Baik': $kondisi_color = 'text-green-600'; break;
                        case 'Rusak': $kondisi_color = 'text-red-600'; break;
                        case 'Hilang': $kondisi_color = 'text-yellow-600'; break;
                    }
                    
                    $html .= '<div class="flex items-center">';
                    $html .= '<div class="w-3 h-3 bg-green-500 rounded-full mr-3"></div>';
                    $html .= '<div class="text-sm">';
                    $html .= '<span class="font-medium">Dikembalikan:</span> ' . date('d/m/Y H:i', strtotime($last_borrower['tanggal_kembali']));
                    $html .= '<br><span class="font-medium">Kondisi:</span> <span class="' . $kondisi_color . ' font-bold">' . htmlspecialchars($last_borrower['kondisi_kembali']) . '</span>';
                    
                    // Status waktu
                    if ($last_borrower['status_waktu']) {
                        $waktu_color = $last_borrower['status_waktu'] == 'tepat' ? 'text-green-600' : 'text-red-600';
                        $waktu_text = $last_borrower['status_waktu'] == 'tepat' ? 'Tepat Waktu' : 'Terlambat';
                        $html .= '<br><span class="font-medium">Status:</span> <span class="' . $waktu_color . ' font-bold">' . $waktu_text . '</span>';
                    }
                    $html .= '</div>';
                    $html .= '</div>';
                } else {
                    $html .= '<div class="flex items-center">';
                    $html .= '<div class="w-3 h-3 bg-red-500 rounded-full mr-3"></div>';
                    $html .= '<div class="text-sm text-red-600 font-medium">❌ Belum Dikembalikan</div>';
                    $html .= '</div>';
                }
                
                $html .= '</div>';
                $html .= '</div>';

                // Catatan dan foto dengan admin access
                if ($last_borrower['catatan'] || $last_borrower['foto_bukti'] || $last_borrower['foto_pengembalian']) {
                    $html .= '<div class="bg-yellow-50 border border-yellow-200 p-4 rounded-lg">';
                    $html .= '<h5 class="font-medium text-gray-800 mb-3"><i class="fas fa-camera mr-2 text-yellow-600"></i>Dokumentasi</h5>';
                    
                    if ($last_borrower['catatan']) {
                        $html .= '<div class="mb-3">';
                        $html .= '<span class="font-medium text-gray-600">Catatan:</span><br>';
                        $html .= '<div class="bg-white p-3 rounded border text-sm">' . htmlspecialchars($last_borrower['catatan']) . '</div>';
                        $html .= '</div>';
                    }
                    
                    $html .= '<div class="flex flex-wrap gap-2">';
                    if ($last_borrower['foto_bukti']) {
                        $html .= '<button onclick="showPhoto(\'' . htmlspecialchars($last_borrower['foto_bukti']) . '\', \'Foto Bukti Kondisi\', \'Kondisi barang saat dikembalikan\')" class="px-3 py-2 bg-blue-100 text-blue-700 rounded text-sm hover:bg-blue-200 border border-blue-300">';
                        $html .= '<i class="fas fa-image mr-1"></i>Foto Bukti';
                        $html .= '</button>';
                    }
                    
                    if ($last_borrower['foto_pengembalian']) {
                        $html .= '<button onclick="showPhoto(\'' . htmlspecialchars($last_borrower['foto_pengembalian']) . '\', \'Foto Pengembalian\', \'Dokumentasi pengembalian ke rack\')" class="px-3 py-2 bg-green-100 text-green-700 rounded text-sm hover:bg-green-200 border border-green-300">';
                        $html .= '<i class="fas fa-camera mr-1"></i>Foto Pengembalian';
                        $html .= '</button>';
                    }
                    $html .= '</div>';
                    
                    $html .= '</div>';
                }
            } else {
                $html .= '<div class="bg-gray-100 border p-4 rounded-lg text-center text-gray-600">';
                $html .= '<i class="fas fa-info-circle text-3xl mb-2 text-gray-400"></i>';
                $html .= '<p class="font-medium">Barang ini belum pernah dipinjam</p>';
                $html .= '<p class="text-sm">Status: Barang baru atau belum pernah digunakan</p>';
                $html .= '</div>';
            }
            
            $html .= '</div>';
            $html .= '</div>';

            echo json_encode([
                'success' => true,
                'html' => $html
            ]);
        } else {
            echo json_encode([
                'success' => false,
                'message' => 'Data barang tidak ditemukan'
            ]);
        }
        exit();
    }

    // Main search functionality
    $search_code = isset($_GET['search_code']) ? trim($_GET['search_code']) : '';
    $page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
    $limit = isset($_GET['limit']) ? intval($_GET['limit']) : 25;
    $offset = ($page - 1) * $limit;

    if (strlen($search_code) < 3) {
        echo json_encode([
            'success' => false,
            'message' => 'Masukkan minimal 3 karakter untuk pencarian'
        ]);
        exit();
    }

    // Base query untuk menghitung total data
    $count_query = "
        SELECT COUNT(*) as total
        FROM color_stock_items_surabaya csi
        JOIN master_color_panel_surabaya mcp ON csi.color_id = mcp.id
        JOIN buyers_surabaya b ON mcp.buyer_id = b.id
        JOIN color_components_surabaya cc ON csi.component_id = cc.id
        WHERE csi.kode_barang LIKE ?
    ";

    // Base query untuk mengambil data dengan admin extras
    $data_query = "
        SELECT 
            csi.*,
            mcp.code_color,
            mcp.deskripsi as color_description,
            b.nama_buyer,
            cc.component_name,
            (SELECT COUNT(*) FROM transaction_items_surabaya ti 
             JOIN stock_transactions_surabaya st ON ti.transaction_id = st.id 
             WHERE ti.stock_item_id = csi.id) as total_peminjaman,
            (SELECT bu.nama_borrower FROM transaction_items_surabaya ti 
             JOIN stock_transactions_surabaya st ON ti.transaction_id = st.id 
             JOIN borrower_users_surabaya bu ON st.borrower_id = bu.id 
             WHERE ti.stock_item_id = csi.id 
             ORDER BY st.tanggal_transaksi DESC LIMIT 1) as peminjam_terakhir,
            (SELECT bu.nik FROM transaction_items_surabaya ti 
             JOIN stock_transactions_surabaya st ON ti.transaction_id = st.id 
             JOIN borrower_users_surabaya bu ON st.borrower_id = bu.id 
             WHERE ti.stock_item_id = csi.id 
             ORDER BY st.tanggal_transaksi DESC LIMIT 1) as nik_peminjam,
            (SELECT ti.tanggal_kembali FROM transaction_items_surabaya ti 
             JOIN stock_transactions_surabaya st ON ti.transaction_id = st.id 
             WHERE ti.stock_item_id = csi.id AND ti.dikembalikan = 1 
             ORDER BY ti.tanggal_kembali DESC LIMIT 1) as terakhir_dikembalikan,
            (SELECT ti.kondisi_kembali FROM transaction_items_surabaya ti 
             JOIN stock_transactions_surabaya st ON ti.transaction_id = st.id 
             WHERE ti.stock_item_id = csi.id AND ti.dikembalikan = 1 
             ORDER BY ti.tanggal_kembali DESC LIMIT 1) as kondisi_terakhir,
            DATEDIFF(csi.tanggal_kedaluwarsa, NOW()) as days_until_expiry
        FROM color_stock_items_surabaya csi
        JOIN master_color_panel_surabaya mcp ON csi.color_id = mcp.id
        JOIN buyers_surabaya b ON mcp.buyer_id = b.id
        JOIN color_components_surabaya cc ON csi.component_id = cc.id
        WHERE csi.kode_barang LIKE ?
    ";

    $search_param = "%{$search_code}%";

    // Get total count
    $count_stmt = $conn->prepare($count_query);
    $count_stmt->bind_param("s", $search_param);
    $count_stmt->execute();
    $count_result = $count_stmt->get_result();
    $total_data = $count_result->fetch_assoc()['total'];
    $total_pages = ceil($total_data / $limit);

    // Get data with pagination
    $data_query .= " ORDER BY csi.kode_barang ASC LIMIT ? OFFSET ?";
    $data_stmt = $conn->prepare($data_query);
    $data_stmt->bind_param("sii", $search_param, $limit, $offset);
    $data_stmt->execute();
    $result = $data_stmt->get_result();

    // Generate table HTML with admin enhancements
    $html = '<table class="min-w-full divide-y divide-gray-200">
                <thead class="bg-gray-50">
                    <tr>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">No</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Kode Barang</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Informasi Barang</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Status</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Peminjam Terakhir</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Kondisi Terakhir</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Expiry Info</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Total Pinjam</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Aksi</th>
                    </tr>
                </thead>
                <tbody class="bg-white divide-y divide-gray-200">';

    if ($result->num_rows > 0) {
        $no = $offset + 1;
        while ($row = $result->fetch_assoc()) {
            // Enhanced row highlighting for admin
            $row_class = 'hover:bg-gray-50';
            $expiry_alert = '';
            
            if ($row['status'] == 'Dipinjam') {
                $row_class = 'bg-orange-50 hover:bg-orange-100 border-l-4 border-orange-400';
            } elseif ($row['status'] == 'Rusak') {
                $row_class = 'bg-red-50 hover:bg-red-100 border-l-4 border-red-400';
            } elseif ($row['status'] == 'Hilang') {
                $row_class = 'bg-yellow-50 hover:bg-yellow-100 border-l-4 border-yellow-400';
            } elseif ($row['status'] == 'Expired') {
                $row_class = 'bg-purple-50 hover:bg-purple-100 border-l-4 border-purple-400';
            } elseif ($row['days_until_expiry'] <= 30 && $row['days_until_expiry'] > 0) {
                $row_class = 'bg-yellow-25 hover:bg-yellow-75 border-l-2 border-yellow-300';
                $expiry_alert = '⚠️ ';
            }
            
            $html .= '<tr class="' . $row_class . '">
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">' . $no . '</td>
                        
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="text-lg font-mono font-bold text-blue-600">' . $expiry_alert . htmlspecialchars($row['kode_barang']) . '</div>
                            <div class="text-sm text-gray-500">Stock #' . $row['stock_number'] . '</div>
                        </td>

                        <td class="px-6 py-4">
                            <div class="text-sm font-medium text-gray-900">' . htmlspecialchars($row['nama_buyer'] . ' ' . $row['code_color']) . '</div>
                            <div class="text-sm text-gray-500">' . htmlspecialchars($row['component_name']) . '</div>
                            <div class="text-sm text-gray-500">Rack: ' . htmlspecialchars($row['rack_no']) . '</div>
                        </td>

                        <td class="px-6 py-4 whitespace-nowrap">';

            // Enhanced status badge for admin
            $status_color = '';
            $status_icon = '';
            switch($row['status']) {
                case 'Tersedia':
                    $status_color = 'bg-green-100 text-green-800';
                    $status_icon = 'fas fa-check-circle';
                    break;
                case 'Dipinjam':
                    $status_color = 'bg-orange-100 text-orange-800';
                    $status_icon = 'fas fa-hand-holding';
                    break;
                case 'Rusak':
                    $status_color = 'bg-red-100 text-red-800';
                    $status_icon = 'fas fa-exclamation-triangle';
                    break;
                case 'Expired':
                    $status_color = 'bg-yellow-100 text-yellow-800';
                    $status_icon = 'fas fa-calendar-times';
                    break;
                case 'Hilang':
                    $status_color = 'bg-purple-100 text-purple-800';
                    $status_icon = 'fas fa-question-circle';
                    break;
                default:
                    $status_color = 'bg-gray-100 text-gray-800';
                    $status_icon = 'fas fa-circle';
            }

            $html .= '<span class="inline-flex items-center px-2 py-1 text-xs font-semibold rounded-full ' . $status_color . '">';
            $html .= '<i class="' . $status_icon . ' mr-1"></i>' . htmlspecialchars($row['status']);
            $html .= '</span></td>

                        <td class="px-6 py-4">';
            
            if ($row['peminjam_terakhir']) {
                $html .= '<div class="text-sm font-medium text-gray-900">' . htmlspecialchars($row['peminjam_terakhir']) . '</div>';
                $html .= '<div class="text-xs text-gray-500">NIK: ' . htmlspecialchars($row['nik_peminjam']) . '</div>';
                if ($row['terakhir_dikembalikan']) {
                    $html .= '<div class="text-sm text-gray-500">Kembali: ' . date('d/m/Y H:i', strtotime($row['terakhir_dikembalikan'])) . '</div>';
                } else {
                    $html .= '<div class="text-sm text-red-600 font-medium">❌ Belum Dikembalikan</div>';
                }
            } else {
                $html .= '<span class="text-sm text-gray-400">Belum pernah dipinjam</span>';
            }
            
            $html .= '</td>

                        <td class="px-6 py-4 whitespace-nowrap">';
            
            if ($row['kondisi_terakhir']) {
                $kondisi_color = '';
                $kondisi_icon = '';
                switch($row['kondisi_terakhir']) {
                    case 'Baik': 
                        $kondisi_color = 'bg-green-100 text-green-800'; 
                        $kondisi_icon = 'fas fa-check';
                        break;
                    case 'Rusak': 
                        $kondisi_color = 'bg-red-100 text-red-800'; 
                        $kondisi_icon = 'fas fa-exclamation-triangle';
                        break;
                    case 'Hilang': 
                        $kondisi_color = 'bg-yellow-100 text-yellow-800'; 
                        $kondisi_icon = 'fas fa-question-circle';
                        break;
                }
                $html .= '<span class="inline-flex items-center px-2 py-1 text-xs font-semibold rounded-full ' . $kondisi_color . '">';
                $html .= '<i class="' . $kondisi_icon . ' mr-1"></i>' . htmlspecialchars($row['kondisi_terakhir']);
                $html .= '</span>';
            } else {
                $html .= '<span class="text-sm text-gray-400">-</span>';
            }
            
            $html .= '</td>

                        <td class="px-6 py-4 whitespace-nowrap text-center">';
            
            // Enhanced expiry info for admin
            if ($row['days_until_expiry'] < 0) {
                $html .= '<div class="text-red-600 font-bold text-xs">';
                $html .= '<i class="fas fa-exclamation-triangle mr-1"></i>';
                $html .= 'Expired ' . abs($row['days_until_expiry']) . ' hari';
                $html .= '</div>';
            } elseif ($row['days_until_expiry'] <= 30) {
                $html .= '<div class="text-yellow-600 font-medium text-xs">';
                $html .= '<i class="fas fa-clock mr-1"></i>';
                $html .= 'Sisa ' . $row['days_until_expiry'] . ' hari';
                $html .= '</div>';
            } else {
                $html .= '<div class="text-green-600 text-xs">';
                $html .= '<i class="fas fa-check mr-1"></i>';
                $html .= 'Valid ' . $row['days_until_expiry'] . ' hari';
                $html .= '</div>';
            }
            
            $html .= '</td>

                        <td class="px-6 py-4 whitespace-nowrap text-center">
                            <div class="text-lg font-bold text-purple-600">' . $row['total_peminjaman'] . '</div>
                            <div class="text-xs text-gray-500">kali</div>
                        </td>

                        <td class="px-6 py-4 whitespace-nowrap text-center">
                            <button onclick="showDetail(' . $row['id'] . ')" class="px-3 py-1 bg-purple-100 text-purple-700 rounded hover:bg-purple-200 transition-colors text-sm border border-purple-300">
                                <i class="fas fa-eye mr-1"></i>Detail
                            </button>
                        </td>
                    </tr>';
            $no++;
        }
    } else {
        $html .= '<tr>
                    <td colspan="9" class="px-6 py-12 text-center text-gray-500">
                        <i class="fas fa-search text-4xl mb-4 text-gray-300"></i>
                        <div class="text-lg font-medium">Tidak ada barang ditemukan</div>
                        <div class="text-sm">Coba gunakan kata kunci yang berbeda</div>
                    </td>
                  </tr>';
    }

    $html .= '</tbody></table>';

    // Return JSON response
    echo json_encode([
        'success' => true,
        'html' => $html,
        'totalData' => $total_data,
        'totalPages' => $total_pages,
        'currentPage' => $page,
        'limit' => $limit
    ]);

} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Terjadi kesalahan saat memuat data: ' . $e->getMessage()
    ]);
}
?>