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

// Get all users - Fixed: removed 'nik' column that doesn't exist
$stmt = $pdo->prepare("SELECT 'admin' as user_type, id, employee_id, full_name, branch_name, organization, jabatan, is_active, created_at FROM admins
                       UNION ALL
                       SELECT 'borrower' as user_type, id, employee_id, full_name, branch_name, organization, jabatan, is_active, created_at FROM borrowers
                       ORDER BY user_type, full_name");
$stmt->execute();
$all_users = $stmt->fetchAll();

// Separate users by type
$admins = array_filter($all_users, fn($u) => $u['user_type'] == 'admin');
$borrowers = array_filter($all_users, fn($u) => $u['user_type'] == 'borrower');
$active_users = array_filter($all_users, fn($u) => $u['is_active'] == 1);
$inactive_users = array_filter($all_users, fn($u) => $u['is_active'] == 0);
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Kelola User - 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 User</h1>
                        <p class="text-sm text-medium-gray">Management admin dan borrower</p>
                    </div>
                </div>
                <div class="flex items-center space-x-4">
                    <div class="flex space-x-2">
                        <a href="add.php?type=admin" class="bg-blue-500 hover:bg-blue-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>Admin</span>
                        </a>
                        <a href="add.php?type=borrower" 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>Borrower</span>
                        </a>
                    </div>
                    <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 Users -->
            <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="showUsers('all')">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-medium-gray text-sm font-medium">Total User</p>
                        <p class="text-3xl font-bold text-blue-600"><?php echo count($all_users); ?></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="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>
            </div>

            <!-- Admins -->
            <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="showUsers('admin')">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-medium-gray text-sm font-medium">Admin</p>
                        <p class="text-3xl font-bold text-green-600"><?php echo count($admins); ?></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="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z"></path>
                        </svg>
                    </div>
                </div>
            </div>

            <!-- Borrowers -->
            <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="showUsers('borrower')">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-medium-gray text-sm font-medium">Borrower</p>
                        <p class="text-3xl font-bold text-yellow-600"><?php echo count($borrowers); ?></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="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"></path>
                        </svg>
                    </div>
                </div>
            </div>

            <!-- Active Users -->
            <div class="bg-white rounded-xl shadow-lg p-6 cursor-pointer hover:shadow-xl transition duration-300 border-l-4 border-purple-400" onclick="showUsers('active')">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-medium-gray text-sm font-medium">User Aktif</p>
                        <p class="text-3xl font-bold text-purple-600"><?php echo count($active_users); ?></p>
                    </div>
                    <div class="bg-purple-100 p-3 rounded-full">
                        <svg class="w-6 h-6 text-purple-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>
                <p class="text-xs text-medium-gray mt-2">Non-aktif: <?php echo count($inactive_users); ?></p>
            </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="showUsers('all')" id="tab-all" class="tab-button active px-4 py-2 rounded-lg text-sm font-medium transition duration-200">
                        Semua User
                    </button>
                    <button onclick="showUsers('admin')" id="tab-admin" class="tab-button px-4 py-2 rounded-lg text-sm font-medium transition duration-200">
                        Admin
                    </button>
                    <button onclick="showUsers('borrower')" id="tab-borrower" class="tab-button px-4 py-2 rounded-lg text-sm font-medium transition duration-200">
                        Borrower
                    </button>
                    <button onclick="showUsers('active')" id="tab-active" class="tab-button px-4 py-2 rounded-lg text-sm font-medium transition duration-200">
                        Aktif
                    </button>
                    <button onclick="showUsers('inactive')" id="tab-inactive" class="tab-button px-4 py-2 rounded-lg text-sm font-medium transition duration-200">
                        Non-Aktif
                    </button>
                </div>
                <div class="flex space-x-2">
                    <input type="text" id="searchInput" placeholder="Cari user..." 
                           class="px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-dark-leaf focus:border-dark-leaf"
                           onkeyup="searchUsers()">
                    <select id="branchFilter" onchange="filterByBranch()" 
                            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 Cabang</option>
                        <?php 
                        $branches = array_unique(array_column($all_users, 'branch_name'));
                        foreach ($branches as $branch): 
                        ?>
                        <option value="<?php echo $branch; ?>"><?php echo $branch; ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>

            <!-- Users List -->
            <div id="users-container">
                <!-- All Users (Default) -->
                <div id="users-all" class="users-section">
                    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                        <?php foreach ($all_users as $user): ?>
                        <div class="user-card bg-soft-gray rounded-lg p-4 hover:bg-gray-100 transition duration-200" 
                             data-type="<?php echo $user['user_type']; ?>"
                             data-branch="<?php echo $user['branch_name']; ?>"
                             data-name="<?php echo strtolower($user['full_name'] . ' ' . $user['employee_id']); ?>"
                             data-active="<?php echo $user['is_active']; ?>">
                            <div class="flex justify-between items-start mb-3">
                                <div class="flex-1 cursor-pointer" onclick="showUserDetail('<?php echo $user['user_type']; ?>', <?php echo $user['id']; ?>)">
                                    <h4 class="font-semibold text-gray-800"><?php echo $user['full_name']; ?></h4>
                                    <p class="text-sm text-medium-gray"><?php echo $user['employee_id']; ?></p>
                                    <p class="text-xs text-medium-gray"><?php echo $user['jabatan']; ?></p>
                                </div>
                                <div class="flex flex-col items-end space-y-2">
                                    <div class="flex space-x-1">
                                        <span class="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium 
                                            <?php echo $user['user_type'] == 'admin' ? 'bg-green-100 text-green-800' : 'bg-blue-100 text-blue-800'; ?>">
                                            <?php echo ucfirst($user['user_type']); ?>
                                        </span>
                                        <span class="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium 
                                            <?php echo $user['is_active'] ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'; ?>">
                                            <?php echo $user['is_active'] ? 'Aktif' : 'Non-Aktif'; ?>
                                        </span>
                                    </div>
                                    <div class="flex space-x-1">
                                        <a href="update.php?id=<?php echo $user['id']; ?>&type=<?php echo $user['user_type']; ?>" 
                                           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="deleteUser(<?php echo $user['id']; ?>, '<?php echo $user['user_type']; ?>', '<?php echo $user['full_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="text-xs text-medium-gray">
                                <p><?php echo $user['branch_name']; ?> • <?php echo $user['organization']; ?></p>
                                <p>Bergabung: <?php echo date('d/m/Y', strtotime($user['created_at'])); ?></p>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                </div>

                <!-- Other sections will be shown/hidden by JavaScript -->
                <?php foreach (['admin', 'borrower', 'active', 'inactive'] as $section): ?>
                <div id="users-<?php echo $section; ?>" class="users-section hidden">
                    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                        <?php 
                        $filtered_users = [];
                        if ($section == 'admin') $filtered_users = $admins;
                        elseif ($section == 'borrower') $filtered_users = $borrowers;
                        elseif ($section == 'active') $filtered_users = $active_users;
                        elseif ($section == 'inactive') $filtered_users = $inactive_users;
                        
                        foreach ($filtered_users as $user): 
                        ?>
                        <div class="user-card bg-soft-gray rounded-lg p-4 hover:bg-gray-100 transition duration-200">
                            <!-- Similar structure as above -->
                            <div class="flex justify-between items-start mb-3">
                                <div class="flex-1">
                                    <h4 class="font-semibold text-gray-800"><?php echo $user['full_name']; ?></h4>
                                    <p class="text-sm text-medium-gray"><?php echo $user['employee_id']; ?></p>
                                    <p class="text-xs text-medium-gray"><?php echo $user['jabatan']; ?></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 $user['user_type'] == 'admin' ? 'bg-green-100 text-green-800' : 'bg-blue-100 text-blue-800'; ?>">
                                        <?php echo ucfirst($user['user_type']); ?>
                                    </span>
                                    <div class="flex space-x-1">
                                        <a href="update.php?id=<?php echo $user['id']; ?>&type=<?php echo $user['user_type']; ?>" 
                                           class="bg-blue-500 hover:bg-blue-600 text-white p-1 rounded text-xs">
                                            <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="deleteUser(<?php echo $user['id']; ?>, '<?php echo $user['user_type']; ?>', '<?php echo $user['full_name']; ?>')" 
                                                class="bg-red-500 hover:bg-red-600 text-white p-1 rounded text-xs">
                                            <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>
                        <?php endforeach; ?>
                    </div>
                </div>
                <?php endforeach; ?>
            </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 User</h3>
                <div class="mt-2 px-7 py-3">
                    <p class="text-sm text-gray-500" id="deleteMessage">
                        Apakah Anda yakin ingin menghapus user 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 deleteUserId = null;
        let deleteUserType = null;

        function showUsers(type) {
            // Hide all user sections
            document.querySelectorAll('.users-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('users-' + type).classList.remove('hidden');
            document.getElementById('tab-' + type).classList.add('active');
        }
        
        function showUserDetail(userType, userId) {
            alert(`Detail ${userType} ID: ${userId} (akan diimplementasi dengan modal yang menampilkan detail lengkap user)`);
        }
        
        function deleteUser(userId, userType, userName) {
            deleteUserId = userId;
            deleteUserType = userType;
            document.getElementById('deleteMessage').textContent = `Apakah Anda yakin ingin menghapus ${userType} "${userName}"?`;
            document.getElementById('deleteModal').classList.remove('hidden');
        }
        
        function closeDeleteModal() {
            document.getElementById('deleteModal').classList.add('hidden');
            deleteUserId = null;
            deleteUserType = null;
        }
        
        document.getElementById('confirmDelete').addEventListener('click', function() {
            if (deleteUserId && deleteUserType) {
                window.location.href = `delete.php?id=${deleteUserId}&type=${deleteUserType}`;
            }
        });
        
        function searchUsers() {
            const searchTerm = document.getElementById('searchInput').value.toLowerCase();
            const userCards = document.querySelectorAll('.user-card');
            
            userCards.forEach(card => {
                const userName = card.getAttribute('data-name');
                if (userName && userName.includes(searchTerm)) {
                    card.style.display = 'block';
                } else {
                    card.style.display = 'none';
                }
            });
        }
        
        function filterByBranch() {
            const selectedBranch = document.getElementById('branchFilter').value;
            const userCards = document.querySelectorAll('.user-card');
            
            userCards.forEach(card => {
                const userBranch = card.getAttribute('data-branch');
                if (selectedBranch === '' || userBranch === selectedBranch) {
                    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>