<?php

declare(strict_types=1);

require_once __DIR__ . '/../../src/db.php';
require_once __DIR__ . '/../../src/SuperAdmin/SuperAdminAuth.php';
require_once __DIR__ . '/navigation.php';

SuperAdminAuth::requirePermission('admins_view');

$admin = SuperAdminAuth::getCurrentAdmin();
$canManage = SuperAdminAuth::hasPermission('admins_manage');

$message = '';
$error = '';
$pdo = getPDO();

// Handle actions
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $canManage) {
    $action = $_POST['action'] ?? '';

    if ($action === 'create') {
        $name = trim($_POST['name'] ?? '');
        $email = trim($_POST['email'] ?? '');
        $password = $_POST['password'] ?? '';
        $role = $_POST['role'] ?? 'support';
        $permissions = $_POST['permissions'] ?? [];

        if (empty($name) || empty($email) || empty($password)) {
            $error = 'All fields are required.';
        } elseif (strlen($password) < 8) {
            $error = 'Password must be at least 8 characters.';
        } else {
            $adminId = SuperAdminAuth::createAdmin($name, $email, $password, $role, $permissions, $admin['id']);
            if ($adminId) {
                $message = 'Admin created successfully.';
            } else {
                $error = 'Failed to create admin. Email may already exist.';
            }
        }
    } elseif ($action === 'update_permissions') {
        $targetAdminId = (int)($_POST['admin_id'] ?? 0);
        $permissions = $_POST['permissions'] ?? [];
        
        // Can't modify owner permissions
        $stmt = $pdo->prepare('SELECT role FROM super_admins WHERE id = ?');
        $stmt->execute([$targetAdminId]);
        $targetAdmin = $stmt->fetch();
        
        if ($targetAdmin && $targetAdmin['role'] !== 'owner') {
            if (SuperAdminAuth::updatePermissions($targetAdminId, $permissions)) {
                SuperAdminAuth::logActivity($admin['id'], 'update_admin_permissions', 'super_admin', $targetAdminId);
                $message = 'Permissions updated successfully.';
            } else {
                $error = 'Failed to update permissions.';
            }
        } else {
            $error = 'Cannot modify owner permissions.';
        }
    } elseif ($action === 'toggle_active') {
        $targetAdminId = (int)($_POST['admin_id'] ?? 0);
        $isActive = (int)($_POST['is_active'] ?? 0);
        
        // Can't deactivate self or owner
        if ($targetAdminId !== $admin['id']) {
            $stmt = $pdo->prepare('SELECT role FROM super_admins WHERE id = ?');
            $stmt->execute([$targetAdminId]);
            $targetAdmin = $stmt->fetch();
            
            if ($targetAdmin && $targetAdmin['role'] !== 'owner') {
                $stmt = $pdo->prepare('UPDATE super_admins SET is_active = ? WHERE id = ?');
                if ($stmt->execute([$isActive, $targetAdminId])) {
                    SuperAdminAuth::logActivity($admin['id'], $isActive ? 'activate_admin' : 'deactivate_admin', 'super_admin', $targetAdminId);
                    $message = $isActive ? 'Admin activated.' : 'Admin deactivated.';
                } else {
                    $error = 'Failed to update admin status.';
                }
            } else {
                $error = 'Cannot modify owner status.';
            }
        } else {
            $error = 'Cannot deactivate yourself.';
        }
    } elseif ($action === 'delete') {
        $targetAdminId = (int)($_POST['admin_id'] ?? 0);
        
        // Can't delete self or owner
        if ($targetAdminId !== $admin['id']) {
            $stmt = $pdo->prepare('SELECT role FROM super_admins WHERE id = ?');
            $stmt->execute([$targetAdminId]);
            $targetAdmin = $stmt->fetch();
            
            if ($targetAdmin && $targetAdmin['role'] !== 'owner') {
                $stmt = $pdo->prepare('DELETE FROM super_admins WHERE id = ?');
                if ($stmt->execute([$targetAdminId])) {
                    SuperAdminAuth::logActivity($admin['id'], 'delete_admin', 'super_admin', $targetAdminId);
                    $message = 'Admin deleted successfully.';
                } else {
                    $error = 'Failed to delete admin.';
                }
            } else {
                $error = 'Cannot delete owner.';
            }
        } else {
            $error = 'Cannot delete yourself.';
        }
    }
}

// Get all admins
$stmt = $pdo->query('SELECT * FROM super_admins ORDER BY role, name');
$admins = $stmt->fetchAll();

$roles = ['owner' => 'Owner', 'admin' => 'Admin', 'support' => 'Support', 'finance' => 'Finance'];
$permissions = SuperAdminAuth::PERMISSIONS;
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin Staff · Keelance Admin</title>
    <link rel="icon" type="image/png" href="/assets/favicon.png">
    <script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-slate-100 min-h-screen text-slate-900">
<div class="min-h-screen flex flex-col">
<?php renderAdminNavigation(); ?>

