<?php
require_once "config/connection.php";

if (!isset($_POST['kode_barang'])) {
    echo "Invalid request";
    exit;
}

$kode_barang = $_POST['kode_barang'];

// Get detailed borrowed item information
$sql = "SELECT 
            csi.*,
            cc.component_name,
            mcp.code_color,
            mcp.deskripsi as color_description,
            mcp.lemari,
            b.nama_buyer,
            b.kode_buyer,
            c.nama_collection_semarang,
            bu.nama_borrower,
            bu.nik,
            bu.lokasi_posisi as borrower_position,
            bu.email as borrower_email,
            st.id as transaction_id,
            st.reservation_number,
            st.tanggal_transaksi,
            st.tanggal_pengembalian,
            st.keterangan as transaction_notes,
            st.status_peminjaman,
            ti.id as transaction_item_id,
            ti.lokasi_asal,
            ti.lokasi_tujuan,
            ti.status_waktu,
            ti.catatan as item_notes,
            ti.foto_bukti,
            ti.foto_pengembalian
        FROM color_stock_items_semarang csi
        JOIN color_components_semarang cc ON csi.component_id = cc.id
        JOIN master_color_panel_semarang mcp ON csi.color_id = mcp.id
        JOIN buyers_semarang b ON mcp.buyer_id = b.id
        JOIN collection_semarangs c ON mcp.collection_semarang_id = c.id
        JOIN transaction_items_semarang ti ON csi.id = ti.stock_item_id
        JOIN stock_transactions_semarang st ON ti.transaction_id = st.id
        JOIN borrower_users_semarang bu ON st.borrower_id = bu.id
        WHERE csi.kode_barang = ? 
        AND ti.dikembalikan = 0 
        AND csi.status = 'Dipinjam'
        ORDER BY ti.id DESC 
        LIMIT 1";

$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $kode_barang);
$stmt->execute();
$borrowedItem = $stmt->get_result()->fetch_assoc();

if (!$borrowedItem) {
    echo "<div class='text-center py-8'>";
    echo "<div class='text-gray-500'>";
    echo "<i class='fas fa-exclamation-triangle text-4xl mb-4'></i>";
    echo "<p class='text-lg'>Item not found or not currently borrowed</p>";
    echo "</div>";
    echo "</div>";
    exit;
}

// Calculate time status and overdue information
$now = new DateTime();
$dueDate = new DateTime($borrowedItem['tanggal_pengembalian']);
$dueDateWithTolerance = clone $dueDate;
$dueDateWithTolerance->add(new DateInterval('PT15M')); // Add 15 minutes tolerance

$isOverdue = $now > $dueDateWithTolerance;
$timeRemaining = '';
$overdueBy = '';

if ($isOverdue) {
    $interval = $now->diff($dueDateWithTolerance);
    $totalMinutes = ($interval->days * 24 * 60) + ($interval->h * 60) + $interval->i;
    $overdueBy = $totalMinutes . ' minutes';
} else {
    $interval = $now->diff($dueDateWithTolerance);
    $totalMinutes = ($interval->days * 24 * 60) + ($interval->h * 60) + $interval->i;
    $timeRemaining = $totalMinutes . ' minutes';
}

function getStatusBadgeClass($status) {
    switch ($status) {
        case 'Tersedia':
            return 'bg-green-100 text-green-800';
        case 'Dipinjam':
            return 'bg-orange-100 text-orange-800';
        case 'Rusak':
            return 'bg-red-100 text-red-800';
        case 'Expired':
            return 'bg-purple-100 text-purple-800';
        case 'Hilang':
            return 'bg-gray-100 text-gray-800';
        default:
            return 'bg-gray-100 text-gray-800';
    }
}
?>

