<?php
$page_title = "Admin Users Management";
require_once 'header.php';

$db = Database::getInstance()->connect();

// Check if current user is superadmin
$current_admin_id = $_SESSION['admin_id'] ?? 0;
$stmt = $db->prepare("SELECT role FROM admin_users WHERE id = ?");
$stmt->execute([$current_admin_id]);
$current_role = $stmt->fetchColumn();

// Handle Actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Only superadmin can manage admins
    if ($current_role !== 'superadmin') {
        $error = "Access Denied. Superadmin privileges required.";
    } elseif (isset($_POST['action'])) {
        $action = $_POST['action'];
        
        if ($action === 'add') {
            $username = trim($_POST['username']);
            $email = trim($_POST['email']);
            $password = $_POST['password'];
            $role = $_POST['role'];
            
            if (empty($username) || empty($email) || empty($password)) {
                $error = "All fields are required";
            } else {
                $check = $db->prepare("SELECT id FROM admin_users WHERE username = ? OR email = ?");
                $check->execute([$username, $email]);
                if ($check->rowCount() > 0) {
                    $error = "Username or Email already exists";
                } else {
                    $hashed_password = password_hash($password, PASSWORD_DEFAULT);
                    $stmt = $db->prepare("INSERT INTO admin_users (username, email, password, role, created_at) VALUES (?, ?, ?, ?, NOW())");
                    if ($stmt->execute([$username, $email, $hashed_password, $role])) {
                        $success = "Admin user created successfully";
                        
                        // Log action
                        $log_stmt = $db->prepare("INSERT INTO activity_logs (admin_id, action, description, ip_address, created_at) VALUES (?, 'create_admin', ?, ?, NOW())");
                        $log_stmt->execute([$current_admin_id, "Created admin user: $username", $_SERVER['REMOTE_ADDR'] ?? '']);
                    } else {
                        $error = "Failed to create admin user";
                    }
                }
            }
        } elseif ($action === 'edit') {
            $id = $_POST['id'];
            $username = trim($_POST['username']);
            $email = trim($_POST['email']);
            $role = $_POST['role'];
            $status = $_POST['status'];
            $password = $_POST['password'];
            
            if (empty($username) || empty($email)) {
                $error = "Username and Email are required";
            } else {
                $check = $db->prepare("SELECT id FROM admin_users WHERE (username = ? OR email = ?) AND id != ?");
                $check->execute([$username, $email, $id]);
                if ($check->rowCount() > 0) {
                    $error = "Username or Email already exists";
                } else {
                    $sql = "UPDATE admin_users SET username = ?, email = ?, role = ?, status = ?, updated_at = NOW()";
                    $params = [$username, $email, $role, $status];
                    
                    if (!empty($password)) {
                        $sql .= ", password = ?";
                        $params[] = password_hash($password, PASSWORD_DEFAULT);
                    }
                    
                    $sql .= " WHERE id = ?";
                    $params[] = $id;
                    
                    $stmt = $db->prepare($sql);
                    if ($stmt->execute($params)) {
                        $success = "Admin user updated successfully";
                        
                        // Log action
                        $log_stmt = $db->prepare("INSERT INTO activity_logs (admin_id, action, description, ip_address, created_at) VALUES (?, 'update_admin', ?, ?, NOW())");
                        $log_stmt->execute([$current_admin_id, "Updated admin user: $username", $_SERVER['REMOTE_ADDR'] ?? '']);
                    } else {
                        $error = "Failed to update admin user";
                    }
                }
            }
        } elseif ($action === 'delete') {
            $id = $_POST['id'];
            if ($id == $current_admin_id) {
                $error = "You cannot delete your own account";
            } else {
                $stmt = $db->prepare("DELETE FROM admin_users WHERE id = ?");
                if ($stmt->execute([$id])) {
                    $success = "Admin user deleted successfully";
                    
                    // Log action
                    $log_stmt = $db->prepare("INSERT INTO activity_logs (admin_id, action, description, ip_address, created_at) VALUES (?, 'delete_admin', ?, ?, NOW())");
                    $log_stmt->execute([$current_admin_id, "Deleted admin user ID: $id", $_SERVER['REMOTE_ADDR'] ?? '']);
                } else {
                    $error = "Failed to delete admin user";
                }
            }
        }
    }
}

