<?php
session_start();

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

// Redirect if not IT user
if (!is_logged_in() || !is_user_type('it')) {
    header("Location: ../login.php");
    exit();
}

// Get IT user data
$it_id = $_SESSION['user_id'];

// Set page title
$page_title = "Lacak Peminjaman Barang";

// Log activity using create_audit_log
create_audit_log($conn, 'Track Borrowing Access', $it_id, 'it', 'IT user accessed track borrowing page');

// Handle AJAX request for detailed item info
if (isset($_GET['get_item_details']) && !empty($_GET['get_item_details'])) {
    header('Content-Type: application/json');
    
    $item_id = intval($_GET['get_item_details']);
    
    $detail_query = "SELECT 
                        csi.id,
                        csi.kode_barang,
                        csi.stock_number,
                        csi.keterangan,
                        csi.rack_no,
                        csi.tanggal_pembuatan,
                        csi.tanggal_kedaluwarsa,
                        csi.qr_code_content,
                        mcp.code_color,
                        mcp.deskripsi as color_deskripsi,
                        mcp.panel_type,
                        mcp.kode_warna_hex,
                        b.nama_buyer,
                        b.kode_buyer,
                        cc.component_name,
                        col.nama_collection,
                        ti.lokasi_asal,
                        ti.lokasi_tujuan,
                        ti.tanggal_kembali as target_kembali,
                        ti.catatan,
                        ti.quantity_requested,
                        ti.quantity_approved,
                        st.reservation_number,
                        st.tanggal_transaksi,
                        st.tanggal_pengembalian,
                        st.status as transaction_status,
                        st.keterangan as transaksi_keterangan,
                        st.status_peminjaman,
                        bu.username as peminjam_name,
                        bu.nama_borrower as peminjam_full_name,
                        bu.email as peminjam_email,
                        bu.lokasi_posisi as peminjam_posisi,
                        bu.nik as peminjam_nik,
                        -- Calculate duration correctly
                        TIMESTAMPDIFF(HOUR, st.tanggal_transaksi, st.tanggal_pengembalian) as durasi_peminjaman_jam,
                        TIMESTAMPDIFF(MINUTE, st.tanggal_transaksi, st.tanggal_pengembalian) as durasi_peminjaman_menit,
                        -- Calculate actual elapsed time
                        TIMESTAMPDIFF(HOUR, st.tanggal_transaksi, NOW()) as waktu_berlalu_jam,
                        TIMESTAMPDIFF(MINUTE, st.tanggal_transaksi, NOW()) as waktu_berlalu_menit,
                        -- Status tracking: Only 2 status - Dipinjam or Overdue
                        CASE 
                            WHEN NOW() > DATE_ADD(st.tanggal_pengembalian, INTERVAL 15 MINUTE) THEN 'Overdue'
                            ELSE 'Dipinjam'
                        END as status_waktu_tracking,
                        -- Additional info for overdue calculation
                        DATE_ADD(st.tanggal_pengembalian, INTERVAL 15 MINUTE) as deadline_with_tolerance,
                        TIMESTAMPDIFF(MINUTE, DATE_ADD(st.tanggal_pengembalian, INTERVAL 15 MINUTE), NOW()) as menit_terlambat
                    FROM color_stock_items csi
                    JOIN master_color_panel mcp ON csi.color_id = mcp.id
                    JOIN buyers b ON mcp.buyer_id = b.id
                    JOIN collections col ON mcp.collection_id = col.id
                    JOIN color_components cc ON csi.component_id = cc.id
                    JOIN transaction_items ti ON csi.id = ti.stock_item_id
                    JOIN stock_transactions st ON ti.transaction_id = st.id
                    JOIN borrower_users bu ON st.borrower_id = bu.id
                    WHERE csi.id = ? AND csi.status = 'Dipinjam' AND ti.dikembalikan = 0";
    
    $detail_stmt = $conn->prepare($detail_query);
    $detail_stmt->bind_param("i", $item_id);
    $detail_stmt->execute();
    $detail_result = $detail_stmt->get_result();
    
    if ($detail_result->num_rows > 0) {
        $detail_data = $detail_result->fetch_assoc();
        echo json_encode(['success' => true, 'data' => $detail_data]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Item not found']);
    }
    exit();
}

// Handle AJAX request for borrowing history
if (isset($_GET['get_borrowing_history'])) {
    header('Content-Type: application/json');
    
    $search_term = isset($_GET['search']) ? trim($_GET['search']) : '';
    $buyer_filter = isset($_GET['buyer_filter']) ? intval($_GET['buyer_filter']) : 0;
    $status_filter = isset($_GET['status_filter']) ? $_GET['status_filter'] : '';
    
    $history_query = "SELECT 
                        csi.kode_barang,
                        mcp.code_color,
                        mcp.deskripsi as color_deskripsi,
                        mcp.panel_type,
                        b.nama_buyer,
                        b.kode_buyer,
                        cc.component_name,
                        bu.username as peminjam_name,
                        bu.nama_borrower as peminjam_full_name,
                        bu.lokasi_posisi as peminjam_posisi,
                        st.reservation_number,
                        st.tanggal_transaksi,
                        st.tanggal_pengembalian,
                        ti.tanggal_kembali,
                        ti.lokasi_asal,
                        ti.lokasi_tujuan,
                        ti.kondisi_kembali,
                        st.status_peminjaman,
                        st.status as transaction_status,
                        CASE 
                            WHEN st.status_peminjaman = 'Dikembalikan' THEN 'Selesai'
                            WHEN csi.status = 'Dipinjam' AND ti.dikembalikan = 0 THEN 
                                CASE 
                                    WHEN NOW() > DATE_ADD(st.tanggal_pengembalian, INTERVAL 15 MINUTE) THEN 'Overdue'
                                    ELSE 'Dipinjam'
                                END
                            ELSE 'Selesai'
                        END as status_display
                    FROM color_stock_items csi
                    JOIN master_color_panel mcp ON csi.color_id = mcp.id
                    JOIN buyers b ON mcp.buyer_id = b.id
                    JOIN color_components cc ON csi.component_id = cc.id
                    JOIN transaction_items ti ON csi.id = ti.stock_item_id
                    JOIN stock_transactions st ON ti.transaction_id = st.id
                    JOIN borrower_users bu ON st.borrower_id = bu.id
                    WHERE 1=1";
    
    $params = [];
    $types = "";
    
    // Add filters
    if (!empty($search_term)) {
        $history_query .= " AND (csi.kode_barang LIKE ? OR mcp.code_color LIKE ? OR st.reservation_number LIKE ? OR bu.username LIKE ? OR bu.nama_borrower LIKE ?)";
        $search_param = "%$search_term%";
        $params = array_merge($params, [$search_param, $search_param, $search_param, $search_param, $search_param]);
        $types .= "sssss";
    }
    
    if ($buyer_filter > 0) {
        $history_query .= " AND b.id = ?";
        $params[] = $buyer_filter;
        $types .= "i";
    }
    
    if (!empty($status_filter)) {
        if ($status_filter === 'Dipinjam') {
            $history_query .= " AND csi.status = 'Dipinjam' AND ti.dikembalikan = 0 AND NOW() <= DATE_ADD(st.tanggal_pengembalian, INTERVAL 15 MINUTE)";
        } elseif ($status_filter === 'Overdue') {
            $history_query .= " AND csi.status = 'Dipinjam' AND ti.dikembalikan = 0 AND NOW() > DATE_ADD(st.tanggal_pengembalian, INTERVAL 15 MINUTE)";
        } elseif ($status_filter === 'Selesai') {
            $history_query .= " AND (st.status_peminjaman = 'Dikembalikan' OR ti.dikembalikan = 1)";
        }
    }
    
    $history_query .= " ORDER BY st.tanggal_transaksi DESC LIMIT 100";
    
    // Execute query
    if (!empty($params)) {
        $history_stmt = $conn->prepare($history_query);
        $history_stmt->bind_param($types, ...$params);
        $history_stmt->execute();
        $history_result = $history_stmt->get_result();
    } else {
        $history_result = $conn->query($history_query);
    }
    
    $history_data = [];
    while ($row = $history_result->fetch_assoc()) {
        $history_data[] = $row;
    }
    
    echo json_encode(['success' => true, 'data' => $history_data]);
    exit();
}

// Get filter parameters
$buyer_filter = isset($_GET['buyer_filter']) ? $_GET['buyer_filter'] : '';
$lokasi_filter = isset($_GET['lokasi_filter']) ? $_GET['lokasi_filter'] : '';
$search_term = isset($_GET['search']) ? $_GET['search'] : '';

// Build main query - only show items with status 'Dipinjam' and not returned
$main_query = "SELECT 
                  csi.id,
                  csi.kode_barang,
                  csi.stock_number,
                  csi.keterangan,
                  csi.qr_code_content,
                  mcp.code_color,
                  mcp.deskripsi,
                  mcp.panel_type,
                  mcp.kode_warna_hex,
                  b.nama_buyer,
                  b.kode_buyer,
                  cc.component_name,
                  ti.lokasi_asal,
                  ti.lokasi_tujuan,
                  st.reservation_number,
                  st.tanggal_transaksi,
                  st.tanggal_pengembalian,
                  bu.username as peminjam_name,
                  bu.nama_borrower as peminjam_full_name,
                  bu.lokasi_posisi as peminjam_posisi,
                  -- Calculate duration correctly
                  TIMESTAMPDIFF(HOUR, st.tanggal_transaksi, st.tanggal_pengembalian) as durasi_peminjaman_jam,
                  TIMESTAMPDIFF(MINUTE, st.tanggal_transaksi, st.tanggal_pengembalian) % 60 as durasi_peminjaman_menit,
                  -- Calculate actual elapsed time
                  TIMESTAMPDIFF(HOUR, st.tanggal_transaksi, NOW()) as waktu_berlalu_jam,
                  TIMESTAMPDIFF(MINUTE, st.tanggal_transaksi, NOW()) % 60 as waktu_berlalu_menit,
                  -- Status tracking: Only 2 status - Dipinjam or Overdue
                  CASE 
                      WHEN NOW() > DATE_ADD(st.tanggal_pengembalian, INTERVAL 15 MINUTE) THEN 'Overdue'
                      ELSE 'Dipinjam'
                  END as status_waktu_tracking,
                  -- Additional overdue info
                  TIMESTAMPDIFF(MINUTE, DATE_ADD(st.tanggal_pengembalian, INTERVAL 15 MINUTE), NOW()) as menit_terlambat,
                  DATE_ADD(st.tanggal_pengembalian, INTERVAL 15 MINUTE) as deadline_with_tolerance
              FROM color_stock_items csi
              JOIN master_color_panel mcp ON csi.color_id = mcp.id
              JOIN buyers b ON mcp.buyer_id = b.id
              JOIN color_components cc ON csi.component_id = cc.id
              JOIN transaction_items ti ON csi.id = ti.stock_item_id
              JOIN stock_transactions st ON ti.transaction_id = st.id
              JOIN borrower_users bu ON st.borrower_id = bu.id
              WHERE csi.status = 'Dipinjam' AND ti.dikembalikan = 0";

$params = [];
$types = "";

// Add filters
if (!empty($buyer_filter)) {
    $main_query .= " AND b.id = ?";
    $params[] = $buyer_filter;
    $types .= "i";
}

if (!empty($lokasi_filter)) {
    $main_query .= " AND ti.lokasi_tujuan = ?";
    $params[] = $lokasi_filter;
    $types .= "s";
}

if (!empty($search_term)) {
    $main_query .= " AND (csi.kode_barang LIKE ? OR mcp.code_color LIKE ? OR st.reservation_number LIKE ? OR bu.username LIKE ? OR bu.nama_borrower LIKE ?)";
    $search_param = "%$search_term%";
    $params = array_merge($params, [$search_param, $search_param, $search_param, $search_param, $search_param]);
    $types .= "sssss";
}

$main_query .= " ORDER BY st.tanggal_transaksi DESC";

// Execute main query
if (!empty($params)) {
    $main_stmt = $conn->prepare($main_query);
    $main_stmt->bind_param($types, ...$params);
    $main_stmt->execute();
    $main_result = $main_stmt->get_result();
} else {
    $main_result = $conn->query($main_query);
}

// Get filter options
$buyers_query = "SELECT id, nama_buyer FROM buyers ORDER BY nama_buyer";
$buyers_result = $conn->query($buyers_query);

$locations = ['PTG 6', 'PTG MANUAL', 'PACKING','CHAIR', 'QC OPEN BOX', 'PTG 6 CONVEYOR','PUSHPULL MANUAL'];

// Get summary statistics - only items with status 'Dipinjam'
$stats_query = "SELECT 
                    COUNT(*) as total_dipinjam,
                    COUNT(CASE WHEN NOW() > DATE_ADD(st.tanggal_pengembalian, INTERVAL 15 MINUTE) THEN 1 END) as total_overdue,
                    COUNT(DISTINCT mcp.code_color) as unique_colors_borrowed,
                    COUNT(DISTINCT bu.id) as active_borrowers
                FROM color_stock_items csi
                JOIN master_color_panel mcp ON csi.color_id = mcp.id
                JOIN transaction_items ti ON csi.id = ti.stock_item_id
                JOIN stock_transactions st ON ti.transaction_id = st.id
                JOIN borrower_users bu ON st.borrower_id = bu.id
                WHERE csi.status = 'Dipinjam' AND ti.dikembalikan = 0";
$stats_result = $conn->query($stats_query);
$stats = $stats_result->fetch_assoc();

// Include header
include '../template_it/header.php';
?>

<!-- Main Content Area -->
<main class="flex-1 p-2 sm:p-6 overflow-auto bg-gradient-to-br from-blue-100 via-teal-100 to-green-100">
    
    <!-- Page Header -->
    <div class="bg-white rounded-lg shadow-md p-3 sm:p-6 mb-4 sm:mb-6">
        <div class="flex flex-col sm:flex-row justify-between items-start sm:items-center">
            <div>
                <h2 class="text-xl sm:text-2xl font-bold text-gray-800 mb-2 sm:mb-4">
                    <i class="fas fa-search-location mr-2"></i>
                    Lacak Peminjaman Barang
                </h2>
                <p class="text-gray-600 text-sm sm:text-base">
                    Monitoring dan tracking barang color code yang sedang dipinjam dari Color Room ke berbagai lokasi.
                    <br><small class="text-gray-500">Menampilkan barang dengan status 'Dipinjam' yang belum dikembalikan.</small>
                </p>
            </div>
            <div class="mt-3 sm:mt-0">
                <button onclick="showBorrowingHistory()" class="bg-purple-500 hover:bg-purple-600 text-white font-medium py-2 px-4 text-sm sm:text-base rounded-md transition duration-150 ease-in-out shadow-md hover:shadow-lg">
                    <i class="fas fa-history mr-2"></i>History
                </button>
            </div>
        </div>
    </div>

    <!-- Statistics Cards -->
    <div class="mb-4 sm:mb-6 grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
        <div class="bg-white p-4 sm:p-6 rounded-lg shadow-md">
            <div class="flex items-center">
                <div class="p-3 rounded-full bg-blue-100 text-blue-600">
                    <i class="fas fa-boxes text-xl"></i>
                </div>
                <div class="ml-4">
                    <p class="text-sm font-medium text-gray-500">Total Dipinjam</p>
                    <p class="text-xl sm:text-2xl font-bold text-gray-900"><?php echo $stats['total_dipinjam']; ?></p>
                    <p class="text-xs text-gray-400">Belum dikembalikan</p>
                </div>
            </div>
        </div>
        
        <div class="bg-white p-4 sm:p-6 rounded-lg shadow-md">
            <div class="flex items-center">
                <div class="p-3 rounded-full bg-red-100 text-red-600">
                    <i class="fas fa-exclamation-triangle text-xl"></i>
                </div>
                <div class="ml-4">
                    <p class="text-sm font-medium text-gray-500">Overdue</p>
                    <p class="text-xl sm:text-2xl font-bold text-red-600"><?php echo $stats['total_overdue']; ?></p>
                    <p class="text-xs text-gray-400">Lewat deadline + 15 menit</p>
                </div>
            </div>
        </div>
        
        <div class="bg-white p-4 sm:p-6 rounded-lg shadow-md">
            <div class="flex items-center">
                <div class="p-3 rounded-full bg-green-100 text-green-600">
                    <i class="fas fa-palette text-xl"></i>
                </div>
                <div class="ml-4">
                    <p class="text-sm font-medium text-gray-500">Unique Colors</p>
                    <p class="text-xl sm:text-2xl font-bold text-green-600"><?php echo $stats['unique_colors_borrowed']; ?></p>
                    <p class="text-xs text-gray-400">Sedang dipinjam</p>
                </div>
            </div>
        </div>
        
        <div class="bg-white p-4 sm:p-6 rounded-lg shadow-md">
            <div class="flex items-center">
                <div class="p-3 rounded-full bg-orange-100 text-orange-600">
                    <i class="fas fa-users text-xl"></i>
                </div>
                <div class="ml-4">
                    <p class="text-sm font-medium text-gray-500">Active Borrowers</p>
                    <p class="text-xl sm:text-2xl font-bold text-orange-600"><?php echo $stats['active_borrowers']; ?></p>
                    <p class="text-xs text-gray-400">Pengguna aktif</p>
                </div>
            </div>
        </div>
    </div>

    <!-- Filters -->
    <div class="bg-white rounded-lg shadow-md p-3 sm:p-6 mb-4 sm:mb-6">
        <h3 class="text-base sm:text-lg font-semibold text-gray-800 mb-3 sm:mb-4">Filter & Pencarian</h3>
        
        <form method="GET" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
            <!-- Buyer Filter -->
            <div>
                <label for="buyer_filter" class="block text-sm font-medium text-gray-700 mb-1">Buyer:</label>
                <select id="buyer_filter" name="buyer_filter" class="w-full py-2 px-3 border border-gray-300 bg-white rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm">
                    <option value="">-- Semua Buyer --</option>
                    <?php while ($buyer = $buyers_result->fetch_assoc()): ?>
                        <option value="<?php echo $buyer['id']; ?>" <?php echo ($buyer_filter == $buyer['id']) ? 'selected' : ''; ?>>
                            <?php echo htmlspecialchars($buyer['nama_buyer']); ?>
                        </option>
                    <?php endwhile; ?>
                </select>
            </div>

            <!-- Location Filter -->
            <div>
                <label for="lokasi_filter" class="block text-sm font-medium text-gray-700 mb-1">Lokasi Tujuan:</label>
                <select id="lokasi_filter" name="lokasi_filter" class="w-full py-2 px-3 border border-gray-300 bg-white rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm">
                    <option value="">-- Semua Lokasi --</option>
                    <?php foreach ($locations as $location): ?>
                        <option value="<?php echo $location; ?>" <?php echo ($lokasi_filter == $location) ? 'selected' : ''; ?>>
                            <?php echo $location; ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>

            <!-- Search -->
            <div>
                <label for="search" class="block text-sm font-medium text-gray-700 mb-1">Pencarian:</label>
                <input type="text" id="search" name="search" value="<?php echo htmlspecialchars($search_term); ?>" placeholder="Kode barang, Color code, dll..." class="w-full py-2 px-3 border border-gray-300 bg-white rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm">
            </div>

            <!-- Filter Button -->
            <div class="flex items-end">
                <button type="submit" class="w-full bg-blue-600 hover:bg-blue-700 text-white py-2 px-4 rounded-md text-sm font-medium">
                    <i class="fas fa-filter mr-2"></i> Filter
                </button>
            </div>
        </form>

        <?php if (!empty($buyer_filter) || !empty($lokasi_filter) || !empty($search_term)): ?>
        <div class="mt-4">
            <a href="lacak_peminjaman_it.php" class="text-sm text-blue-600 hover:text-blue-800">
                <i class="fas fa-times mr-1"></i> Clear All Filters
            </a>
        </div>
        <?php endif; ?>
    </div>

    <!-- Borrowing Items Table -->
    <div class="bg-white rounded-lg shadow-md p-3 sm:p-6">
        <div class="flex justify-between items-center mb-4">
            <h3 class="text-lg sm:text-xl font-semibold text-gray-800">Barang yang Sedang Dipinjam</h3>
            <div class="text-sm text-gray-500">
                Total: <?php echo $main_result->num_rows; ?> item
            </div>
        </div>
        
        <div class="overflow-x-auto">
            <table class="min-w-full bg-white border border-gray-200">
                <thead class="bg-gray-100">
                    <tr>
                        <th class="py-3 px-4 border-b text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Kode Barang</th>
                        <th class="py-3 px-4 border-b text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Color Code</th>
                        <th class="py-3 px-4 border-b text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Komponen</th>
                        <th class="py-3 px-4 border-b text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Buyer</th>
                        <th class="py-3 px-4 border-b text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Lokasi</th>
                        <th class="py-3 px-4 border-b text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Peminjam</th>
                        <th class="py-3 px-4 border-b text-left text-xs font-medium text-gray-500 uppercase tracking-wider">No. Reservasi</th>
                        <th class="py-3 px-4 border-b text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Durasi & Waktu</th>
                        <th class="py-3 px-4 border-b text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Status Tracking</th>
                        <th class="py-3 px-4 border-b text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Aksi</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-gray-200">
                <?php
                if ($main_result->num_rows > 0) {
                    while ($item = $main_result->fetch_assoc()) {
                        // Status tracking styling - only 2 status
                        $status_class = '';
                        $status_icon = '';
                        if($item['status_waktu_tracking'] == 'Overdue') {
                            $status_class = 'bg-red-100 text-red-800';
                            $status_icon = 'fas fa-exclamation-triangle';
                        } else {
                            $status_class = 'bg-green-100 text-green-800';
                            $status_icon = 'fas fa-check-circle';
                        }
                        
                        // Calculate duration display
                        $durasi_jam = $item['durasi_peminjaman_jam'];
                        $durasi_menit = $item['durasi_peminjaman_menit'];
                        $durasi_display = '';
                        if ($durasi_jam > 0) {
                            $durasi_display = $durasi_jam . ' jam';
                            if ($durasi_menit > 0) {
                                $durasi_display .= ' ' . $durasi_menit . ' menit';
                            }
                        } else {
                            $durasi_display = $durasi_menit . ' menit';
                        }
                        
                        // Calculate elapsed time
                        $waktu_berlalu_jam = $item['waktu_berlalu_jam'];
                        $waktu_berlalu_menit = $item['waktu_berlalu_menit'];
                        $waktu_berlalu_display = '';
                        if ($waktu_berlalu_jam > 0) {
                            $waktu_berlalu_display = $waktu_berlalu_jam . ' jam';
                            if ($waktu_berlalu_menit > 0) {
                                $waktu_berlalu_display .= ' ' . $waktu_berlalu_menit . ' menit';
                            }
                        } else {
                            $waktu_berlalu_display = $waktu_berlalu_menit . ' menit';
                        }
                        
                        echo '<tr class="hover:bg-gray-50">';
                        echo '<td class="py-3 px-4 text-sm">';
                        echo '<div class="font-medium text-blue-600 font-mono">' . htmlspecialchars($item['kode_barang']) . '</div>';
                        echo '<div class="text-gray-500 text-xs">Stock #' . $item['stock_number'] . '</div>';
                        if (!empty($item['qr_code_content'])) {
                            echo '<div class="text-gray-400 text-xs">QR: ' . htmlspecialchars($item['qr_code_content']) . '</div>';
                        }
                        echo '</td>';
                        
                        echo '<td class="py-3 px-4 text-sm">';
                        echo '<div class="font-medium text-gray-900">' . htmlspecialchars($item['code_color']) . '</div>';
                        echo '<div class="text-gray-500 text-xs">' . htmlspecialchars($item['deskripsi']) . '</div>';
                        $panel_type_color = $item['panel_type'] === 'master_color' ? 'text-blue-600' : 'text-green-600';
                        echo '<div class="text-xs ' . $panel_type_color . '">' . ucfirst($item['panel_type']) . '</div>';
                        echo '</td>';
                        
                        echo '<td class="py-3 px-4 text-sm text-gray-900">' . htmlspecialchars($item['component_name']) . '</td>';
                        
                        echo '<td class="py-3 px-4 text-sm">';
                        echo '<div class="font-medium text-gray-900">' . htmlspecialchars($item['nama_buyer']) . '</div>';
                        echo '<div class="text-gray-500">' . htmlspecialchars($item['kode_buyer']) . '</div>';
                        echo '</td>';
                        
                        echo '<td class="py-3 px-4 text-sm">';
                        echo '<div class="text-gray-900"><i class="fas fa-arrow-right mx-1"></i></div>';
                        echo '<div class="text-xs text-gray-500">' . htmlspecialchars($item['lokasi_asal']) . '</div>';
                        echo '<div class="font-medium text-blue-600">' . htmlspecialchars($item['lokasi_tujuan']) . '</div>';
                        echo '</td>';
                        
                        echo '<td class="py-3 px-4 text-sm">';
                        echo '<div class="font-medium text-gray-900">' . htmlspecialchars($item['peminjam_name']) . '</div>';
                        if (!empty($item['peminjam_full_name'])) {
                            echo '<div class="text-gray-500 text-xs">' . htmlspecialchars($item['peminjam_full_name']) . '</div>';
                        }
                        echo '<div class="text-gray-500 text-xs">' . htmlspecialchars($item['peminjam_posisi']) . '</div>';
                        echo '</td>';
                        
                        echo '<td class="py-3 px-4 text-sm">';
                        echo '<div class="font-mono text-blue-600">' . htmlspecialchars($item['reservation_number']) . '</div>';
                        echo '<div class="text-xs text-gray-500">' . date('d/m/Y H:i', strtotime($item['tanggal_transaksi'])) . '</div>';
                        echo '</td>';
                        
                        echo '<td class="py-3 px-4 text-sm">';
                        echo '<div class="text-gray-900">Dialokasikan: ' . $durasi_display . '</div>';
                        echo '<div class="text-xs text-blue-600">Berlalu: ' . $waktu_berlalu_display . '</div>';
                        echo '<div class="text-xs text-gray-500">Deadline: ' . date('d/m/Y H:i', strtotime($item['deadline_with_tolerance'])) . '</div>';
                        echo '</td>';
                        
                        echo '<td class="py-3 px-4">';
                        echo '<span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full ' . $status_class . '">';
                        echo '<i class="' . $status_icon . ' mr-1"></i>' . $item['status_waktu_tracking'];
                        echo '</span>';
                        // Show overdue time if applicable
                        if ($item['status_waktu_tracking'] === 'Overdue' && $item['menit_terlambat'] > 0) {
                            $jam_terlambat = floor($item['menit_terlambat'] / 60);
                            $menit_terlambat = $item['menit_terlambat'] % 60;
                            $terlambat_display = '';
                            if ($jam_terlambat > 0) {
                                $terlambat_display = $jam_terlambat . 'j ' . $menit_terlambat . 'm';
                            } else {
                                $terlambat_display = $menit_terlambat . 'm';
                            }
                            echo '<div class="text-xs text-red-600 mt-1">+' . $terlambat_display . '</div>';
                        }
                        echo '</td>';
                        
                        echo '<td class="py-3 px-4 text-sm">';
                        echo '<button onclick="viewItemDetails(' . $item['id'] . ')" class="bg-blue-500 hover:bg-blue-600 text-white text-xs py-1 px-3 rounded mr-1">';
                        echo '<i class="fas fa-eye"></i> Detail';
                        echo '</button>';
                        echo '</td>';
                        
                        echo '</tr>';
                    }
                } else {
                    echo '<tr><td colspan="10" class="py-8 px-4 text-center text-gray-500">';
                    echo '<i class="fas fa-inbox text-4xl mb-4 text-gray-300"></i><br>';
                    echo 'Tidak ada barang yang sedang dipinjam';
                    echo '<br><small class="text-gray-400">Semua barang sudah dikembalikan atau tidak ada transaksi peminjaman aktif</small>';
                    echo '</td></tr>';
                }
                ?>
                </tbody>
            </table>
        </div>
    </div>
</main>

<!-- Item Details Modal -->
<div id="itemDetailsModal" class="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full hidden z-50">
    <div class="relative top-5 mx-auto p-4 border w-11/12 md:w-2/3 lg:w-1/2 max-h-[90vh] shadow-lg rounded-lg bg-white">
        <div class="flex flex-col h-full">
            <div class="flex justify-between items-center mb-3 pb-3 border-b">
                <h3 class="text-lg font-semibold text-gray-900">
                    <i class="fas fa-info-circle mr-2 text-blue-600"></i>
                    Detail Peminjaman
                </h3>
                <button onclick="closeItemDetailsModal()" class="text-gray-400 hover:text-gray-600 p-1">
                    <i class="fas fa-times text-lg"></i>
                </button>
            </div>
            
            <div id="itemDetailsContent" class="flex-1 overflow-y-auto">
                <!-- Content will be loaded here -->
            </div>
            
            <div class="flex justify-end mt-4 pt-3 border-t">
                <button onclick="closeItemDetailsModal()" class="bg-gray-500 hover:bg-gray-600 text-white py-2 px-4 rounded text-sm">
                    Tutup
                </button>
            </div>
        </div>
    </div>
</div>

<!-- Borrowing History Modal -->
<div id="borrowingHistoryModal" class="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full hidden z-50">
    <div class="relative top-2 mx-auto p-4 border w-11/12 max-w-6xl max-h-[95vh] shadow-lg rounded-lg bg-white">
        <div class="flex flex-col h-full">
            <div class="flex justify-between items-center mb-3 pb-3 border-b">
                <h3 class="text-lg font-semibold text-gray-900">
                    <i class="fas fa-history mr-2 text-purple-600"></i>
                    History Peminjaman
                </h3>
                <button onclick="closeBorrowingHistoryModal()" class="text-gray-400 hover:text-gray-600 p-1">
                    <i class="fas fa-times text-lg"></i>
                </button>
            </div>
            
            <!-- History Filters -->
            <div class="mb-4 p-4 bg-gray-50 rounded-lg">
                <div class="grid grid-cols-1 md:grid-cols-4 gap-3">
                    <input type="text" id="history_search" placeholder="Cari kode barang, color code, peminjam..." 
                           class="px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-purple-500 text-sm">
                    
                    <select id="history_buyer_filter" class="px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-purple-500 text-sm">
                        <option value="">Semua Buyer</option>
                        <?php 
                        $buyers_result->data_seek(0);
                        while ($buyer = $buyers_result->fetch_assoc()): 
                        ?>
                            <option value="<?php echo $buyer['id']; ?>"><?php echo htmlspecialchars($buyer['nama_buyer']); ?></option>
                        <?php endwhile; ?>
                    </select>
                    
                    <select id="history_status_filter" class="px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-purple-500 text-sm">
                        <option value="">Semua Status</option>
                        <option value="Dipinjam">Dipinjam</option>
                        <option value="Overdue">Overdue</option>
                        <option value="Selesai">Selesai</option>
                    </select>
                    
                    <button onclick="loadBorrowingHistory()" class="bg-purple-500 hover:bg-purple-600 text-white py-2 px-4 rounded text-sm">
                        <i class="fas fa-search mr-1"></i>Filter
                    </button>
                </div>
            </div>
            
            <div id="borrowingHistoryContent" class="flex-1 overflow-y-auto">
                <!-- History content will be loaded here -->
            </div>
            
            <div class="flex justify-end mt-4 pt-3 border-t">
                <button onclick="closeBorrowingHistoryModal()" class="bg-gray-500 hover:bg-gray-600 text-white py-2 px-4 rounded text-sm">
                    Tutup
                </button>
            </div>
        </div>
    </div>
</div>

<script>
// View item details with correct status tracking
function viewItemDetails(itemId) {
    document.getElementById('itemDetailsModal').classList.remove('hidden');
    document.getElementById('itemDetailsContent').innerHTML = '<div class="text-center py-8"><i class="fas fa-spinner fa-spin text-2xl text-gray-400"></i><p class="mt-2 text-gray-500">Loading...</p></div>';
    
    fetch(`lacak_peminjaman_it.php?get_item_details=${itemId}`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const item = data.data;
                let statusClass = '';
                let statusIcon = '';
                
                if (item.status_waktu_tracking === 'Overdue') {
                    statusClass = 'bg-red-100 text-red-800';
                    statusIcon = 'fas fa-exclamation-triangle';
                } else {
                    statusClass = 'bg-green-100 text-green-800';
                    statusIcon = 'fas fa-check-circle';
                }
                
                // Calculate duration display correctly
                const durasiJam = parseInt(item.durasi_peminjaman_jam);
                const durasiMenit = parseInt(item.durasi_peminjaman_menit);
                let durasiDisplay = '';
                if (durasiJam > 0) {
                    durasiDisplay = durasiJam + ' jam';
                    if (durasiMenit > 0) {
                        durasiDisplay += ' ' + durasiMenit + ' menit';
                    }
                } else {
                    durasiDisplay = durasiMenit + ' menit';
                }
                
                const waktuBerlaluJam = parseInt(item.waktu_berlalu_jam);
                const waktuBerlaluMenit = parseInt(item.waktu_berlalu_menit);
                let waktuBerlaluDisplay = '';
                if (waktuBerlaluJam > 0) {
                    waktuBerlaluDisplay = waktuBerlaluJam + ' jam';
                    if (waktuBerlaluMenit > 0) {
                        waktuBerlaluDisplay += ' ' + waktuBerlaluMenit + ' menit';
                    }
                } else {
                    waktuBerlaluDisplay = waktuBerlaluMenit + ' menit';
                }
                
                const content = `
                    <div class="space-y-4">
                        <!-- Status Banner -->
                        <div class="bg-gradient-to-r ${item.status_waktu_tracking === 'Overdue' ? 'from-red-50 to-red-100 border-red-200' : 'from-green-50 to-green-100 border-green-200'} border rounded-lg p-3">
                            <div class="flex items-center justify-between">
                                <div class="flex items-center">
                                    <i class="${statusIcon} text-lg mr-2"></i>
                                    <span class="font-semibold">${item.status_waktu_tracking}</span>
                                </div>
                                ${item.status_waktu_tracking === 'Overdue' && item.menit_terlambat > 0 ? `
                                    <span class="text-red-700 font-medium text-sm">Terlambat: ${Math.floor(item.menit_terlambat / 60) > 0 ? Math.floor(item.menit_terlambat / 60) + ' jam ' + (item.menit_terlambat % 60) + ' menit' : item.menit_terlambat + ' menit'}</span>
                                ` : ''}
                            </div>
                        </div>

                        <!-- Main Info Grid -->
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                            <!-- Left Column -->
                            <div class="space-y-3">
                                <h5 class="font-semibold text-gray-800 text-sm border-b pb-1">Informasi Barang</h5>
                                
                                <div class="bg-gray-50 p-3 rounded">
                                    <div class="text-xs text-gray-500">Kode Barang (New Format)</div>
                                    <div class="font-mono font-bold text-blue-600">${item.kode_barang}</div>
                                    ${item.qr_code_content ? `<div class="text-xs text-gray-500 mt-1">QR: ${item.qr_code_content}</div>` : ''}
                                </div>
                                
                                <div class="grid grid-cols-2 gap-2">
                                    <div>
                                        <div class="text-xs text-gray-500">Color Code</div>
                                        <div class="font-medium text-sm">${item.code_color}</div>
                                    </div>
                                    <div>
                                        <div class="text-xs text-gray-500">Stock #</div>
                                        <div class="text-sm">${item.stock_number}</div>
                                    </div>
                                </div>
                                
                                <div>
                                    <div class="text-xs text-gray-500">Panel Type</div>
                                    <div class="text-sm ${item.panel_type === 'master_color' ? 'text-blue-600' : 'text-green-600'}">${item.panel_type.charAt(0).toUpperCase() + item.panel_type.slice(1)}</div>
                                </div>
                                
                                <div>
                                    <div class="text-xs text-gray-500">Deskripsi</div>
                                    <div class="text-sm">${item.color_deskripsi || 'N/A'}</div>
                                </div>
                                
                                <div>
                                    <div class="text-xs text-gray-500">Komponen</div>
                                    <div class="text-sm">${item.component_name}</div>
                                </div>
                                
                                <div>
                                    <div class="text-xs text-gray-500">Buyer</div>
                                    <div class="text-sm font-medium">${item.nama_buyer} (${item.kode_buyer})</div>
                                </div>
                                
                                <div>
                                    <div class="text-xs text-gray-500">Collection</div>
                                    <div class="text-sm">${item.nama_collection || 'N/A'}</div>
                                </div>
                                
                                <div>
                                    <div class="text-xs text-gray-500">Lokasi Rack</div>
                                    <div class="text-sm">${item.rack_no || 'N/A'}</div>
                                </div>
                                
                                <div class="grid grid-cols-2 gap-2">
                                    <div>
                                        <div class="text-xs text-gray-500">Dibuat</div>
                                        <div class="text-xs">${item.tanggal_pembuatan ? new Date(item.tanggal_pembuatan).toLocaleDateString('id-ID') : 'N/A'}</div>
                                    </div>
                                    <div>
                                        <div class="text-xs text-gray-500">Kadaluarsa</div>
                                        <div class="text-xs">${item.tanggal_kedaluwarsa ? new Date(item.tanggal_kedaluwarsa).toLocaleDateString('id-ID') : 'N/A'}</div>
                                    </div>
                                </div>
                            </div>

                            <!-- Right Column -->
                            <div class="space-y-3">
                                <h5 class="font-semibold text-gray-800 text-sm border-b pb-1">Informasi Peminjaman</h5>
                                
                                <div class="bg-blue-50 p-3 rounded">
                                    <div class="text-xs text-gray-500">No. Reservasi</div>
                                    <div class="font-mono text-blue-600 font-medium">${item.reservation_number}</div>
                                </div>
                                
                                <div>
                                    <div class="text-xs text-gray-500">Peminjam</div>
                                    <div class="text-sm font-medium">${item.peminjam_name}</div>
                                    ${item.peminjam_full_name ? `<div class="text-xs text-gray-500">${item.peminjam_full_name}</div>` : ''}
                                    <div class="text-xs text-gray-500">${item.peminjam_email}</div>
                                    <div class="text-xs text-gray-500">NIK: ${item.peminjam_nik || 'N/A'}</div>
                                    <div class="text-xs text-gray-500">Posisi: ${item.peminjam_posisi}</div>
                                </div>
                                
                                <div>
                                    <div class="text-xs text-gray-500">Rute</div>
                                    <div class="text-sm">${item.lokasi_asal} <i class="fas fa-arrow-right mx-1 text-blue-500"></i> ${item.lokasi_tujuan}</div>
                                </div>
                                
                                <div class="grid grid-cols-2 gap-2">
                                    <div>
                                        <div class="text-xs text-gray-500">Qty Diminta</div>
                                        <div class="text-sm">${item.quantity_requested || 1}</div>
                                    </div>
                                    <div>
                                        <div class="text-xs text-gray-500">Qty Disetujui</div>
                                        <div class="text-sm">${item.quantity_approved || item.quantity_requested || 1}</div>
                                    </div>
                                </div>
                                
                                <div class="grid grid-cols-2 gap-2">
                                    <div>
                                        <div class="text-xs text-gray-500">Mulai</div>
                                        <div class="text-xs">${new Date(item.tanggal_transaksi).toLocaleString('id-ID')}</div>
                                    </div>
                                    <div>
                                        <div class="text-xs text-gray-500">Target Selesai</div>
                                        <div class="text-xs">${new Date(item.tanggal_pengembalian).toLocaleString('id-ID')}</div>
                                    </div>
                                </div>
                                
                                <div>
                                    <div class="text-xs text-gray-500">Deadline (+ 15 menit)</div>
                                    <div class="text-xs font-medium text-orange-600">${new Date(item.deadline_with_tolerance).toLocaleString('id-ID')}</div>
                                </div>
                                
                                <div>
                                    <div class="text-xs text-gray-500">Status Transaksi</div>
                                    <div class="text-sm font-medium">${item.transaction_status}</div>
                                </div>
                                
                                <div>
                                    <div class="text-xs text-gray-500">Status Peminjaman</div>
                                    <div class="text-sm font-medium">${item.status_peminjaman}</div>
                                </div>
                            </div>
                        </div>

                        <!-- Time Info -->
                        <div class="bg-gray-50 p-3 rounded">
                            <h5 class="font-semibold text-gray-800 text-sm mb-2">Informasi Waktu</h5>
                            <div class="grid grid-cols-2 gap-4 text-sm">
                                <div>
                                    <span class="text-gray-500">Durasi Dialokasikan:</span>
                                    <span class="font-medium text-blue-600 ml-1">${durasiDisplay}</span>
                                </div>
                                <div>
                                    <span class="text-gray-500">Waktu Berlalu:</span>
                                    <span class="font-medium ml-1">${waktuBerlaluDisplay}</span>
                                </div>
                            </div>
                        </div>

                        ${item.catatan || item.transaksi_keterangan || item.keterangan ? `
                        <div class="space-y-2">
                            ${item.catatan ? `
                            <div>
                                <div class="text-xs text-gray-500 mb-1">Catatan Item</div>
                                <div class="text-sm bg-yellow-50 p-2 rounded border-l-4 border-yellow-400">${item.catatan}</div>
                            </div>
                            ` : ''}
                            ${item.transaksi_keterangan ? `
                            <div>
                                <div class="text-xs text-gray-500 mb-1">Keterangan Transaksi</div>
                                <div class="text-sm bg-blue-50 p-2 rounded border-l-4 border-blue-400">${item.transaksi_keterangan}</div>
                            </div>
                            ` : ''}
                            ${item.keterangan ? `
                            <div>
                                <div class="text-xs text-gray-500 mb-1">Keterangan Barang</div>
                                <div class="text-sm bg-gray-50 p-2 rounded border-l-4 border-gray-400">${item.keterangan}</div>
                            </div>
                            ` : ''}
                        </div>
                        ` : ''}
                    </div>
                `;
                
                document.getElementById('itemDetailsContent').innerHTML = content;
            } else {
                document.getElementById('itemDetailsContent').innerHTML = '<div class="text-center text-red-500 py-8"><i class="fas fa-exclamation-triangle text-2xl mb-2"></i><p>' + data.message + '</p></div>';
            }
        })
        .catch(error => {
            console.error('Error:', error);
            document.getElementById('itemDetailsContent').innerHTML = '<div class="text-center text-red-500 py-8"><i class="fas fa-exclamation-triangle text-2xl mb-2"></i><p>Terjadi kesalahan saat mengambil data</p></div>';
        });
}

