<?php
/**
 * Staff User Permissions
 * LandSales Pro - Manage permissions for a staff user
 */
define('APP_RUNNING', true);
require_once '../../db_connect.php';
require_once '../../includes/auth.php';
require_once '../../includes/subscription.php';
require_once '../../includes/functions.php';

initSecureSession();
requireAuth();
requireSubscription();

$userId = $_SESSION['user_id'];
$staffId = intval($_GET['id'] ?? 0);

// Get staff user
$staff = db_fetch_one("SELECT * FROM staff_users WHERE id = ? AND owner_id = ?", 'ii', [$staffId, $userId]);
if (!$staff) {
    setFlashMessage('Staff user not found', 'error');
    header('Location: index.php');
    exit;
}

// Get current permissions
$currentPermissions = db_fetch_all("SELECT permission FROM staff_permissions WHERE staff_id = ?", 'i', [$staffId]);
$currentPermissionsArray = array_column($currentPermissions, 'permission');

// Available permissions grouped
$permissionGroups = [
    'General' => [
        'dashboard' => ['label' => 'Dashboard', 'icon' => 'tachometer-alt', 'desc' => 'View main dashboard with statistics'],
    ],
    'Projects' => [
        'projects_view' => ['label' => 'View Projects', 'icon' => 'eye', 'desc' => 'View project list and details'],
        'projects_manage' => ['label' => 'Manage Projects', 'icon' => 'edit', 'desc' => 'Create, edit, delete projects'],
    ],
    'Plots' => [
        'plots_view' => ['label' => 'View Plots', 'icon' => 'eye', 'desc' => 'View plot list, grid, and details'],
        'plots_manage' => ['label' => 'Manage Plots', 'icon' => 'edit', 'desc' => 'Create, edit, delete plots'],
    ],
    'Buyers' => [
        'buyers_view' => ['label' => 'View Buyers', 'icon' => 'eye', 'desc' => 'View buyer list and details'],
        'buyers_manage' => ['label' => 'Manage Buyers', 'icon' => 'edit', 'desc' => 'Create, edit buyer records'],
    ],
    'Sales' => [
        'sales_view' => ['label' => 'View Sales', 'icon' => 'eye', 'desc' => 'View sales records and history'],
        'sales_manage' => ['label' => 'Manage Sales', 'icon' => 'edit', 'desc' => 'Create, edit sales transactions'],
    ],
    'Payments' => [
        'payments_view' => ['label' => 'View Payments', 'icon' => 'eye', 'desc' => 'View payment records'],
        'payments_manage' => ['label' => 'Manage Payments', 'icon' => 'edit', 'desc' => 'Record payments, generate receipts'],
    ],
    'Agents' => [
        'agents_view' => ['label' => 'View Agents', 'icon' => 'eye', 'desc' => 'View sales agents'],
        'agents_manage' => ['label' => 'Manage Agents', 'icon' => 'edit', 'desc' => 'Create, edit agents'],
    ],
    'Reports & Settings' => [
        'reports' => ['label' => 'View Reports', 'icon' => 'chart-bar', 'desc' => 'Access all reports'],
        'settings' => ['label' => 'Settings', 'icon' => 'cog', 'desc' => 'View and modify company settings'],
    ],
];

$errors = [];
$success = false;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $permissions = $_POST['permissions'] ?? [];

    // Delete all and re-insert
    db_execute("DELETE FROM staff_permissions WHERE staff_id = ?", 'i', [$staffId]);

    foreach ($permissions as $permission) {
        db_execute("INSERT INTO staff_permissions (staff_id, permission) VALUES (?, ?)", 'is', [$staffId, $permission]);
    }

    logActivity('staff_permissions_updated', "Updated permissions for: {$staff['full_name']}");
    $success = true;
    $currentPermissionsArray = $permissions;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Permissions - <?php echo APP_NAME; ?></title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="<?php echo SITE_URL; ?>/assets/font-awesome/css/all.min.css">