<div class="space-y-6">
    <!-- Alert for Overdue Status -->
    <?php if ($isOverdue): ?>
        <div class="bg-red-50 border-l-4 border-red-400 p-4">
            <div class="flex">
                <div class="flex-shrink-0">
                    <i class="fas fa-exclamation-triangle text-red-400"></i>
                </div>
                <div class="ml-3">
                    <h3 class="text-sm font-medium text-red-800">Overdue Item</h3>
                    <div class="mt-2 text-sm text-red-700">
                        <p>This item is overdue by <strong><?= $overdueBy ?></strong></p>
                        <p>Due date was: <?= date('d/m/Y H:i', strtotime($borrowedItem['tanggal_pengembalian'])) ?></p>
                    </div>
                </div>
            </div>
        </div>
    <?php elseif ($timeRemaining): ?>
        <div class="bg-yellow-50 border-l-4 border-yellow-400 p-4">
            <div class="flex">
                <div class="flex-shrink-0">
                    <i class="fas fa-clock text-yellow-400"></i>
                </div>
                <div class="ml-3">
                    <h3 class="text-sm font-medium text-yellow-800">Due Soon</h3>
                    <div class="mt-2 text-sm text-yellow-700">
                        <p>Time remaining: <strong><?= $timeRemaining ?></strong></p>
                        <p>Due date: <?= date('d/m/Y H:i', strtotime($borrowedItem['tanggal_pengembalian'])) ?></p>
                    </div>
                </div>
            </div>
        </div>
    <?php endif; ?>

    <!-- Item Information -->
    <div class="bg-gray-50 rounded-lg p-6">
        <h3 class="text-lg font-semibold text-gray-800 mb-4">
            <i class="fas fa-box mr-2"></i>Item Information
        </h3>
        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div class="space-y-3">
                <div class="flex justify-between">
                    <span class="font-medium text-gray-600">Code Barang:</span>
                    <span class="font-semibold text-gray-800"><?= htmlspecialchars($borrowedItem['kode_barang']) ?></span>
                </div>
                <div class="flex justify-between">
                    <span class="font-medium text-gray-600">Color Code:</span>
                    <span class="font-semibold text-green-600"><?= htmlspecialchars($borrowedItem['code_color']) ?></span>
                </div>
                <div class="flex justify-between">
                    <span class="font-medium text-gray-600">Component:</span>
                    <span class="font-semibold text-gray-800"><?= htmlspecialchars($borrowedItem['component_name']) ?></span>
                </div>
                <div class="flex justify-between">
                    <span class="font-medium text-gray-600">Stock Number:</span>
                    <span class="font-semibold text-gray-800"><?= $borrowedItem['stock_number'] ?></span>
                </div>
                <div class="flex justify-between">
                    <span class="font-medium text-gray-600">Status:</span>
                    <span class="inline-block px-2 py-1 rounded text-xs font-semibold <?= getStatusBadgeClass($borrowedItem['status']) ?>">
                        <?= htmlspecialchars($borrowedItem['status']) ?>
                    </span>
                </div>
            </div>
            <div class="space-y-3">
                <div class="flex justify-between">
                    <span class="font-medium text-gray-600">Buyer:</span>
                    <span class="font-semibold text-gray-800"><?= htmlspecialchars($borrowedItem['nama_buyer']) ?></span>
                </div>
                <div class="flex justify-between">
                    <span class="font-medium text-gray-600">collection_semarang:</span>
                    <span class="font-semibold text-gray-800"><?= htmlspecialchars($borrowedItem['nama_collection_semarang']) ?></span>
                </div>
                <div class="flex justify-between">
                    <span class="font-medium text-gray-600">Rack:</span>
                    <span class="font-semibold text-gray-800"><?= htmlspecialchars($borrowedItem['lemari']) ?>.<?= htmlspecialchars($borrowedItem['rack_no']) ?></span>
                </div>
                <div class="flex justify-between">
                    <span class="font-medium text-gray-600">Original Location:</span>
                    <span class="font-semibold text-gray-800"><?= htmlspecialchars($borrowedItem['lokasi']) ?></span>
                </div>
                <?php if ($borrowedItem['tanggal_kedaluwarsa']): ?>
                <div class="flex justify-between">
                    <span class="font-medium text-gray-600">Expires:</span>
                    <span class="font-semibold text-gray-800"><?= date('d/m/Y', strtotime($borrowedItem['tanggal_kedaluwarsa'])) ?></span>
                </div>
                <?php endif; ?>
            </div>
        </div>
        
        <?php if ($borrowedItem['color_description']): ?>
        <div class="mt-4 pt-4 border-t border-gray-200">
            <div class="flex justify-between">
                <span class="font-medium text-gray-600">Description:</span>
                <span class="text-gray-800"><?= htmlspecialchars($borrowedItem['color_description']) ?></span>
            </div>
        </div>
        <?php endif; ?>
    </div>

    <!-- Borrower Information -->
    <div class="bg-blue-50 rounded-lg p-6">
        <h3 class="text-lg font-semibold text-gray-800 mb-4">
            <i class="fas fa-user mr-2"></i>Borrower Information
        </h3>
        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div class="space-y-3">
                <div class="flex justify-between">
                    <span class="font-medium text-gray-600">Name:</span>
                    <span class="font-semibold text-gray-800"><?= htmlspecialchars($borrowedItem['nama_borrower']) ?></span>
                </div>
                <div class="flex justify-between">
                    <span class="font-medium text-gray-600">NIK:</span>
                    <span class="font-semibold text-gray-800"><?= htmlspecialchars($borrowedItem['nik']) ?></span>
                </div>
                <div class="flex justify-between">
                    <span class="font-medium text-gray-600">Position:</span>
                    <span class="font-semibold text-gray-800"><?= htmlspecialchars($borrowedItem['borrower_position']) ?></span>
                </div>
            </div>
            <div class="space-y-3">
                <div class="flex justify-between">
                    <span class="font-medium text-gray-600">Email:</span>
                    <span class="font-semibold text-gray-800"><?= htmlspecialchars($borrowedItem['borrower_email']) ?></span>
                </div>
                <div class="flex justify-between">
                    <span class="font-medium text-gray-600">Work Location:</span>
                    <span class="font-semibold text-gray-800"><?= htmlspecialchars($borrowedItem['borrower_position']) ?></span>
                </div>
            </div>
        </div>
    </div>

    <!-- Transaction Information -->
    <div class="bg-green-50 rounded-lg p-6">
        <h3 class="text-lg font-semibold text-gray-800 mb-4">
            <i class="fas fa-exchange-alt mr-2"></i>Transaction Information
        </h3>
        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div class="space-y-3">
                <div class="flex justify-between">
                    <span class="font-medium text-gray-600">Reservation Number:</span>
                    <span class="font-semibold text-blue-600"><?= htmlspecialchars($borrowedItem['reservation_number']) ?></span>
                </div>
                <div class="flex justify-between">
                    <span class="font-medium text-gray-600">Borrowed Date:</span>
                    <span class="font-semibold text-gray-800"><?= date('d/m/Y H:i', strtotime($borrowedItem['tanggal_transaksi'])) ?></span>
                </div>
                <div class="flex justify-between">
                    <span class="font-medium text-gray-600">Due Date:</span>
                    <span class="font-semibold text-gray-800"><?= date('d/m/Y H:i', strtotime($borrowedItem['tanggal_pengembalian'])) ?></span>
                </div>
                <div class="flex justify-between">
                    <span class="font-medium text-gray-600">Due Date + Tolerance:</span>
                    <span class="font-semibold text-orange-600"><?= $dueDateWithTolerance->format('d/m/Y H:i') ?></span>
                </div>
            </div>
            <div class="space-y-3">
                <div class="flex justify-between">
                    <span class="font-medium text-gray-600">From Location:</span>
                    <span class="font-semibold text-gray-800"><?= htmlspecialchars($borrowedItem['lokasi_asal'] ?? 'Color Room') ?></span>
                </div>
                <div class="flex justify-between">
                    <span class="font-medium text-gray-600">To Location:</span>
                    <span class="font-semibold text-gray-800"><?= htmlspecialchars($borrowedItem['lokasi_tujuan']) ?></span>
                </div>
                <div class="flex justify-between">
                    <span class="font-medium text-gray-600">Time Status:</span>
                    <?php if ($isOverdue): ?>
                        <span class="inline-block px-2 py-1 rounded text-xs font-semibold bg-red-100 text-red-800">OVERDUE</span>
                    <?php elseif ($borrowedItem['status_waktu'] === 'tepat'): ?>
                        <span class="inline-block px-2 py-1 rounded text-xs font-semibold bg-green-100 text-green-800">ON TIME</span>
                    <?php else: ?>
                        <span class="inline-block px-2 py-1 rounded text-xs font-semibold bg-blue-100 text-blue-800">ONGOING</span>
                    <?php endif; ?>
                </div>
                <div class="flex justify-between">
                    <span class="font-medium text-gray-600">Loan Status:</span>
                    <span class="inline-block px-2 py-1 rounded text-xs font-semibold bg-orange-100 text-orange-800">
                        <?= htmlspecialchars($borrowedItem['status_peminjaman']) ?>
                    </span>
                </div>
            </div>
        </div>

        <?php if ($borrowedItem['transaction_notes']): ?>
        <div class="mt-4 pt-4 border-t border-gray-200">
            <div>
                <span class="font-medium text-gray-600">Transaction Notes:</span>
                <p class="text-gray-800 mt-1 text-sm"><?= htmlspecialchars($borrowedItem['transaction_notes']) ?></p>
            </div>
        </div>
        <?php endif; ?>

        <?php if ($borrowedItem['item_notes']): ?>
        <div class="mt-4 pt-4 border-t border-gray-200">
            <div>
                <span class="font-medium text-gray-600">Item Notes:</span>
                <p class="text-gray-800 mt-1 text-sm"><?= htmlspecialchars($borrowedItem['item_notes']) ?></p>
            </div>
        </div>
        <?php endif; ?>
    </div>

    <!-- Time Analysis -->
    <div class="bg-white border rounded-lg p-6">
        <h3 class="text-lg font-semibold text-gray-800 mb-4">
            <i class="fas fa-chart-line mr-2"></i>Time Analysis
        </h3>
        <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
            <div class="text-center">
                <div class="text-2xl font-bold text-blue-600">
                    <?php
                    $borrowedInterval = $now->diff(new DateTime($borrowedItem['tanggal_transaksi']));
                    $totalBorrowedMinutes = ($borrowedInterval->days * 24 * 60) + ($borrowedInterval->h * 60) + $borrowedInterval->i;
                    echo $totalBorrowedMinutes;
                    ?>
                </div>
                <div class="text-sm text-gray-600">Minutes Borrowed</div>
            </div>
            <div class="text-center">
                <div class="text-2xl font-bold <?= $isOverdue ? 'text-red-600' : 'text-green-600' ?>">
                    <?= $isOverdue ? $overdueBy : $timeRemaining ?>
                </div>
                <div class="text-sm text-gray-600"><?= $isOverdue ? 'Overdue By' : 'Time Remaining' ?></div>
            </div>
            <div class="text-center">
                <div class="text-2xl font-bold text-gray-600">
                    <?php
                    $plannedInterval = (new DateTime($borrowedItem['tanggal_pengembalian']))->diff(new DateTime($borrowedItem['tanggal_transaksi']));
                    $plannedMinutes = ($plannedInterval->days * 24 * 60) + ($plannedInterval->h * 60) + $plannedInterval->i;
                    echo $plannedMinutes;
                    ?>
                </div>
                <div class="text-sm text-gray-600">Planned Duration (minutes)</div>
            </div>
        </div>
        
        <!-- Progress Bar -->
        <div class="mt-6">
            <div class="flex justify-between text-sm text-gray-600 mb-2">
                <span>Borrowed</span>
                <span>Due Date + Tolerance</span>
            </div>
            <div class="w-full bg-gray-200 rounded-full h-2.5">
                <?php
                $totalPlannedWithTolerance = $plannedMinutes + 15; // Add 15 minutes tolerance
                $progressPercentage = min(100, ($totalBorrowedMinutes / $totalPlannedWithTolerance) * 100);
                $progressColor = $isOverdue ? 'bg-red-500' : ($progressPercentage > 80 ? 'bg-yellow-500' : 'bg-green-500');
                ?>
                <div class="<?= $progressColor ?> h-2.5 rounded-full transition-all duration-300" 
                     style="width: <?= $progressPercentage ?>%"></div>
            </div>
            <div class="flex justify-between text-xs text-gray-500 mt-1">
                <span><?= date('d/m/Y H:i', strtotime($borrowedItem['tanggal_transaksi'])) ?></span>
                <span><?= $dueDateWithTolerance->format('d/m/Y H:i') ?></span>
            </div>
        </div>
    </div>

    <!-- Additional Photos (if available) -->
    <?php if ($borrowedItem['foto_bukti'] || $borrowedItem['foto_pengembalian']): ?>
    <div class="bg-gray-50 rounded-lg p-6">
        <h3 class="text-lg font-semibold text-gray-800 mb-4">
            <i class="fas fa-camera mr-2"></i>Photo Evidence
        </h3>
        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
            <?php if ($borrowedItem['foto_bukti']): ?>
            <div>
                <h4 class="font-medium text-gray-700 mb-2">Condition Photo</h4>
                <img src="data:image/jpeg;base64,<?= $borrowedItem['foto_bukti'] ?>" 
                     alt="Item Condition" 
                     class="w-full h-48 object-cover rounded-lg border">
            </div>
            <?php endif; ?>
            
            <?php if ($borrowedItem['foto_pengembalian']): ?>
            <div>
                <h4 class="font-medium text-gray-700 mb-2">Return Photo</h4>
                <img src="data:image/jpeg;base64,<?= $borrowedItem['foto_pengembalian'] ?>" 
                     alt="Return Location" 
                     class="w-full h-48 object-cover rounded-lg border">
            </div>
            <?php endif; ?>
        </div>
    </div>
    <?php endif; ?>

    <!-- Action Buttons -->
    <div class="flex justify-end space-x-3 pt-4 border-t border-gray-200">
        <button onclick="printBorrowedDetails()" 
                class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition duration-300">
            <i class="fas fa-print mr-2"></i>Print Details
        </button>
        <button onclick="refreshBorrowedDetails('<?= $borrowedItem['kode_barang'] ?>')" 
                class="px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition duration-300">
            <i class="fas fa-sync-alt mr-2"></i>Refresh
        </button>
    </div>
</div>

<script>
function printBorrowedDetails() {
    window.print();
}

function refreshBorrowedDetails(kodeBarang) {
    // Reload the borrowed details
    parent.showBorrowedDetails(kodeBarang);
}

// Auto-refresh every 30 seconds if item is overdue
<?php if ($isOverdue): ?>
setInterval(() => {
    refreshBorrowedDetails('<?= $borrowedItem['kode_barang'] ?>');
}, 30000);
<?php endif; ?>
</script>

<style>
@media print {
    .no-print {
        display: none !important;
    }
    
    body {
        font-size: 12px;
    }
    
    .bg-red-50, .bg-yellow-50, .bg-blue-50, .bg-green-50, .bg-gray-50 {
        background-color: #f9f9f9 !important;
    }
}
</style>