// Close item details modal
function closeItemDetailsModal() {
    document.getElementById('itemDetailsModal').classList.add('hidden');
}

// Show borrowing history modal
function showBorrowingHistory() {
    document.getElementById('borrowingHistoryModal').classList.remove('hidden');
    loadBorrowingHistory();
}

// Load borrowing history
function loadBorrowingHistory() {
    const search = document.getElementById('history_search').value;
    const buyerFilter = document.getElementById('history_buyer_filter').value;
    const statusFilter = document.getElementById('history_status_filter').value;
    
    document.getElementById('borrowingHistoryContent').innerHTML = '<div class="text-center py-8"><i class="fas fa-spinner fa-spin text-2xl text-gray-400"></i><p class="mt-2 text-gray-500">Loading...</p></div>';
    
    const params = new URLSearchParams({
        get_borrowing_history: '1',
        search: search,
        buyer_filter: buyerFilter,
        status_filter: statusFilter
    });
    
    fetch(`lacak_peminjaman_it.php?${params.toString()}`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const historyItems = data.data;
                
                if (historyItems.length === 0) {
                    document.getElementById('borrowingHistoryContent').innerHTML = '<div class="text-center py-8 text-gray-500"><i class="fas fa-inbox text-4xl mb-4 text-gray-300"></i><br>Tidak ada data history yang ditemukan</div>';
                    return;
                }
                
                let content = `
                    <div class="overflow-x-auto">
                        <table class="min-w-full bg-white border border-gray-200">
                            <thead class="bg-gray-100">
                                <tr>
                                    <th class="py-2 px-3 border-b text-left text-xs font-medium text-gray-500 uppercase">Kode Barang</th>
                                    <th class="py-2 px-3 border-b text-left text-xs font-medium text-gray-500 uppercase">Color Code</th>
                                    <th class="py-2 px-3 border-b text-left text-xs font-medium text-gray-500 uppercase">Komponen</th>
                                    <th class="py-2 px-3 border-b text-left text-xs font-medium text-gray-500 uppercase">Buyer</th>
                                    <th class="py-2 px-3 border-b text-left text-xs font-medium text-gray-500 uppercase">Peminjam</th>
                                    <th class="py-2 px-3 border-b text-left text-xs font-medium text-gray-500 uppercase">Lokasi</th>
                                    <th class="py-2 px-3 border-b text-left text-xs font-medium text-gray-500 uppercase">Tanggal</th>
                                    <th class="py-2 px-3 border-b text-left text-xs font-medium text-gray-500 uppercase">Status</th>
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-gray-200">
                `;
                
                historyItems.forEach(item => {
                    let statusClass = '';
                    let statusIcon = '';
                    
                    switch(item.status_display) {
                        case 'Overdue':
                            statusClass = 'bg-red-100 text-red-800';
                            statusIcon = 'fas fa-exclamation-triangle';
                            break;
                        case 'Dipinjam':
                            statusClass = 'bg-yellow-100 text-yellow-800';
                            statusIcon = 'fas fa-clock';
                            break;
                        case 'Selesai':
                            statusClass = 'bg-green-100 text-green-800';
                            statusIcon = 'fas fa-check-circle';
                            break;
                        default:
                            statusClass = 'bg-gray-100 text-gray-800';
                            statusIcon = 'fas fa-question-circle';
                    }
                    
                    const panelTypeColor = item.panel_type === 'master_color' ? 'text-blue-600' : 'text-green-600';
                    
                    content += `
                        <tr class="hover:bg-gray-50">
                            <td class="py-2 px-3 text-sm">
                                <div class="font-mono text-blue-600">${item.kode_barang}</div>
                            </td>
                            <td class="py-2 px-3 text-sm">
                                <div class="font-medium">${item.code_color}</div>
                                <div class="text-xs text-gray-500">${item.color_deskripsi || 'N/A'}</div>
                                <div class="text-xs ${panelTypeColor}">${item.panel_type.charAt(0).toUpperCase() + item.panel_type.slice(1)}</div>
                            </td>
                            <td class="py-2 px-3 text-sm">
                                <div class="font-medium">${item.component_name}</div>
                            </td>
                            <td class="py-2 px-3 text-sm">
                                <div class="font-medium">${item.nama_buyer}</div>
                                <div class="text-xs text-gray-500">${item.kode_buyer}</div>
                            </td>
                            <td class="py-2 px-3 text-sm">
                                <div class="font-medium">${item.peminjam_name}</div>
                                ${item.peminjam_full_name ? `<div class="text-xs text-gray-500">${item.peminjam_full_name}</div>` : ''}
                                <div class="text-xs text-gray-500">${item.peminjam_posisi}</div>
                            </td>
                            <td class="py-2 px-3 text-sm">
                                <div class="text-xs">${item.lokasi_asal}</div>
                                <div class="text-center text-blue-500"><i class="fas fa-arrow-down"></i></div>
                                <div class="font-medium text-blue-600">${item.lokasi_tujuan}</div>
                            </td>
                            <td class="py-2 px-3 text-sm">
                                <div class="text-xs text-gray-500">Mulai:</div>
                                <div class="text-xs">${new Date(item.tanggal_transaksi).toLocaleDateString('id-ID')}</div>
                                <div class="text-xs">${new Date(item.tanggal_transaksi).toLocaleTimeString('id-ID', {hour: '2-digit', minute: '2-digit'})}</div>
                                ${item.tanggal_kembali ? `
                                    <div class="text-xs text-gray-500 mt-1">Kembali:</div>
                                    <div class="text-xs">${new Date(item.tanggal_kembali).toLocaleDateString('id-ID')}</div>
                                    <div class="text-xs">${new Date(item.tanggal_kembali).toLocaleTimeString('id-ID', {hour: '2-digit', minute: '2-digit'})}</div>
                                ` : ''}
                            </td>
                            <td class="py-2 px-3">
                                <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full ${statusClass}">
                                    <i class="${statusIcon} mr-1"></i>${item.status_display}
                                </span>
                                ${item.kondisi_kembali ? `
                                    <div class="text-xs mt-1 text-gray-600">Kondisi: ${item.kondisi_kembali}</div>
                                ` : ''}
                                <div class="text-xs text-gray-500 mt-1">Res: ${item.reservation_number}</div>
                            </td>
                        </tr>
                    `;
                });
                
                content += `
                            </tbody>
                        </table>
                    </div>
                `;
                
                document.getElementById('borrowingHistoryContent').innerHTML = content;
            } else {
                document.getElementById('borrowingHistoryContent').innerHTML = '<div class="text-center text-red-500 py-8"><i class="fas fa-exclamation-triangle text-2xl mb-2"></i><p>Error loading history</p></div>';
            }
        })
        .catch(error => {
            console.error('Error:', error);
            document.getElementById('borrowingHistoryContent').innerHTML = '<div class="text-center text-red-500 py-8"><i class="fas fa-exclamation-triangle text-2xl mb-2"></i><p>Terjadi kesalahan saat mengambil data history</p></div>';
        });
}

// Close borrowing history modal
function closeBorrowingHistoryModal() {
    document.getElementById('borrowingHistoryModal').classList.add('hidden');
}

// Close modals when clicking outside
document.getElementById('itemDetailsModal').addEventListener('click', function(e) {
    if (e.target === this) {
        closeItemDetailsModal();
    }
});

document.getElementById('borrowingHistoryModal').addEventListener('click', function(e) {
    if (e.target === this) {
        closeBorrowingHistoryModal();
    }
});

// Auto refresh every 30 seconds for real-time updates
setInterval(function() {
    if (!document.getElementById('itemDetailsModal').classList.contains('hidden') || 
        !document.getElementById('borrowingHistoryModal').classList.contains('hidden')) {
        // Don't refresh if modals are open
        return;
    }
    window.location.reload();
}, 30000);

// Add enter key support for history search
document.getElementById('history_search').addEventListener('keypress', function(e) {
    if (e.key === 'Enter') {
        loadBorrowingHistory();
    }
});
</script>

<?php include '../template_it/footer.php'; ?>