<?php
require_once '../config/connection.php';
checkUserType(['superadmin']);

// Get all assets with borrower info and history count
$stmt = $pdo->prepare("
    SELECT a.*, 
           bh.borrower_employee_id, 
           b.full_name as borrower_name,
           bh.borrow_date,
           bh.notes as borrow_notes,
           COUNT(DISTINCT bh2.id) as borrow_count
    FROM assets a 
    LEFT JOIN borrow_history bh ON a.id = bh.asset_id AND bh.status = 'borrowed'
    LEFT JOIN borrowers b ON bh.borrower_employee_id = b.employee_id
    LEFT JOIN borrow_history bh2 ON a.id = bh2.asset_id
    GROUP BY a.id
    ORDER BY a.asset_number ASC
");
$stmt->execute();
$assets = $stmt->fetchAll();

// Group assets by status
$available_assets = array_filter($assets, fn($a) => $a['status_borrower'] == 'available');
$borrowed_assets = array_filter($assets, fn($a) => $a['status_borrower'] == 'borrowed');
$maintenance_assets = array_filter($assets, fn($a) => $a['status_borrower'] == 'maintenance');
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Kelola Asset - 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 -->
    <header class="bg-white shadow-sm border-b-2 border-leaf-green">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div class="flex justify-between items-center py-4">
                <div class="flex items-center space-x-4">
                    <a href="dashboard.php" class="text-dark-leaf hover:text-green-600">
                        <svg class="w-6 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-10 w-10" onerror="this.style.display='none'">
                    <div>
                        <h1 class="text-xl font-bold text-gray-800">Kelola Asset</h1>
                        <p class="text-sm text-medium-gray">Full CRUD asset management</p>
                    </div>
                </div>
                <div class="flex items-center space-x-4">
                    <a href="add.php?type=asset" class="bg-dark-leaf hover:bg-green-600 text-white px-4 py-2 rounded-lg text-sm transition duration-200 flex items-center space-x-2">
                        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"></path>
                        </svg>
                        <span>Tambah Asset</span>
                    </a>
                    <span class="text-sm text-gray-600"><?php echo $_SESSION['user_name']; ?></span>
                    <a href="../logout.php" class="bg-red-500 hover:bg-red-600 text-white px-4 py-2 rounded-lg text-sm transition duration-200">
                        Logout
                    </a>
                </div>
            </div>
        </div>
    </header>

    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <!-- Stats Cards -->
        <div class="grid grid-cols-1 md:grid-cols-4 gap-6 mb-8">
            <!-- Total Assets -->
            <div class="bg-white rounded-xl shadow-lg p-6 cursor-pointer hover:shadow-xl transition duration-300 border-l-4 border-blue-400" onclick="showAssets('all')">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-medium-gray text-sm font-medium">Total Asset</p>
                        <p class="text-3xl font-bold text-blue-600"><?php echo count($assets); ?></p>
                    </div>
                    <div class="bg-blue-100 p-3 rounded-full">
                        <svg class="w-6 h-6 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4"></path>
                        </svg>
                    </div>
                </div>
            </div>

            <!-- Available Assets -->
            <div class="bg-white rounded-xl shadow-lg p-6 cursor-pointer hover:shadow-xl transition duration-300 border-l-4 border-green-400" onclick="showAssets('available')">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-medium-gray text-sm font-medium">Tersedia</p>
                        <p class="text-3xl font-bold text-green-600"><?php echo count($available_assets); ?></p>
                    </div>
                    <div class="bg-green-100 p-3 rounded-full">
                        <svg class="w-6 h-6 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path>
                        </svg>
                    </div>
                </div>
            </div>

            <!-- Borrowed Assets -->
            <div class="bg-white rounded-xl shadow-lg p-6 cursor-pointer hover:shadow-xl transition duration-300 border-l-4 border-yellow-400" onclick="showAssets('borrowed')">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-medium-gray text-sm font-medium">Dipinjam</p>
                        <p class="text-3xl font-bold text-yellow-600"><?php echo count($borrowed_assets); ?></p>
                    </div>
                    <div class="bg-yellow-100 p-3 rounded-full">
                        <svg class="w-6 h-6 text-yellow-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                        </svg>
                    </div>
                </div>
            </div>

            <!-- Maintenance Assets -->
            <div class="bg-white rounded-xl shadow-lg p-6 cursor-pointer hover:shadow-xl transition duration-300 border-l-4 border-red-400" onclick="showAssets('maintenance')">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-medium-gray text-sm font-medium">Maintenance</p>
                        <p class="text-3xl font-bold text-red-600"><?php echo count($maintenance_assets); ?></p>
                    </div>
                    <div class="bg-red-100 p-3 rounded-full">
                        <svg class="w-6 h-6 text-red-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z"></path>
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"></path>
                        </svg>
                    </div>
                </div>
            </div>
        </div>

        <!-- Filter and Search -->
        <div class="bg-white rounded-xl shadow-lg p-6 mb-8">
            <div class="flex flex-col lg:flex-row lg:items-center lg:justify-between gap-4 mb-6">
                <div class="flex flex-wrap gap-2">
                    <button onclick="showAssets('all')" id="tab-all" class="tab-button active px-4 py-2 rounded-lg text-sm font-medium transition duration-200">
                        Semua Asset
                    </button>
                    <button onclick="showAssets('available')" id="tab-available" class="tab-button px-4 py-2 rounded-lg text-sm font-medium transition duration-200">
                        Tersedia
                    </button>
                    <button onclick="showAssets('borrowed')" id="tab-borrowed" class="tab-button px-4 py-2 rounded-lg text-sm font-medium transition duration-200">
                        Dipinjam
                    </button>
                    <button onclick="showAssets('maintenance')" id="tab-maintenance" class="tab-button px-4 py-2 rounded-lg text-sm font-medium transition duration-200">
                        Maintenance
                    </button>
                </div>
                <div class="flex space-x-2">
                    <input type="text" id="searchInput" placeholder="Cari asset..." 
                           class="px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-dark-leaf focus:border-dark-leaf"
                           onkeyup="searchAssets()">
                    <select id="categoryFilter" onchange="filterByCategory()" 
                            class="px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-dark-leaf focus:border-dark-leaf">
                        <option value="">Semua Kategori</option>
                        <option value="Electronics">Electronics</option>
                        <option value="Tools">Tools</option>
                        <option value="Furniture">Furniture</option>
                        <option value="Vehicle">Vehicle</option>
                        <option value="Others">Others</option>
                    </select>
                </div>
            </div>

            <!-- Assets List -->
            <div id="assets-container">
                <!-- All Assets (Default) -->
                <div id="assets-all" class="assets-section">
                    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                        <?php foreach ($assets as $asset): ?>
                        <div class="asset-card bg-soft-gray rounded-lg p-4 hover:bg-gray-100 transition duration-200" 
                             data-category="<?php echo $asset['asset_category']; ?>"
                             data-name="<?php echo strtolower($asset['asset_name'] . ' ' . $asset['asset_number']); ?>">
                            <div class="flex justify-between items-start mb-3">
                                <div class="flex-1 cursor-pointer" onclick="showAssetDetail(<?php echo $asset['id']; ?>)">
                                    <h4 class="font-semibold text-gray-800"><?php echo $asset['asset_name']; ?></h4>
                                    <p class="text-sm text-medium-gray"><?php echo $asset['asset_number']; ?></p>
                                    <p class="text-xs text-medium-gray"><?php echo $asset['asset_category']; ?></p>
                                </div>
                                <div class="flex flex-col items-end space-y-2">
                                    <span class="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium 
                                        <?php echo $asset['status_borrower'] == 'available' ? 'bg-green-100 text-green-800' : 
                                             ($asset['status_borrower'] == 'borrowed' ? 'bg-yellow-100 text-yellow-800' : 'bg-red-100 text-red-800'); ?>">
                                        <?php echo $asset['status_borrower'] == 'available' ? 'Tersedia' : 
                                             ($asset['status_borrower'] == 'borrowed' ? 'Dipinjam' : 'Maintenance'); ?>
                                    </span>
                                    <div class="flex space-x-1">
                                        <a href="update.php?id=<?php echo $asset['id']; ?>" class="bg-blue-500 hover:bg-blue-600 text-white p-1 rounded text-xs transition duration-200">
                                            <svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"></path>
                                            </svg>
                                        </a>
                                        <button onclick="deleteAsset(<?php echo $asset['id']; ?>, '<?php echo $asset['asset_name']; ?>')" 
                                                class="bg-red-500 hover:bg-red-600 text-white p-1 rounded text-xs transition duration-200">
                                            <svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path>
                                            </svg>
                                        </button>
                                    </div>
                                </div>
                            </div>
                            <?php if ($asset['status_borrower'] == 'borrowed' && $asset['borrower_name']): ?>
                            <div class="mt-2 p-2 bg-yellow-50 rounded border-l-2 border-yellow-400">
                                <p class="text-xs text-yellow-700">Dipinjam: <?php echo $asset['borrower_name']; ?></p>
                                <p class="text-xs text-yellow-600">Sejak: <?php echo date('d/m/Y', strtotime($asset['borrow_date'])); ?></p>
                            </div>
                            <?php endif; ?>
                            <div class="mt-2 text-xs text-medium-gray">
                                Total peminjaman: <?php echo $asset['borrow_count']; ?> kali
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                </div>

                <!-- Available Assets -->
                <div id="assets-available" class="assets-section hidden">
                    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                        <?php foreach ($available_assets as $asset): ?>
                        <div class="asset-card bg-soft-gray rounded-lg p-4 hover:bg-gray-100 transition duration-200"
                             data-category="<?php echo $asset['asset_category']; ?>"
                             data-name="<?php echo strtolower($asset['asset_name'] . ' ' . $asset['asset_number']); ?>">
                            <div class="flex justify-between items-start mb-3">
                                <div class="flex-1 cursor-pointer" onclick="showAssetDetail(<?php echo $asset['id']; ?>)">
                                    <h4 class="font-semibold text-gray-800"><?php echo $asset['asset_name']; ?></h4>
                                    <p class="text-sm text-medium-gray"><?php echo $asset['asset_number']; ?></p>
                                    <p class="text-xs text-medium-gray"><?php echo $asset['asset_category']; ?></p>
                                </div>
                                <div class="flex flex-col items-end space-y-2">
                                    <span class="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-green-100 text-green-800">
                                        Tersedia
                                    </span>
                                    <div class="flex space-x-1">
                                        <a href="update.php?id=<?php echo $asset['id']; ?>" class="bg-blue-500 hover:bg-blue-600 text-white p-1 rounded text-xs transition duration-200">
                                            <svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"></path>
                                            </svg>
                                        </a>
                                        <button onclick="deleteAsset(<?php echo $asset['id']; ?>, '<?php echo $asset['asset_name']; ?>')" 
                                                class="bg-red-500 hover:bg-red-600 text-white p-1 rounded text-xs transition duration-200">
                                            <svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path>
                                            </svg>
                                        </button>
                                    </div>
                                </div>
                            </div>
                            <div class="mt-2 text-xs text-medium-gray">
                                Total peminjaman: <?php echo $asset['borrow_count']; ?> kali
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                </div>

                <!-- Similar sections for borrowed and maintenance assets -->
                <!-- For brevity, I'll show the pattern - you can duplicate similar structure -->
                <div id="assets-borrowed" class="assets-section hidden">
                    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                        <?php foreach ($borrowed_assets as $asset): ?>
                        <div class="asset-card bg-soft-gray rounded-lg p-4 hover:bg-gray-100 transition duration-200">
                            <!-- Similar structure with borrowed status -->
                            <div class="flex justify-between items-start mb-3">
                                <div class="flex-1 cursor-pointer" onclick="showAssetDetail(<?php echo $asset['id']; ?>)">
                                    <h4 class="font-semibold text-gray-800"><?php echo $asset['asset_name']; ?></h4>
                                    <p class="text-sm text-medium-gray"><?php echo $asset['asset_number']; ?></p>
                                </div>
                                <span class="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-yellow-100 text-yellow-800">
                                    Dipinjam
                                </span>
                            </div>
                            <div class="mt-2 p-2 bg-yellow-50 rounded border-l-2 border-yellow-400">
                                <p class="text-xs text-yellow-700">Dipinjam: <?php echo $asset['borrower_name']; ?></p>
                                <p class="text-xs text-yellow-600">Sejak: <?php echo date('d/m/Y', strtotime($asset['borrow_date'])); ?></p>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                </div>

                <div id="assets-maintenance" class="assets-section hidden">
                    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                        <?php foreach ($maintenance_assets as $asset): ?>
                        <div class="asset-card bg-soft-gray rounded-lg p-4 hover:bg-gray-100 transition duration-200">
                            <div class="flex justify-between items-start mb-3">
                                <div class="flex-1 cursor-pointer" onclick="showAssetDetail(<?php echo $asset['id']; ?>)">
                                    <h4 class="font-semibold text-gray-800"><?php echo $asset['asset_name']; ?></h4>
                                    <p class="text-sm text-medium-gray"><?php echo $asset['asset_number']; ?></p>
                                </div>
                                <span class="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-red-100 text-red-800">
                                    Maintenance
                                </span>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Delete Confirmation Modal -->
    <div id="deleteModal" class="hidden fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full z-50">
        <div class="relative top-20 mx-auto p-5 border w-96 shadow-lg rounded-md bg-white">
            <div class="mt-3 text-center">
                <h3 class="text-lg font-medium text-gray-900">Konfirmasi Hapus</h3>
                <div class="mt-2 px-7 py-3">
                    <p class="text-sm text-gray-500" id="deleteMessage">
                        Apakah Anda yakin ingin menghapus asset ini?
                    </p>
                </div>
                <div class="flex justify-center space-x-4">
                    <button id="confirmDelete" class="bg-red-500 hover:bg-red-600 text-white px-4 py-2 rounded-lg transition duration-200">
                        Hapus
                    </button>
                    <button onclick="closeDeleteModal()" class="bg-gray-500 hover:bg-gray-600 text-white px-4 py-2 rounded-lg transition duration-200">
                        Batal
                    </button>
                </div>
            </div>
        </div>
    </div>

    <style>
        .tab-button {
            background-color: #F5F5F5;
            color: #9CA3AF;
        }
        .tab-button.active {
            background-color: #32CD32;
            color: white;
        }
        .tab-button:hover:not(.active) {
            background-color: #90EE90;
            color: white;
        }
    </style>

    <script>
        let deleteAssetId = null;

        function showAssets(type) {
            // Hide all asset sections
            document.querySelectorAll('.assets-section').forEach(section => {
                section.classList.add('hidden');
            });
            
            // Remove active class from all tabs
            document.querySelectorAll('.tab-button').forEach(tab => {
                tab.classList.remove('active');
            });
            
            // Show selected section and activate tab
            document.getElementById('assets-' + type).classList.remove('hidden');
            document.getElementById('tab-' + type).classList.add('active');
        }
        
        function showAssetDetail(assetId) {
            alert('Detail asset ID: ' + assetId + ' (akan diimplementasi dengan modal yang menampilkan detail lengkap asset, riwayat peminjaman, dll)');
        }
        
        function deleteAsset(assetId, assetName) {
            deleteAssetId = assetId;
            document.getElementById('deleteMessage').textContent = `Apakah Anda yakin ingin menghapus asset "${assetName}"?`;
            document.getElementById('deleteModal').classList.remove('hidden');
        }
        
        function closeDeleteModal() {
            document.getElementById('deleteModal').classList.add('hidden');
            deleteAssetId = null;
        }
        
        document.getElementById('confirmDelete').addEventListener('click', function() {
            if (deleteAssetId) {
                // Redirect to delete.php
                window.location.href = `delete.php?id=${deleteAssetId}&type=asset`;
            }
        });
        
        function searchAssets() {
            const searchTerm = document.getElementById('searchInput').value.toLowerCase();
            const assetCards = document.querySelectorAll('.asset-card');
            
            assetCards.forEach(card => {
                const assetName = card.getAttribute('data-name');
                if (assetName.includes(searchTerm)) {
                    card.style.display = 'block';
                } else {
                    card.style.display = 'none';
                }
            });
        }
        
        function filterByCategory() {
            const selectedCategory = document.getElementById('categoryFilter').value;
            const assetCards = document.querySelectorAll('.asset-card');
            
            assetCards.forEach(card => {
                const assetCategory = card.getAttribute('data-category');
                if (selectedCategory === '' || assetCategory === selectedCategory) {
                    card.style.display = 'block';
                } else {
                    card.style.display = 'none';
                }
            });
        }
        
        // Close modal when clicking outside
        document.getElementById('deleteModal').addEventListener('click', function(e) {
            if (e.target === this) {
                closeDeleteModal();
            }
        });
    </script>
</body>
</html>