<main class="flex-1">
    <div class="max-w-6xl mx-auto px-4 py-6 space-y-6">
        <div class="flex items-center justify-between gap-3">
            <div>
                <h1 class="text-2xl font-bold text-slate-900 tracking-tight">Admin Staff</h1>
                <p class="text-slate-500 mt-1 text-sm">Manage super admin accounts, roles, and permissions.</p>
            </div>
            <?php if ($canManage): ?>
                <button onclick="showCreateModal()" class="inline-flex items-center gap-1.5 px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg text-sm font-medium transition-colors">
                    <span class="text-base leading-none">＋</span>
                    <span>Add admin</span>
                </button>
            <?php endif; ?>
        </div>

        <?php if ($message): ?>
            <div class="bg-emerald-50 border border-emerald-200 rounded-lg p-4">
                <p class="text-sm text-emerald-700"><?= htmlspecialchars($message) ?></p>
            </div>
        <?php endif; ?>

        <?php if ($error): ?>
            <div class="bg-red-50 border border-red-200 rounded-lg p-4">
                <p class="text-sm text-red-700"><?= htmlspecialchars($error) ?></p>
            </div>
        <?php endif; ?>

        <!-- Admins List -->
        <div class="bg-white border border-slate-200 shadow-sm rounded-xl overflow-hidden">
        <div class="overflow-x-auto">
            <table class="w-full">
                <thead>
                    <tr class="text-left text-sm text-slate-500 border-b border-slate-200 bg-slate-50">
                        <th class="px-4 py-3 font-medium">Admin</th>
                        <th class="px-4 py-3 font-medium">Role</th>
                        <th class="px-4 py-3 font-medium">Status</th>
                        <th class="px-4 py-3 font-medium">Last Login</th>
                        <th class="px-4 py-3 font-medium text-right">Actions</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-slate-100">
                    <?php foreach ($admins as $a): 
                        $adminPermissions = SuperAdminAuth::getAdminPermissions((int)$a['id']);
                    ?>
                        <tr class="hover:bg-slate-50">
                            <td class="px-4 py-3">
                                <div>
                                    <p class="font-medium">
                                        <?= htmlspecialchars($a['name']) ?>
                                        <?php if ($a['id'] === $admin['id']): ?>
                                            <span class="text-xs text-slate-500">(you)</span>
                                        <?php endif; ?>
                                    </p>
                                    <p class="text-slate-500 text-sm"><?= htmlspecialchars($a['email']) ?></p>
                                </div>
                            </td>
                            <td class="px-6 py-4">
                                <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium 
                                    <?php
                                    echo match($a['role']) {
                                        'owner' => 'bg-amber-500/20 text-amber-400',
                                        'admin' => 'bg-blue-500/20 text-blue-400',
                                        'support' => 'bg-emerald-500/20 text-emerald-400',
                                        'finance' => 'bg-purple-500/20 text-purple-400',
                                        default => 'bg-slate-500/20 text-slate-500',
                                    };
                                    ?>">
                                    <?= ucfirst($a['role']) ?>
                                </span>
                            </td>
                            <td class="px-6 py-4">
                                <?php if ($a['is_active']): ?>
                                    <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-emerald-500/20 text-emerald-400">
                                        Active
                                    </span>
                                <?php else: ?>
                                    <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-red-500/20 text-red-400">
                                        Inactive
                                    </span>
                                <?php endif; ?>
                            </td>
                            <td class="px-4 py-3 text-slate-500 text-sm">
                                <?= $a['last_login_at'] ? date('M j, Y H:i', strtotime($a['last_login_at'])) : 'Never' ?>
                            </td>
                            <td class="px-6 py-4">
                                <div class="flex items-center justify-end gap-2">
                                    <?php if ($canManage && $a['role'] !== 'owner' && $a['id'] !== $admin['id']): ?>
                                        <button onclick='showPermissionsModal(<?= $a["id"] ?>, "<?= htmlspecialchars($a["name"], ENT_QUOTES) ?>", <?= json_encode($adminPermissions) ?>)'
                                                class="px-3 py-1.5 text-xs rounded-full border border-blue-200 text-blue-700 bg-white hover:bg-blue-50 transition-colors">
                                            Permissions
                                        </button>
                                        
                                        <form method="POST" class="inline">
                                            <input type="hidden" name="action" value="toggle_active">
                                            <input type="hidden" name="admin_id" value="<?= $a['id'] ?>">
                                            <input type="hidden" name="is_active" value="<?= $a['is_active'] ? 0 : 1 ?>">
                                            <button type="submit" class="px-3 py-1.5 text-xs rounded-full border <?= $a['is_active'] ? 'border-amber-300 text-amber-700 bg-white hover:bg-amber-50' : 'border-emerald-300 text-emerald-700 bg-white hover:bg-emerald-50' ?> transition-colors">
                                                <?= $a['is_active'] ? 'Deactivate' : 'Activate' ?>
                                            </button>
                                        </form>
                                        
                                        <form method="POST" class="inline" onsubmit="return confirm('Delete this admin?')">
                                            <input type="hidden" name="action" value="delete">
                                            <input type="hidden" name="admin_id" value="<?= $a['id'] ?>">
                                            <button type="submit" class="px-3 py-1.5 text-xs rounded-full border border-red-300 text-red-700 bg-white hover:bg-red-50 transition-colors">
                                                Delete
                                            </button>
                                        </form>
                                    <?php endif; ?>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</main>

