<!-- borrower/history.php -->
<?php
require_once '../config/connection.php';
checkUserType(['borrower']);

$borrower_id = $_SESSION['employee_id'];

// Get filter parameters
$status_filter = isset($_GET['status']) ? $_GET['status'] : 'all';
$month_filter = isset($_GET['month']) ? $_GET['month'] : 'all';

// Build WHERE clause based on filters
$where_conditions = ["bh.borrower_employee_id = ?"];
$params = [$borrower_id];

if ($status_filter !== 'all') {
    $where_conditions[] = "bh.status = ?";
    $params[] = $status_filter;
}

if ($month_filter !== 'all') {
    $where_conditions[] = "DATE_FORMAT(bh.created_at, '%Y-%m') = ?";
    $params[] = $month_filter;
}

$where_clause = implode(' AND ', $where_conditions);

// Get all borrow history with filters
$stmt = $pdo->prepare("
    SELECT bh.*, a.asset_name, a.asset_number, a.asset_category, a.kondisi,
           DATEDIFF(IFNULL(bh.tanggal_kembali, NOW()), bh.tanggal_peminjam) as duration_days
    FROM borrow_history bh 
    JOIN assets a ON bh.asset_id = a.id 
    WHERE {$where_clause}
    ORDER BY bh.created_at DESC
");
$stmt->execute($params);
$history = $stmt->fetchAll();

// Get available months for filter
$stmt = $pdo->prepare("
    SELECT DISTINCT DATE_FORMAT(created_at, '%Y-%m') as month_year,
                    DATE_FORMAT(created_at, '%M %Y') as month_name
    FROM borrow_history 
    WHERE borrower_employee_id = ?
    ORDER BY month_year DESC
");
$stmt->execute([$borrower_id]);
$available_months = $stmt->fetchAll();

// Get summary stats
$stats = [
    'total' => count($history),
    'pending' => count(array_filter($history, fn($h) => $h['status'] == 'pending_approval')),
    'borrowed' => count(array_filter($history, fn($h) => $h['status'] == 'borrowed')),
    'returned' => count(array_filter($history, fn($h) => $h['status'] == 'returned'))
];
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Riwayat Peminjaman - Peminjaman Tools Room</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        'leaf-green': '#90EE90',
                        'dark-leaf': '#32CD32',
                        'soft-gray': '#F5F5F5',
                        'medium-gray': '#9CA3AF'
                    }
                }
            }
        }
    </script>
