<?php
// lacak_peminjaman_it.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
log_activity($conn, $it_id, 'it', 'Track Borrowing Access', '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,
                        mcp.code_color,
                        mcp.deskripsi as color_deskripsi,
                        b.nama_buyer,
                        b.kode_buyer,
                        cc.component_name,
                        ti.lokasi_asal,
                        ti.lokasi_tujuan,
                        ti.tanggal_kembali as target_kembali,
                        ti.catatan,
                        st.reservation_number,
                        st.tanggal_transaksi,
                        st.tanggal_pengembalian,
                        st.keterangan as transaksi_keterangan,
                        bu.username as peminjam_name,
                        bu.email as peminjam_email,
                        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) 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 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();
}

// 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,
                  mcp.code_color,
                  mcp.deskripsi,
                  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.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 ?)";
    $search_param = "%$search_term%";
    $params = array_merge($params, [$search_param, $search_param, $search_param, $search_param]);
    $types .= "ssss";
}

$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
                FROM color_stock_items csi
                JOIN transaction_items ti ON csi.id = ti.stock_item_id
                JOIN stock_transactions st ON ti.transaction_id = st.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-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-6 mb-6">
        <h2 class="text-2xl font-bold text-gray-800 mb-4">
            <i class="fas fa-search-location mr-2"></i>
            Lacak Peminjaman Barang
        </h2>
        <p class="text-gray-600">
            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>

    <!-- Statistics Cards - Only 2 status -->
    <div class="mb-6 grid grid-cols-1 md:grid-cols-2 gap-4">
        <div class="bg-white 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-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-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-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>

    <!-- Filters -->
    <div class="bg-white rounded-lg shadow-md p-6 mb-6">
        <h3 class="text-lg font-semibold text-gray-800 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-6">
        <div class="flex justify-between items-center mb-4">
            <h3 class="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-gray-900">' . htmlspecialchars($item['kode_barang']) . '</div>';
                        echo '<div class="text-gray-500">Stock #' . $item['stock_number'] . '</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">' . htmlspecialchars($item['deskripsi']) . '</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>';
                        echo '<div class="text-gray-500">' . 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>

<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"><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';
                }
                
                // Overdue information
                let overdueInfo = '';
                if (item.status_waktu_tracking === 'Overdue' && item.menit_terlambat > 0) {
                    const jamTerlambat = Math.floor(item.menit_terlambat / 60);
                    const menitTerlambat = item.menit_terlambat % 60;
                    let terlambatDisplay = '';
                    if (jamTerlambat > 0) {
                        terlambatDisplay = jamTerlambat + ' jam ' + menitTerlambat + ' menit';
                    } else {
                        terlambatDisplay = menitTerlambat + ' menit';
                    }
                    overdueInfo = `
                        <div class="bg-red-50 border border-red-200 rounded-lg p-3">
                            <div class="flex items-center">
                                <i class="fas fa-exclamation-triangle text-red-500 mr-2"></i>
                                <span class="text-red-700 font-medium">Terlambat: ${terlambatDisplay}</span>
                            </div>
                        </div>
                    `;
                }
                
                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</div>
                                    <div class="font-mono font-bold text-blue-600">${item.kode_barang}</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">Deskripsi</div>
                                    <div class="text-sm">${item.color_deskripsi}</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">Lokasi Rack</div>
                                    <div class="text-sm">${item.rack_no || 'N/A'}</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>
                                    <div class="text-xs text-gray-500">${item.peminjam_email}</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">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>

                        <!-- 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 ? `
                        <div class="space-y-2">
                            ${item.catatan ? `
                            <div>
                                <div class="text-xs text-gray-500 mb-1">Catatan</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>
                            ` : ''}
                        </div>
                        ` : ''}
                    </div>
                `;
                
                document.getElementById('itemDetailsContent').innerHTML = content;
            } else {
                document.getElementById('itemDetailsContent').innerHTML = '<div class="text-center text-red-500"><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"><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');
}

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

// Auto refresh every 30 seconds for real-time updates
setInterval(function() {
    window.location.reload();
}, 30000);
</script>

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