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

// Get filter parameters
$status_filter = $_GET['status'] ?? 'all';
$kondisi_filter = $_GET['kondisi'] ?? 'all';

// Build WHERE clause
$where_conditions = [];
$params = [];

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

if ($kondisi_filter !== 'all') {
    $where_conditions[] = "a.kondisi = ?";
    $params[] = $kondisi_filter;
}

$where_clause = !empty($where_conditions) ? 'WHERE ' . implode(' AND ', $where_conditions) : '';

// Get assets with borrower info
$stmt = $pdo->prepare("
    SELECT a.*, 
           bh.borrower_employee_id, 
           b.full_name as borrower_name,
           b.organization as borrower_organization,
           bh.borrow_date,
           bh.workcenter,
           DATEDIFF(CURDATE(), bh.borrow_date) as days_borrowed
    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
    {$where_clause}
    ORDER BY a.asset_number ASC
");
$stmt->execute($params);
$assets = $stmt->fetchAll();

// Get statistics
$stats = [
    'total' => count($assets),
    'available' => count(array_filter($assets, fn($a) => $a['status_borrower'] == 'available')),
    'borrowed' => count(array_filter($assets, fn($a) => $a['status_borrower'] == 'borrowed')),
    'maintenance' => count(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 - 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'
                    }
                }
            }
        }
    </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-gray-500">Monitor dan kelola asset</p>
                    </div>
                </div>
                <div class="flex items-center space-x-4">
                    <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">
                        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-2 md:grid-cols-4 gap-6 mb-8">
            <div class="bg-white rounded-xl shadow-lg p-6 text-center border-l-4 border-green-400">
                <div class="text-2xl font-bold text-green-600"><?php echo $stats['available']; ?></div>
                <div class="text-sm text-gray-600">Tersedia</div>
            </div>
            
            <div class="bg-white rounded-xl shadow-lg p-6 text-center border-l-4 border-blue-400">
                <div class="text-2xl font-bold text-blue-600"><?php echo $stats['borrowed']; ?></div>
                <div class="text-sm text-gray-600">Dipinjam</div>
            </div>
            
            <div class="bg-white rounded-xl shadow-lg p-6 text-center border-l-4 border-yellow-400">
                <div class="text-2xl font-bold text-yellow-600"><?php echo $stats['maintenance']; ?></div>
                <div class="text-sm text-gray-600">Maintenance</div>
            </div>
            
            <div class="bg-white rounded-xl shadow-lg p-6 text-center border-l-4 border-gray-400">
                <div class="text-2xl font-bold text-gray-600"><?php echo $stats['total']; ?></div>
                <div class="text-sm text-gray-600">Total</div>
            </div>
        </div>

        <!-- Filters -->
        <div class="bg-white rounded-xl shadow-lg p-6 mb-8">
            <h3 class="text-lg font-semibold text-gray-800 mb-4">Filter Asset</h3>
            
            <form method="GET" class="grid grid-cols-1 md:grid-cols-3 gap-4">
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">Status</label>
                    <select name="status" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-dark-leaf">
                        <option value="all" <?php echo $status_filter == 'all' ? 'selected' : ''; ?>>Semua Status</option>
                        <option value="available" <?php echo $status_filter == 'available' ? 'selected' : ''; ?>>Tersedia</option>
                        <option value="borrowed" <?php echo $status_filter == 'borrowed' ? 'selected' : ''; ?>>Dipinjam</option>
                        <option value="maintenance" <?php echo $status_filter == 'maintenance' ? 'selected' : ''; ?>>Maintenance</option>
                    </select>
                </div>
                
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">Kondisi</label>
                    <select name="kondisi" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-dark-leaf">
                        <option value="all" <?php echo $kondisi_filter == 'all' ? 'selected' : ''; ?>>Semua Kondisi</option>
                        <option value="baik" <?php echo $kondisi_filter == 'baik' ? 'selected' : ''; ?>>Baik</option>
                        <option value="rusak" <?php echo $kondisi_filter == 'rusak' ? 'selected' : ''; ?>>Rusak</option>
                        <option value="hilang" <?php echo $kondisi_filter == 'hilang' ? 'selected' : ''; ?>>Hilang</option>
                    </select>
                </div>
                
                <div class="flex items-end space-x-2">
                    <button type="submit" class="bg-dark-leaf hover:bg-green-600 text-white px-6 py-2 rounded-lg">
                        Filter
                    </button>
                    <a href="assets.php" class="bg-gray-500 hover:bg-gray-600 text-white px-6 py-2 rounded-lg">
                        Reset
                    </a>
                </div>
            </form>
        </div>

        <!-- Assets Grid -->
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            <?php foreach ($assets as $asset): ?>
            <div class="bg-white rounded-xl shadow-lg p-6 hover:shadow-xl transition duration-300">
                <div class="flex justify-between items-start mb-4">
                    <div class="flex-1">
                        <h3 class="font-semibold text-gray-800 mb-1"><?php echo $asset['asset_name']; ?></h3>
                        <p class="text-sm text-gray-600"><?php echo $asset['asset_number']; ?></p>
                        <p class="text-xs text-gray-500"><?php echo $asset['asset_category']; ?></p>
                    </div>
                    <div class="text-right">
                        <span class="inline-block 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-blue-100 text-blue-800' : 'bg-yellow-100 text-yellow-800'); 
                        ?>">
                            <?php 
                            echo $asset['status_borrower'] == 'available' ? 'Tersedia' : 
                                ($asset['status_borrower'] == 'borrowed' ? 'Dipinjam' : 'Maintenance'); 
                            ?>
                        </span>
                    </div>
                </div>
                
                <div class="flex justify-between items-center mb-3">
                    <span class="text-sm text-gray-600">Kondisi:</span>
                    <span class="px-2 py-1 rounded-full text-xs font-medium <?php 
                        echo $asset['kondisi'] == 'baik' ? 'bg-green-100 text-green-800' : 
                            ($asset['kondisi'] == 'rusak' ? 'bg-yellow-100 text-yellow-800' : 'bg-red-100 text-red-800'); 
                    ?>">
                        <?php echo ucfirst($asset['kondisi']); ?>
                    </span>
                </div>

                <?php if ($asset['status_borrower'] == 'borrowed' && $asset['borrower_name']): ?>
                <div class="mt-4 pt-4 border-t border-gray-200">
                    <div class="text-xs text-blue-600 space-y-1">
                        <p><span class="font-medium">Dipinjam:</span> <?php echo $asset['borrower_name']; ?></p>
                        <p><span class="font-medium">Sejak:</span> <?php echo date('d/m/Y', strtotime($asset['borrow_date'])); ?></p>
                        <?php if ($asset['days_borrowed'] > 7): ?>
                        <p class="text-red-600 font-medium">Terlambat <?php echo $asset['days_borrowed']; ?> hari</p>
                        <?php endif; ?>
                        <?php if ($asset['workcenter']): ?>
                        <p><span class="font-medium">workcenter:</span> <?php echo $asset['workcenter']; ?></p>
                        <?php endif; ?>
                    </div>
                </div>
                <?php endif; ?>

                <?php if ($asset['description']): ?>
                <div class="mt-3 text-xs text-gray-500">
                    <p><?php echo $asset['description']; ?></p>
                </div>
                <?php endif; ?>
            </div>
            <?php endforeach; ?>
        </div>

        <?php if (empty($assets)): ?>
        <div class="text-center py-12">
            <div class="text-gray-400 mb-4">
                <svg class="w-16 h-16 mx-auto" 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>
            <h3 class="text-lg font-semibold text-gray-700 mb-2">Tidak Ada Asset</h3>
            <p class="text-gray-500">Tidak ada asset yang sesuai dengan filter yang dipilih</p>
        </div>
        <?php endif; ?>
    </div>
</body>
</html>