</head>
<body>
    <?php include '../includes/sidebar.php'; ?>

    <div class="main-content">
        <div class="top-header">
            <button class="menu-toggle" onclick="toggleSidebar()">
                <i class="fas fa-bars"></i>
            </button>
            <h1 class="page-title">Manage Permissions</h1>
            <div class="header-actions">
                <a href="index.php" class="btn btn-outline">
                    <i class="fas fa-arrow-left"></i> Back
                </a>
            </div>
        </div>

        <div class="content-wrapper">
            <div class="form-container">
                <!-- User Info Card -->
                <div class="user-info-card">
                    <div class="user-avatar">
                        <?php echo strtoupper(substr($staff['full_name'], 0, 1)); ?>
                    </div>
                    <div class="user-details">
                        <h3><?php echo htmlspecialchars($staff['full_name']); ?></h3>
                        <p><?php echo htmlspecialchars($staff['email']); ?></p>
                        <span class="status-badge status-<?php echo $staff['status']; ?>">
                            <?php echo ucfirst($staff['status']); ?>
                        </span>
                    </div>
                </div>

                <?php if ($success): ?>
                <div class="alert alert-success">
                    <i class="fas fa-check-circle"></i>
                    Permissions updated successfully!
                </div>
                <?php endif; ?>

                <form method="POST">
                    <div class="card">
                        <div class="card-header">
                            <h3><i class="fas fa-key"></i> Permissions</h3>
                            <div class="card-header-actions">
                                <button type="button" class="btn btn-sm btn-outline" onclick="selectAll()">Select All</button>
                                <button type="button" class="btn btn-sm btn-outline" onclick="deselectAll()">Deselect All</button>
                            </div>
                        </div>
                        <div class="card-body">
                            <p class="text-muted mb-4">Control what this user can see and do in the system. "View" permissions allow read-only access, while "Manage" permissions allow creating and editing records.</p>

                            <?php foreach ($permissionGroups as $groupName => $permissions): ?>
                            <div class="permission-group">
                                <h4 class="group-title">
                                    <i class="fas fa-folder"></i>
                                    <?php echo $groupName; ?>
                                    <button type="button" class="btn-link" onclick="toggleGroup('<?php echo strtolower($groupName); ?>')">
                                        Toggle All
                                    </button>
                                </h4>
                                <div class="permissions-list" data-group="<?php echo strtolower($groupName); ?>">
                                    <?php foreach ($permissions as $key => $perm): ?>
                                    <label class="permission-item">
                                        <input type="checkbox" name="permissions[]" value="<?php echo $key; ?>"
                                               <?php echo in_array($key, $currentPermissionsArray) ? 'checked' : ''; ?>>
                                        <div class="permission-content">
                                            <i class="fas fa-<?php echo $perm['icon']; ?>"></i>
                                            <div>
                                                <span class="permission-label"><?php echo $perm['label']; ?></span>
                                                <span class="permission-desc"><?php echo $perm['desc']; ?></span>
                                            </div>
                                        </div>
                                    </label>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                            <?php endforeach; ?>
                        </div>
                    </div>

                    <div class="form-actions">
                        <a href="index.php" class="btn btn-outline">Cancel</a>
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-save"></i> Save Permissions
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <style>
        body { font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif; margin: 0; background: #f1f5f9; }
        .header-actions { display: flex; gap: 0.75rem; }
        .btn { padding: 0.625rem 1.25rem; border-radius: 8px; font-weight: 500; text-decoration: none; display: inline-flex; align-items: center; gap: 0.5rem; transition: all 0.2s; border: none; cursor: pointer; font-size: 0.875rem; }
        .btn-sm { padding: 0.375rem 0.75rem; font-size: 0.8rem; }
        .btn-primary { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; }
        .btn-outline { border: 1px solid #e2e8f0; background: white; color: #64748b; }
        .btn-link { background: none; border: none; color: #667eea; font-size: 0.75rem; cursor: pointer; text-decoration: underline; }

        .form-container { max-width: 700px; }

        .user-info-card { display: flex; align-items: center; gap: 1rem; padding: 1.25rem; background: white; border-radius: 14px; box-shadow: 0 2px 8px rgba(0,0,0,0.05); margin-bottom: 1.5rem; }
        .user-info-card .user-avatar { width: 60px; height: 60px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border-radius: 12px; color: white; display: flex; align-items: center; justify-content: center; font-weight: 700; font-size: 1.5rem; }
        .user-details h3 { margin: 0 0 0.25rem 0; font-size: 1.1rem; color: #1e293b; }
        .user-details p { margin: 0 0 0.5rem 0; color: #64748b; font-size: 0.9rem; }

        .status-badge { padding: 0.25rem 0.625rem; border-radius: 20px; font-size: 0.75rem; font-weight: 500; }
        .status-active { background: #dcfce7; color: #166534; }
        .status-inactive { background: #fee2e2; color: #991b1b; }

        .alert { padding: 1rem 1.5rem; border-radius: 10px; margin-bottom: 1.5rem; display: flex; align-items: center; gap: 0.75rem; }
        .alert-success { background: #dcfce7; border: 1px solid #86efac; color: #166534; }

        .card { background: white; border-radius: 14px; box-shadow: 0 2px 8px rgba(0,0,0,0.05); overflow: hidden; }
        .card-header { padding: 1.25rem 1.5rem; border-bottom: 1px solid #f1f5f9; background: #f8fafc; display: flex; justify-content: space-between; align-items: center; }
        .card-header h3 { margin: 0; font-size: 1rem; font-weight: 600; color: #1e293b; display: flex; align-items: center; gap: 0.5rem; }
        .card-header h3 i { color: #667eea; }
        .card-header-actions { display: flex; gap: 0.5rem; }
        .card-body { padding: 1.5rem; }

        .text-muted { color: #64748b; font-size: 0.875rem; }
        .mb-4 { margin-bottom: 1.5rem; }

        .permission-group { margin-bottom: 1.5rem; padding-bottom: 1.5rem; border-bottom: 1px solid #f1f5f9; }
        .permission-group:last-child { margin-bottom: 0; padding-bottom: 0; border-bottom: none; }
        .group-title { display: flex; align-items: center; gap: 0.5rem; font-size: 0.875rem; font-weight: 600; color: #1e293b; margin: 0 0 1rem 0; }
        .group-title i { color: #667eea; }
        .group-title .btn-link { margin-left: auto; }

        .permissions-list { display: grid; grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); gap: 0.75rem; }
        .permission-item { display: flex; align-items: flex-start; gap: 0.75rem; padding: 1rem; border: 1px solid #e2e8f0; border-radius: 10px; cursor: pointer; transition: all 0.2s; }
        .permission-item:hover { border-color: #667eea; background: #f8fafc; }
        .permission-item input { margin-top: 0.25rem; }
        .permission-item:has(input:checked) { border-color: #667eea; background: linear-gradient(135deg, rgba(102, 126, 234, 0.05) 0%, rgba(118, 75, 162, 0.05) 100%); }
        .permission-content { display: flex; gap: 0.75rem; align-items: flex-start; }
        .permission-content i { color: #667eea; font-size: 1rem; margin-top: 0.125rem; }
        .permission-label { display: block; font-weight: 500; color: #1e293b; font-size: 0.875rem; }
        .permission-desc { display: block; font-size: 0.75rem; color: #64748b; margin-top: 0.125rem; }

        .form-actions { margin-top: 1.5rem; display: flex; justify-content: flex-end; gap: 1rem; }

        @media (max-width: 576px) {
            .permissions-list { grid-template-columns: 1fr; }
            .form-actions { flex-direction: column-reverse; }
            .form-actions .btn { width: 100%; justify-content: center; }
        }
    </style>

    <script>
    function selectAll() {
        document.querySelectorAll('input[name="permissions[]"]').forEach(cb => cb.checked = true);
    }
    function deselectAll() {
        document.querySelectorAll('input[name="permissions[]"]').forEach(cb => cb.checked = false);
    }
    function toggleGroup(group) {
        const checkboxes = document.querySelectorAll(`[data-group="${group}"] input[type="checkbox"]`);
        const allChecked = Array.from(checkboxes).every(cb => cb.checked);
        checkboxes.forEach(cb => cb.checked = !allChecked);
    }
    </script>
</body>
</html>