// Fetch Admin Users
$stmt = $db->query("SELECT * FROM admin_users ORDER BY created_at DESC");
$admins = $stmt->fetchAll();
?>

<div class="container-fluid">
    <!-- Page Header -->
    <div class="mb-6 flex justify-between items-center">
        <div>
            <h1 class="text-2xl font-bold">Admin Users Management</h1>
            <p class="text-gray-600">Manage admin accounts and permissions</p>
        </div>
        <?php if ($current_role === 'superadmin'): ?>
        <button onclick="openAddModal()" class="bg-purple-600 text-white px-4 py-2 rounded-lg hover:bg-purple-700">
            <i class="fas fa-plus mr-2"></i>Add New Admin
        </button>
        <?php endif; ?>
    </div>

    <!-- Messages -->
    <?php if (isset($error)): ?>
    <div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-4">
        <?php echo $error; ?>
    </div>
    <?php endif; ?>
    
    <?php if (isset($success)): ?>
    <div class="bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded mb-4">
        <?php echo $success; ?>
    </div>
    <?php endif; ?>

    <!-- Admin Users Table -->
    <div class="bg-white rounded-xl shadow overflow-hidden">
        <div class="overflow-x-auto">
            <table class="w-full">
                <thead class="bg-gray-50">
                    <tr>
                        <th class="p-4 text-left">User</th>
                        <th class="p-4 text-left">Role</th>
                        <th class="p-4 text-left">Status</th>
                        <th class="p-4 text-left">Last Login</th>
                        <th class="p-4 text-left">Created At</th>
                        <th class="p-4 text-left">Actions</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-gray-100">
                    <?php foreach ($admins as $admin): ?>
                    <tr class="hover:bg-gray-50">
                        <td class="p-4">
                            <div class="flex items-center">
                                <div class="w-10 h-10 rounded-full bg-purple-100 flex items-center justify-center text-purple-600 font-bold mr-3">
                                    <?php echo strtoupper(substr($admin['username'], 0, 1)); ?>
                                </div>
                                <div>
                                    <p class="font-medium"><?php echo htmlspecialchars($admin['username']); ?></p>
                                    <p class="text-sm text-gray-500"><?php echo htmlspecialchars($admin['email']); ?></p>
                                </div>
                            </div>
                        </td>
                        <td class="p-4">
                            <span class="px-2 py-1 rounded-full text-xs font-semibold 
                                <?php echo $admin['role'] === 'superadmin' ? 'bg-red-100 text-red-800' : 'bg-blue-100 text-blue-800'; ?>">
                                <?php echo ucfirst($admin['role']); ?>
                            </span>
                        </td>
                        <td class="p-4">
                            <span class="px-2 py-1 rounded-full text-xs font-semibold 
                                <?php echo $admin['status'] === 'active' ? 'bg-green-100 text-green-800' : 'bg-gray-100 text-gray-800'; ?>">
                                <?php echo ucfirst($admin['status']); ?>
                            </span>
                        </td>
                        <td class="p-4">
                            <?php if ($admin['last_login']): ?>
                                <p class="text-sm"><?php echo date('M d, Y H:i', strtotime($admin['last_login'])); ?></p>
                                <p class="text-xs text-gray-500"><?php echo $admin['last_ip']; ?></p>
                            <?php else: ?>
                                <span class="text-gray-500 text-sm">Never</span>
                            <?php endif; ?>
                        </td>
                        <td class="p-4">
                            <p class="text-sm"><?php echo date('M d, Y', strtotime($admin['created_at'])); ?></p>
                        </td>
                        <td class="p-4">
                            <?php if ($current_role === 'superadmin'): ?>
                            <div class="flex space-x-2">
                                <button onclick="openEditModal(<?php echo htmlspecialchars(json_encode($admin)); ?>)" 
                                        class="text-blue-600 hover:text-blue-800">
                                    <i class="fas fa-edit"></i>
                                </button>
                                <?php if ($admin['id'] != $current_admin_id): ?>
                                <button onclick="deleteAdmin(<?php echo $admin['id']; ?>)" 
                                        class="text-red-600 hover:text-red-800">
                                    <i class="fas fa-trash"></i>
                                </button>
                                <?php endif; ?>
                            </div>
                            <?php endif; ?>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Add/Edit Modal -->
