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

// Get comprehensive stats
// Assets stats
$stmt = $pdo->prepare("SELECT COUNT(*) as total FROM assets");
$stmt->execute();
$total_assets = $stmt->fetch()['total'];

$stmt = $pdo->prepare("SELECT COUNT(*) as available FROM assets WHERE status_borrower = 'available'");
$stmt->execute();
$available_assets = $stmt->fetch()['available'];

$stmt = $pdo->prepare("SELECT COUNT(*) as borrowed FROM assets WHERE status_borrower = 'borrowed'");
$stmt->execute();
$borrowed_assets = $stmt->fetch()['borrowed'];

// Users stats
$stmt = $pdo->prepare("SELECT COUNT(*) as total FROM admins WHERE is_active = 1");
$stmt->execute();
$total_admins = $stmt->fetch()['total'];

$stmt = $pdo->prepare("SELECT COUNT(*) as total FROM borrowers WHERE is_active = 1");
$stmt->execute();
$total_borrowers = $stmt->fetch()['total'];

// Pending requests
$stmt = $pdo->prepare("SELECT COUNT(*) as pending FROM borrow_history WHERE status = 'pending_approval'");
$stmt->execute();
$pending_requests = $stmt->fetch()['pending'];

// Recent activities (last 10)
$stmt = $pdo->prepare("
    SELECT bh.*, a.asset_name, a.asset_number, b.full_name as borrower_name, 'borrow' as activity_type
    FROM borrow_history bh 
    JOIN assets a ON bh.asset_id = a.id 
    JOIN borrowers b ON bh.borrower_employee_id = b.employee_id
    ORDER BY bh.created_at DESC 
    LIMIT 10
");
$stmt->execute();
$recent_activities = $stmt->fetchAll();

// Assets by category
$stmt = $pdo->prepare("SELECT asset_category, COUNT(*) as count FROM assets GROUP BY asset_category");
$stmt->execute();
$assets_by_category = $stmt->fetchAll();
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dashboard Superadmin - 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">
                    <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">Tools Room Superadmin</h1>
                        <p class="text-sm text-medium-gray">Dashboard Superadmin - Full Access</p>
                    </div>
                </div>
                <div class="flex items-center space-x-4">
                    <span class="text-sm text-gray-600">Halo, <?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">
        <!-- Welcome Card -->
        <div class="bg-gradient-to-r from-leaf-green to-dark-leaf rounded-xl shadow-lg p-6 mb-8 text-white">
            <h2 class="text-2xl font-bold mb-2">Selamat Datang, <?php echo $_SESSION['user_name']; ?>!</h2>
            <p class="opacity-90">Kelola seluruh sistem peminjaman tools room dengan akses penuh</p>
        </div>

        <!-- Main Stats Grid - Improved Layout -->
        <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 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 h-32 flex flex-col justify-between" onclick="toggleDetails('assets')">
                <div class="flex items-start justify-between">
                    <div class="flex-1">
                        <p class="text-medium-gray text-sm font-medium mb-2">Total Asset</p>
                        <p class="text-3xl font-bold text-blue-600"><?php echo $total_assets; ?></p>
                    </div>
                    <div class="bg-blue-100 p-2 rounded-full">
                        <svg class="w-5 h-5 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>
                <p class="text-xs text-medium-gray">Tersedia: <?php echo $available_assets; ?> | Dipinjam: <?php echo $borrowed_assets; ?></p>
            </div>

            <!-- Total Users -->
            <div class="bg-white rounded-xl shadow-lg p-6 cursor-pointer hover:shadow-xl transition duration-300 border-l-4 border-green-400 h-32 flex flex-col justify-between" onclick="toggleDetails('users')">
                <div class="flex items-start justify-between">
                    <div class="flex-1">
                        <p class="text-medium-gray text-sm font-medium mb-2">Total User</p>
                        <p class="text-3xl font-bold text-green-600"><?php echo ($total_admins + $total_borrowers); ?></p>
                    </div>
                    <div class="bg-green-100 p-2 rounded-full">
                        <svg class="w-5 h-5 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4.354a4 4 0 110 5.292M15 21H3v-1a6 6 0 0112 0v1zm0 0h6v-1a6 6 0 00-9-5.197m13.5-9a2.5 2.5 0 11-5 0 2.5 2.5 0 015 0z"></path>
                        </svg>
                    </div>
                </div>
                <p class="text-xs text-medium-gray">Admin: <?php echo $total_admins; ?> | Borrower: <?php echo $total_borrowers; ?></p>
            </div>

            <!-- Pending Requests -->
            <a href="persetujuan.php" class="bg-white rounded-xl shadow-lg p-6 cursor-pointer hover:shadow-xl transition duration-300 border-l-4 border-red-400 h-32 flex flex-col justify-between block">
                <div class="flex items-start justify-between">
                    <div class="flex-1">
                        <p class="text-medium-gray text-sm font-medium mb-2">Pending Request</p>
                        <p class="text-3xl font-bold text-red-600"><?php echo $pending_requests; ?></p>
                    </div>
                    <div class="bg-red-100 p-2 rounded-full">
                        <svg class="w-5 h-5 text-red-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L3.732 16.5c-.77.833.192 2.5 1.732 2.5z"></path>
                        </svg>
                    </div>
                </div>
                <p class="text-xs text-medium-gray">Memerlukan perhatian admin</p>
            </a>
        </div>

        <!-- Quick Actions Grid - Improved Layout -->
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 mb-8">
            <!-- Manage Assets -->
            <a href="assets.php" class="bg-white rounded-xl shadow-lg p-6 hover:shadow-xl transition duration-300 block h-24">
                <div class="flex items-center space-x-4 h-full">
                    <div class="bg-blue-500 p-3 rounded-full flex-shrink-0">
                        <svg class="w-6 h-6 text-white" 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 class="flex-1">
                        <h3 class="text-lg font-semibold text-gray-800">Kelola Asset</h3>
                        <p class="text-medium-gray text-sm">Add, edit, delete assets</p>
                    </div>
                </div>
            </a>

            <!-- Manage Users -->
            <a href="users.php" class="bg-white rounded-xl shadow-lg p-6 hover:shadow-xl transition duration-300 block h-24">
                <div class="flex items-center space-x-4 h-full">
                    <div class="bg-green-500 p-3 rounded-full flex-shrink-0">
                        <svg class="w-6 h-6 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4.354a4 4 0 110 5.292M15 21H3v-1a6 6 0 0112 0v1zm0 0h6v-1a6 6 0 00-9-5.197m13.5-9a2.5 2.5 0 11-5 0 2.5 2.5 0 015 0z"></path>
                        </svg>
                    </div>
                    <div class="flex-1">
                        <h3 class="text-lg font-semibold text-gray-800">Kelola User</h3>
                        <p class="text-medium-gray text-sm">Manage admin & borrower</p>
                    </div>
                </div>
            </a>

            <!-- Quick Add Asset -->
            <a href="add.php?type=asset" class="bg-white rounded-xl shadow-lg p-6 hover:shadow-xl transition duration-300 block h-24">
                <div class="flex items-center space-x-4 h-full">
                    <div class="bg-dark-leaf p-3 rounded-full flex-shrink-0">
                        <svg class="w-6 h-6 text-white" 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>
                    </div>
                    <div class="flex-1">
                        <h3 class="text-lg font-semibold text-gray-800">Tambah Asset</h3>
                        <p class="text-medium-gray text-sm">Add new asset quickly</p>
                    </div>
                </div>
            </a>
        </div>

        <!-- Details Section (Hidden by default) -->
        <div id="details-section" class="hidden mb-8">
            <div class="bg-white rounded-xl shadow-lg p-6">
                <div class="flex justify-between items-center mb-4">
                    <h3 id="details-title" class="text-lg font-semibold text-gray-800"></h3>
                    <button onclick="document.getElementById('details-section').classList.add('hidden')" 
                            class="text-gray-400 hover:text-gray-600">
                        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
                        </svg>
                    </button>
                </div>
                <div id="details-content"></div>
            </div>
        </div>
    </div>

    <script>
        function toggleDetails(type) {
            const detailsSection = document.getElementById('details-section');
            const detailsTitle = document.getElementById('details-title');
            const detailsContent = document.getElementById('details-content');
            
            // Show details section
            detailsSection.classList.remove('hidden');
            
            // Set title and load content based on type
            switch(type) {
                case 'assets':
                    detailsTitle.textContent = 'Detail Asset System';
                    loadDetailsContent('assets');
                    break;
                case 'users':
                    detailsTitle.textContent = 'Detail User System';
                    loadDetailsContent('users');
                    break;
                case 'pending':
                    // Redirect to persetujuan.php instead of showing details
                    window.location.href = 'persetujuan.php';
                    break;
                case 'system':
                    detailsTitle.textContent = 'System Health Details';
                    loadDetailsContent('system');
                    break;
            }
            
            // Scroll to details
            detailsSection.scrollIntoView({ behavior: 'smooth' });
        }
        
        function loadDetailsContent(type) {
            const detailsContent = document.getElementById('details-content');
            detailsContent.innerHTML = '<div class="text-center py-4"><div class="animate-spin rounded-full h-8 w-8 border-b-2 border-dark-leaf mx-auto"></div></div>';
            
            setTimeout(() => {
                let content = '';
                switch(type) {
                    case 'assets':
                        content = `
                            <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                                <div class="text-center p-4 bg-blue-50 rounded-lg">
                                    <div class="text-2xl font-bold text-blue-600"><?php echo $total_assets; ?></div>
                                    <div class="text-sm text-gray-600">Total Asset</div>
                                </div>
                                <div class="text-center p-4 bg-green-50 rounded-lg">
                                    <div class="text-2xl font-bold text-green-600"><?php echo $available_assets; ?></div>
                                    <div class="text-sm text-gray-600">Tersedia</div>
                                </div>
                                <div class="text-center p-4 bg-yellow-50 rounded-lg">
                                    <div class="text-2xl font-bold text-yellow-600"><?php echo $borrowed_assets; ?></div>
                                    <div class="text-sm text-gray-600">Dipinjam</div>
                                </div>
                            </div>
                            <div class="mt-4 text-center">
                                <a href="assets.php" class="bg-blue-500 text-white px-4 py-2 rounded-lg hover:bg-blue-600 transition duration-200">
                                    Kelola Asset
                                </a>
                            </div>
                        `;
                        break;
                    case 'users':
                        content = `
                            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                                <div class="text-center p-4 bg-green-50 rounded-lg">
                                    <div class="text-2xl font-bold text-green-600"><?php echo $total_admins; ?></div>
                                    <div class="text-sm text-gray-600">Admin Aktif</div>
                                </div>
                                <div class="text-center p-4 bg-blue-50 rounded-lg">
                                    <div class="text-2xl font-bold text-blue-600"><?php echo $total_borrowers; ?></div>
                                    <div class="text-sm text-gray-600">Borrower Aktif</div>
                                </div>
                            </div>
                            <div class="mt-4 text-center">
                                <a href="users.php" class="bg-green-500 text-white px-4 py-2 rounded-lg hover:bg-green-600 transition duration-200">
                                    Kelola User
                                </a>
                            </div>
                        `;
                        break;
                    default:
                        content = `
                            <div class="text-center py-8">
                                <p class="text-medium-gray">Detail informasi ${type}</p>
                            </div>
                        `;
                }
                detailsContent.innerHTML = content;
            }, 1000);
        }
    </script>
</body>
</html>