<!-- Create Modal -->
<div id="createModal" class="fixed inset-0 bg-black/40 hidden items-center justify-center z-50">
    <div class="bg-white border border-slate-200 shadow-xl rounded-xl p-6 w-full max-w-md mx-4">
        <h3 class="text-lg font-semibold mb-4 text-slate-900">Add Admin</h3>
        <form method="POST" class="space-y-4">
            <input type="hidden" name="action" value="create">
            
            <div>
                <label class="block text-sm text-slate-500 mb-2">Name</label>
                <input type="text" name="name" required
                       class="w-full px-4 py-2 bg-slate-50 border border-slate-300 rounded-lg text-slate-900 focus:outline-none focus:ring-2 focus:ring-blue-500">
            </div>
            
            <div>
                <label class="block text-sm text-slate-500 mb-2">Email</label>
                <input type="email" name="email" required
                       class="w-full px-4 py-2 bg-slate-50 border border-slate-300 rounded-lg text-slate-900 focus:outline-none focus:ring-2 focus:ring-blue-500">
            </div>
            
            <div>
                <label class="block text-sm text-slate-500 mb-2">Password</label>
                <input type="password" name="password" required minlength="8"
                       class="w-full px-4 py-2 bg-slate-50 border border-slate-300 rounded-lg text-slate-900 focus:outline-none focus:ring-2 focus:ring-blue-500">
            </div>
            
            <div>
                <label class="block text-sm text-slate-500 mb-2">Role</label>
                <select name="role" class="w-full px-4 py-2 bg-slate-50 border border-slate-300 rounded-lg text-slate-900 focus:outline-none focus:ring-2 focus:ring-blue-500">
                    <option value="support">Support</option>
                    <option value="finance">Finance</option>
                    <option value="admin">Admin</option>
                </select>
            </div>
            
            <div class="flex gap-3 pt-4">
                <button type="button" onclick="closeCreateModal()" class="flex-1 px-4 py-2 bg-slate-50 hover:bg-slate-100 border border-slate-200 text-slate-700 rounded-lg transition-colors">
                    Cancel
                </button>
                <button type="submit" class="flex-1 px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition-colors">
                    Create Admin
                </button>
            </div>
        </form>
    </div>
</div>

<!-- Permissions Modal -->
<div id="permissionsModal" class="fixed inset-0 bg-black/40 hidden items-center justify-center z-50 overflow-y-auto">
    <div class="bg-white border border-slate-200 shadow-xl rounded-xl p-6 w-full max-w-2xl mx-4 my-8">
        <h3 class="text-lg font-semibold mb-4 text-slate-900">Edit Permissions for <span id="permAdminName"></span></h3>
        <form method="POST">
            <input type="hidden" name="action" value="update_permissions">
            <input type="hidden" name="admin_id" id="permAdminId">
            
            <div class="grid md:grid-cols-2 gap-4 max-h-96 overflow-y-auto">
                <?php foreach ($permissions as $key => $label): ?>
                    <label class="flex items-center gap-3 p-3 bg-slate-50/50 rounded-lg cursor-pointer hover:bg-slate-50">
                        <input type="checkbox" name="permissions[]" value="<?= $key ?>" id="perm_<?= $key ?>"
                               class="w-4 h-4 rounded bg-slate-600 border-slate-500 text-blue-600 focus:ring-blue-500">
                        <span class="text-sm text-slate-700"><?= $label ?></span>
                    </label>
                <?php endforeach; ?>
            </div>
            
            <div class="flex gap-3 pt-6">
                <button type="button" onclick="closePermissionsModal()" class="flex-1 px-4 py-2 bg-slate-50 hover:bg-slate-100 border border-slate-200 text-slate-700 rounded-lg transition-colors">
                    Cancel
                </button>
                <button type="submit" class="flex-1 px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition-colors">
                    Save Permissions
                </button>
            </div>
        </form>
    </div>
</div>

<script>
function showCreateModal() {
    document.getElementById('createModal').classList.remove('hidden');
    document.getElementById('createModal').classList.add('flex');
}

function closeCreateModal() {
    document.getElementById('createModal').classList.add('hidden');
    document.getElementById('createModal').classList.remove('flex');
}

function showPermissionsModal(adminId, adminName, currentPermissions) {
    document.getElementById('permAdminId').value = adminId;
    document.getElementById('permAdminName').textContent = adminName;
    
    // Reset all checkboxes
    document.querySelectorAll('#permissionsModal input[type="checkbox"]').forEach(cb => {
        cb.checked = currentPermissions.includes(cb.value);
    });
    
    document.getElementById('permissionsModal').classList.remove('hidden');
    document.getElementById('permissionsModal').classList.add('flex');
}

function closePermissionsModal() {
    document.getElementById('permissionsModal').classList.add('hidden');
    document.getElementById('permissionsModal').classList.remove('flex');
}
</script>

<?php renderAdminFooter(); ?>
</div>
</body>
</html>