<div id="adminModal" class="fixed inset-0 bg-black bg-opacity-50 hidden z-50 flex items-center justify-center">
    <div class="bg-white rounded-xl shadow-xl w-full max-w-md p-6">
        <h3 id="modalTitle" class="text-xl font-bold mb-4">Add New Admin</h3>
        <form method="POST" action="">
            <input type="hidden" name="action" id="formAction" value="add">
            <input type="hidden" name="id" id="adminId">
            
            <div class="space-y-4">
                <div>
                    <label class="block text-gray-700 text-sm font-medium mb-1">Username</label>
                    <input type="text" name="username" id="username" required
                           class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500">
                </div>
                
                <div>
                    <label class="block text-gray-700 text-sm font-medium mb-1">Email</label>
                    <input type="email" name="email" id="email" required
                           class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500">
                </div>
                
                <div>
                    <label class="block text-gray-700 text-sm font-medium mb-1">Password</label>
                    <input type="password" name="password" id="password"
                           class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500">
                    <p class="text-xs text-gray-500 mt-1" id="passwordHelp">Required for new users</p>
                </div>
                
                <div>
                    <label class="block text-gray-700 text-sm font-medium mb-1">Role</label>
                    <select name="role" id="role" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500">
                        <option value="admin">Admin</option>
                        <option value="superadmin">Super Admin</option>
                        <option value="support">Support</option>
                        <option value="moderator">Moderator</option>
                    </select>
                </div>
                
                <div id="statusField" class="hidden">
                    <label class="block text-gray-700 text-sm font-medium mb-1">Status</label>
                    <select name="status" id="status" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500">
                        <option value="active">Active</option>
                        <option value="inactive">Inactive</option>
                    </select>
                </div>
            </div>
            
            <div class="mt-6 flex justify-end space-x-3">
                <button type="button" onclick="closeModal()" class="px-4 py-2 bg-gray-200 text-gray-800 rounded-lg hover:bg-gray-300">
                    Cancel
                </button>
                <button type="submit" class="px-4 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700">
                    Save
                </button>
            </div>
        </form>
    </div>
</div>

<script>
function openAddModal() {
    document.getElementById('modalTitle').textContent = 'Add New Admin';
    document.getElementById('formAction').value = 'add';
    document.getElementById('adminId').value = '';
    document.getElementById('username').value = '';
    document.getElementById('email').value = '';
    document.getElementById('password').value = '';
    document.getElementById('password').required = true;
    document.getElementById('passwordHelp').textContent = 'Required for new users';
    document.getElementById('role').value = 'admin';
    document.getElementById('statusField').classList.add('hidden');
    document.getElementById('adminModal').classList.remove('hidden');
}

function openEditModal(admin) {
    document.getElementById('modalTitle').textContent = 'Edit Admin';
    document.getElementById('formAction').value = 'edit';
    document.getElementById('adminId').value = admin.id;
    document.getElementById('username').value = admin.username;
    document.getElementById('email').value = admin.email;
    document.getElementById('password').value = '';
    document.getElementById('password').required = false;
    document.getElementById('passwordHelp').textContent = 'Leave blank to keep current password';
    document.getElementById('role').value = admin.role;
    document.getElementById('status').value = admin.status;
    document.getElementById('statusField').classList.remove('hidden');
    document.getElementById('adminModal').classList.remove('hidden');
}

function closeModal() {
    document.getElementById('adminModal').classList.add('hidden');
}

function deleteAdmin(id) {
    if (confirm('Are you sure you want to delete this admin user?')) {
        const form = document.createElement('form');
        form.method = 'POST';
        form.innerHTML = `<input type="hidden" name="action" value="delete"><input type="hidden" name="id" value="${id}">`;
        document.body.appendChild(form);
        form.submit();
    }
}
</script>

<?php require_once 'footer.php'; ?>