</head>
<body class="bg-soft-gray min-h-screen">
    <!-- Header - Responsive -->
    <header class="bg-white shadow-sm border-b-2 border-leaf-green sticky top-0 z-40">
        <div class="max-w-7xl mx-auto px-3 sm:px-6 lg:px-8">
            <div class="flex justify-between items-center py-3 sm:py-4">
                <div class="flex items-center space-x-2 sm:space-x-4">
                    <a href="dashboard.php" class="text-dark-leaf hover:text-green-600">
                        <svg class="w-5 h-5 sm:w-6 sm:h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 19l-7-7m0 0l7-7m-7 7h18"></path>
                        </svg>
                    </a>
                    <img src="../images/logo.png" alt="Logo" class="h-8 w-8 sm:h-10 sm:w-10" onerror="this.style.display='none'">
                    <div>
                        <h1 class="text-base sm:text-xl font-bold text-gray-800">Riwayat Peminjaman</h1>
                        <p class="text-xs sm:text-sm text-medium-gray hidden sm:block">Lihat semua riwayat peminjaman Anda</p>
                    </div>
                </div>
                <div class="flex items-center space-x-2 sm:space-x-4">
                    <span class="text-xs sm:text-sm text-gray-600 hidden md:inline"><?php echo $_SESSION['user_name']; ?></span>
                    <a href="../logout.php" class="bg-red-500 hover:bg-red-600 text-white px-3 py-1.5 sm:px-4 sm:py-2 rounded-lg text-xs sm:text-sm transition duration-200">
                        Logout
                    </a>
                </div>
            </div>
        </div>
    </header>

    <div class="max-w-7xl mx-auto px-3 sm:px-6 lg:px-8 py-4 sm:py-8">
        <!-- Filters - Responsive -->
        <div class="bg-white rounded-xl shadow-lg p-4 sm:p-6 mb-4 sm:mb-8">
            <h3 class="text-base sm:text-lg font-semibold text-gray-800 mb-3 sm:mb-4">Filter Riwayat</h3>
            
            <form method="GET" class="space-y-3 sm:space-y-0 sm:grid sm:grid-cols-3 sm:gap-4">
                <div>
                    <label for="status" class="block text-xs sm:text-sm font-medium text-gray-700 mb-1 sm:mb-2">Status</label>
                    <select name="status" id="status" class="w-full px-2 py-1.5 sm:px-3 sm:py-2 text-sm border border-gray-300 rounded-lg focus:ring-2 focus:ring-dark-leaf focus:border-dark-leaf">
                        <option value="all" <?php echo $status_filter == 'all' ? 'selected' : ''; ?>>Semua Status</option>
                        <option value="pending_approval" <?php echo $status_filter == 'pending_approval' ? 'selected' : ''; ?>>Menunggu Persetujuan</option>
                        <option value="borrowed" <?php echo $status_filter == 'borrowed' ? 'selected' : ''; ?>>Sedang Dipinjam</option>
                        <option value="returned" <?php echo $status_filter == 'returned' ? 'selected' : ''; ?>>Sudah Dikembalikan</option>
                    </select>
                </div>
                
                <div>
                    <label for="month" class="block text-xs sm:text-sm font-medium text-gray-700 mb-1 sm:mb-2">Bulan</label>
                    <select name="month" id="month" class="w-full px-2 py-1.5 sm:px-3 sm:py-2 text-sm border border-gray-300 rounded-lg focus:ring-2 focus:ring-dark-leaf focus:border-dark-leaf">
                        <option value="all" <?php echo $month_filter == 'all' ? 'selected' : ''; ?>>Semua Bulan</option>
                        <?php foreach ($available_months as $month): ?>
                        <option value="<?php echo $month['month_year']; ?>" <?php echo $month_filter == $month['month_year'] ? 'selected' : ''; ?>>
                            <?php echo $month['month_name']; ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <div class="flex items-end space-x-2">
                    <button type="submit" class="flex-1 sm:flex-none bg-dark-leaf hover:bg-green-600 text-white px-4 sm:px-6 py-1.5 sm:py-2 rounded-lg transition duration-200 text-sm">
                        <svg class="w-3 h-3 sm:w-4 sm:h-4 inline mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 4a1 1 0 011-1h16a1 1 0 011 1v2.586a1 1 0 01-.293.707l-6.414 6.414a1 1 0 00-.293.707V17l-4 4v-6.586a1 1 0 00-.293-.707L3.293 7.414A1 1 0 013 6.707V4z"></path>
                        </svg>
                        Filter
                    </button>
                    <a href="history.php" class="flex-1 sm:flex-none text-center bg-gray-500 hover:bg-gray-600 text-white px-4 sm:px-6 py-1.5 sm:py-2 rounded-lg transition duration-200 text-sm">
                        Reset
                    </a>
                </div>
            </form>
        </div>

        <!-- Quick Stats - Responsive Grid -->
        <div class="grid grid-cols-2 sm:grid-cols-4 gap-3 sm:gap-6 mb-4 sm:mb-8">
            <div class="bg-white rounded-xl shadow-lg p-4 sm:p-6 text-center">
                <div class="text-2xl sm:text-3xl font-bold text-blue-600"><?php echo $stats['total']; ?></div>
                <div class="text-xs sm:text-sm text-medium-gray mt-1">Total</div>
            </div>
            <div class="bg-white rounded-xl shadow-lg p-4 sm:p-6 text-center">
                <div class="text-2xl sm:text-3xl font-bold text-yellow-600"><?php echo $stats['pending']; ?></div>
                <div class="text-xs sm:text-sm text-medium-gray mt-1">Menunggu</div>
            </div>
            <div class="bg-white rounded-xl shadow-lg p-4 sm:p-6 text-center">
                <div class="text-2xl sm:text-3xl font-bold text-green-600"><?php echo $stats['borrowed']; ?></div>
                <div class="text-xs sm:text-sm text-medium-gray mt-1">Dipinjam</div>
            </div>
            <div class="bg-white rounded-xl shadow-lg p-4 sm:p-6 text-center">
                <div class="text-2xl sm:text-3xl font-bold text-purple-600"><?php echo $stats['returned']; ?></div>
                <div class="text-xs sm:text-sm text-medium-gray mt-1">Dikembalikan</div>
            </div>
        </div>

        <!-- History Cards - Responsive -->
        <div class="space-y-3 sm:space-y-4">
            <?php if (empty($history)): ?>
            <div class="bg-white rounded-xl shadow-lg p-6 sm:p-8 text-center">
                <div class="text-medium-gray mb-4">
                    <svg class="w-12 h-12 sm:w-16 sm:h-16 mx-auto" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path>
                    </svg>
                </div>
                <h3 class="text-base sm:text-lg font-semibold text-gray-800 mb-2">Tidak Ada Riwayat</h3>
                <p class="text-sm sm:text-base text-medium-gray mb-4">
                    <?php if ($status_filter !== 'all' || $month_filter !== 'all'): ?>
                        Tidak ada riwayat sesuai filter yang dipilih
                    <?php else: ?>
                        Anda belum memiliki riwayat peminjaman
                    <?php endif; ?>
                </p>
                <div class="flex flex-col sm:flex-row gap-2 sm:gap-2 justify-center">
                    <?php if ($status_filter !== 'all' || $month_filter !== 'all'): ?>
                    <a href="history.php" class="bg-gray-500 hover:bg-gray-600 text-white px-4 sm:px-6 py-2 sm:py-3 rounded-lg transition duration-200 text-sm">
                        Reset Filter
                    </a>
                    <?php endif; ?>
                    <a href="borrow.php" class="bg-dark-leaf hover:bg-green-600 text-white px-4 sm:px-6 py-2 sm:py-3 rounded-lg transition duration-200 text-sm">
                        Ajukan Peminjaman
                    </a>
                </div>
            </div>
            <?php else: ?>
                <?php foreach ($history as $item): ?>
                <div class="bg-white rounded-xl shadow-lg p-4 sm:p-6 cursor-pointer hover:shadow-xl transition duration-300" onclick="toggleDetail(<?php echo $item['id']; ?>)">
                    <!-- Mobile Layout -->
                    <div class="flex flex-col space-y-3 sm:hidden">
                        <div class="flex items-start justify-between">
                            <div class="flex items-start space-x-3 flex-1">
                                <div class="w-3 h-3 rounded-full mt-1 flex-shrink-0 <?php 
                                    echo $item['status'] == 'pending_approval' ? 'bg-yellow-400' : 
                                        ($item['status'] == 'borrowed' ? 'bg-green-400' : 'bg-purple-400'); 
                                ?>"></div>
                                
                                <div class="flex-1 min-w-0">
                                    <h3 class="text-sm font-semibold text-gray-800 break-words"><?php echo $item['asset_name']; ?></h3>
                                    <p class="text-xs text-medium-gray mt-1">
                                        <?php echo $item['asset_number']; ?>
                                    </p>
                                    <p class="text-xs text-medium-gray">
                                        <?php echo $item['asset_category']; ?>
                                    </p>
                                    <?php if ($item['workcenter']): ?>
                                    <p class="text-xs text-medium-gray">
                                        workcenter: <?php echo $item['workcenter']; ?>
                                    </p>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                        
                        <div class="flex items-center justify-between pt-2 border-t border-gray-100">
                            <span class="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium <?php 
                                echo $item['status'] == 'pending_approval' ? 'bg-yellow-100 text-yellow-800' : 
                                    ($item['status'] == 'borrowed' ? 'bg-green-100 text-green-800' : 'bg-purple-100 text-purple-800'); 
                            ?>">
                                <?php 
                                echo $item['status'] == 'pending_approval' ? 'Menunggu' : 
                                    ($item['status'] == 'borrowed' ? 'Dipinjam' : 'Dikembalikan'); 
                                ?>
                            </span>
                            
                            <div class="text-right">
                                <?php if ($item['status'] == 'borrowed' || $item['status'] == 'returned'): ?>
                                <p class="text-xs text-medium-gray">
                                    <?php echo $item['duration_days']; ?> hari
                                    <?php if ($item['status'] == 'borrowed' && $item['duration_days'] > 7): ?>
                                    <span class="text-red-600 font-medium text-xs">(!</span>
                                    <?php endif; ?>
                                </p>
                                <?php endif; ?>
                                <p class="text-xs text-medium-gray">
                                    <?php 
                                    if ($item['tanggal_peminjam']) {
                                        echo date('d/m/Y', strtotime($item['tanggal_peminjam']));
                                    } else {
                                        echo date('d/m/Y', strtotime($item['borrow_date']));
                                    }
                                    ?>
                                </p>
                            </div>
                        </div>
                    </div>

                    <!-- Desktop Layout -->
                    <div class="hidden sm:flex items-center justify-between">
                        <div class="flex items-center space-x-4">
                            <div class="w-4 h-4 rounded-full <?php 
                                echo $item['status'] == 'pending_approval' ? 'bg-yellow-400' : 
                                    ($item['status'] == 'borrowed' ? 'bg-green-400' : 'bg-purple-400'); 
                            ?>"></div>
                            
                            <div>
                                <h3 class="text-lg font-semibold text-gray-800"><?php echo $item['asset_name']; ?></h3>
                                <p class="text-medium-gray">
                                    <?php echo $item['asset_number']; ?> • <?php echo $item['asset_category']; ?>
                                    <?php if ($item['workcenter']): ?>
                                     • workcenter: <?php echo $item['workcenter']; ?>
                                    <?php endif; ?>
                                </p>
                                <p class="text-sm text-gray-500">
                                    Kondisi Asset: <span class="<?php 
                                        echo $item['kondisi'] == 'baik' ? 'text-green-600' : 
                                            ($item['kondisi'] == 'rusak' ? 'text-yellow-600' : 'text-red-600'); 
                                    ?>"><?php echo ucfirst($item['kondisi']); ?></span>
                                </p>
                            </div>
                        </div>
                        
                        <div class="text-right">
                            <span class="inline-flex items-center px-3 py-1 rounded-full text-xs font-medium <?php 
                                echo $item['status'] == 'pending_approval' ? 'bg-yellow-100 text-yellow-800' : 
                                    ($item['status'] == 'borrowed' ? 'bg-green-100 text-green-800' : 'bg-purple-100 text-purple-800'); 
                            ?>">
                                <?php 
                                echo $item['status'] == 'pending_approval' ? 'Menunggu Persetujuan' : 
                                    ($item['status'] == 'borrowed' ? 'Sedang Dipinjam' : 'Dikembalikan'); 
                                ?>
                            </span>
                            
                            <?php if ($item['status'] == 'borrowed' || $item['status'] == 'returned'): ?>
                            <p class="text-sm text-medium-gray mt-1">
                                Durasi: <?php echo $item['duration_days']; ?> hari
                                <?php if ($item['status'] == 'borrowed' && $item['duration_days'] > 7): ?>
                                <span class="text-red-600 font-medium">(Terlambat)</span>
                                <?php endif; ?>
                            </p>
                            <?php endif; ?>
                            
                            <p class="text-sm text-medium-gray mt-1">
                                <?php 
                                if ($item['tanggal_peminjam']) {
                                    echo date('d/m/Y H:i', strtotime($item['tanggal_peminjam']));
                                } else {
                                    echo date('d/m/Y', strtotime($item['borrow_date']));
                                }
                                ?>
                            </p>
                        </div>
                    </div>
                    
                    <!-- Detail Section - Responsive -->
                    <div id="detail-<?php echo $item['id']; ?>" class="hidden mt-4 sm:mt-6 pt-4 sm:pt-6 border-t border-gray-200">
                        <div class="grid grid-cols-1 sm:grid-cols-2 gap-3 sm:gap-4">
                            <div>
                                <p class="text-xs sm:text-sm text-medium-gray">Tanggal Pinjam:</p>
                                <p class="font-medium text-gray-800 text-sm sm:text-base">
                                    <?php 
                                    if ($item['tanggal_peminjam']) {
                                        echo date('d F Y, H:i', strtotime($item['tanggal_peminjam'])) . ' WIB';
                                    } else {
                                        echo date('d F Y', strtotime($item['borrow_date']));
                                    }
                                    ?>
                                </p>
                            </div>
                            
                            <?php if ($item['tanggal_kembali']): ?>
                            <div>
                                <p class="text-xs sm:text-sm text-medium-gray">Tanggal Kembali:</p>
                                <p class="font-medium text-gray-800 text-sm sm:text-base">
                                    <?php echo date('d F Y, H:i', strtotime($item['tanggal_kembali'])) . ' WIB'; ?>
                                </p>
                            </div>
                            <?php endif; ?>
                            
                            <div>
                                <p class="text-xs sm:text-sm text-medium-gray">Preference Pro:</p>
                                <p class="font-medium text-gray-800 text-sm sm:text-base"><?php echo $item['preference_pro']; ?></p>
                            </div>
                            
                            <?php if ($item['workcenter']): ?>
                            <div>
                                <p class="text-xs sm:text-sm text-medium-gray">workcenter:</p>
                                <p class="font-medium text-gray-800 text-sm sm:text-base"><?php echo $item['workcenter']; ?></p>
                            </div>
                            <?php endif; ?>
                            
                            <div>
                                <p class="text-xs sm:text-sm text-medium-gray">Organisasi:</p>
                                <p class="font-medium text-gray-800 text-sm sm:text-base"><?php echo $item['organization']; ?></p>
                            </div>
                            
                            <div>
                                <p class="text-xs sm:text-sm text-medium-gray">Diajukan:</p>
                                <p class="font-medium text-gray-800 text-sm sm:text-base"><?php echo date('d/m/Y H:i', strtotime($item['created_at'])); ?></p>
                            </div>
                            
                            <?php if ($item['kondisi_kembali']): ?>
                            <div>
                                <p class="text-xs sm:text-sm text-medium-gray">Kondisi Saat Kembali:</p>
                                <p class="font-medium text-sm sm:text-base <?php 
                                    echo $item['kondisi_kembali'] == 'baik' ? 'text-green-600' : 
                                        ($item['kondisi_kembali'] == 'rusak' ? 'text-yellow-600' : 'text-red-600'); 
                                ?>">
                                    <?php echo ucfirst($item['kondisi_kembali']); ?>
                                </p>
                            </div>
                            <?php endif; ?>
                            
                            <?php if ($item['notes']): ?>
                            <div class="sm:col-span-2">
                                <p class="text-xs sm:text-sm text-medium-gray">Catatan:</p>
                                <p class="font-medium text-gray-800 text-sm sm:text-base"><?php echo nl2br(htmlspecialchars($item['notes'])); ?></p>
                            </div>
                            <?php endif; ?>
                            
                            <?php if ($item['foto_kembali']): ?>
                            <div class="sm:col-span-2">
                                <p class="text-xs sm:text-sm text-medium-gray mb-2">Foto Pengembalian:</p>
                                <img src="data:image/jpeg;base64,<?php echo base64_encode($item['foto_kembali']); ?>" 
                                     alt="Foto Pengembalian" 
                                     class="w-full sm:max-w-xs rounded-lg shadow-md cursor-pointer" 
                                     onclick="showImageModal(this.src)">
                            </div>
                            <?php endif; ?>
                        </div>
                        
                        <!-- Quick Actions - Responsive -->
                        <?php if ($item['status'] == 'borrowed'): ?>
                        <div class="mt-4 p-3 bg-green-50 rounded-lg">
                            <p class="text-xs sm:text-sm text-green-700 mb-2">Asset ini sedang Anda pinjam</p>
                            <a href="return.php" class="inline-flex items-center px-3 py-1.5 sm:py-2 bg-purple-500 text-white rounded text-xs sm:text-sm hover:bg-purple-600 transition duration-200">
                                <svg class="w-3 h-3 sm:w-4 sm:h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 10h10a8 8 0 018 8v2M3 10l6 6m-6-6l6-6"></path>
                                </svg>
                                Kembalikan
                            </a>
                        </div>
                        <?php endif; ?>
                    </div>
                </div>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>

        <!-- Back to Dashboard - Responsive -->
        <div class="mt-6 sm:mt-8 text-center">
            <a href="dashboard.php" class="bg-dark-leaf hover:bg-green-600 text-white px-5 py-2.5 sm:px-6 sm:py-3 rounded-lg transition duration-200 inline-flex items-center space-x-2 text-sm sm:text-base">
                <svg class="w-4 h-4 sm:w-5 sm:h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6"></path>
                </svg>
                <span>Kembali ke Dashboard</span>
            </a>
        </div>
    </div>

    <!-- Image Modal - Responsive -->
    <div id="imageModal" class="fixed inset-0 bg-black bg-opacity-75 hidden z-50 flex items-center justify-center p-4" onclick="hideImageModal()">
        <div class="max-w-full max-h-full">
            <img id="modalImage" src="" alt="Full Size Image" class="max-w-full max-h-[90vh] rounded-lg">
        </div>
    </div>

    <script>
        function toggleDetail(id) {
            const detail = document.getElementById('detail-' + id);
            const isHidden = detail.classList.contains('hidden');
            
            // Hide all other details
            document.querySelectorAll('[id^="detail-"]').forEach(el => {
                el.classList.add('hidden');
            });
            
            // Toggle current detail
            if (isHidden) {
                detail.classList.remove('hidden');
            }
        }

        function showImageModal(src) {
            document.getElementById('modalImage').src = src;
            document.getElementById('imageModal').classList.remove('hidden');
            document.body.style.overflow = 'hidden';
        }

        function hideImageModal() {
            document.getElementById('imageModal').classList.add('hidden');
            document.body.style.overflow = 'auto';
        }

        // Keyboard navigation for modal
        document.addEventListener('keydown', function(e) {
            if (e.key === 'Escape') {
                hideImageModal();
            }
        });

        // Prevent modal close when clicking image
        document.getElementById('modalImage').addEventListener('click', function(e) {
            e.stopPropagation();
        });
    </script>
</body>
</html>