<?php
/**
 * Edit Staff User
 * LandSales Pro - Edit existing 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');

$errors = [];

// Available permissions
$availablePermissions = [
    'dashboard' => ['label' => 'Dashboard', 'icon' => 'tachometer-alt', 'desc' => 'View main dashboard'],
    'projects_view' => ['label' => 'View Projects', 'icon' => 'project-diagram', 'desc' => 'View project list and details'],
    'projects_manage' => ['label' => 'Manage Projects', 'icon' => 'project-diagram', 'desc' => 'Create, edit, delete projects'],
    'plots_view' => ['label' => 'View Plots', 'icon' => 'th', 'desc' => 'View plot list, grid, and details'],
    'plots_manage' => ['label' => 'Manage Plots', 'icon' => 'th', 'desc' => 'Create, edit, delete plots'],
    'buyers_view' => ['label' => 'View Buyers', 'icon' => 'users', 'desc' => 'View buyer list and details'],
    'buyers_manage' => ['label' => 'Manage Buyers', 'icon' => 'users', 'desc' => 'Create, edit buyers'],
    'sales_view' => ['label' => 'View Sales', 'icon' => 'handshake', 'desc' => 'View sales records'],
    'sales_manage' => ['label' => 'Manage Sales', 'icon' => 'handshake', 'desc' => 'Create, edit sales'],
    'payments_view' => ['label' => 'View Payments', 'icon' => 'money-bill-wave', 'desc' => 'View payment records'],
    'payments_manage' => ['label' => 'Manage Payments', 'icon' => 'money-bill-wave', 'desc' => 'Record payments, generate receipts'],
    'agents_view' => ['label' => 'View Agents', 'icon' => 'user-tie', 'desc' => 'View agent list'],
    'agents_manage' => ['label' => 'Manage Agents', 'icon' => 'user-tie', 'desc' => 'Create, edit agents'],
    'reports' => ['label' => 'Reports', 'icon' => 'chart-bar', 'desc' => 'View all reports'],
    'settings' => ['label' => 'Settings', 'icon' => 'cog', 'desc' => 'View and modify settings'],
];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $fullName = trim($_POST['full_name'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $phone = trim($_POST['phone'] ?? '');
    $password = $_POST['password'] ?? '';
    $confirmPassword = $_POST['confirm_password'] ?? '';
    $status = $_POST['status'] ?? 'active';
    $permissions = $_POST['permissions'] ?? [];

    // Validation
    if (empty($fullName)) $errors[] = "Full name is required";
    if (empty($email)) $errors[] = "Email is required";
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) $errors[] = "Invalid email format";
    if ($password && strlen($password) < 6) $errors[] = "Password must be at least 6 characters";
    if ($password && $password !== $confirmPassword) $errors[] = "Passwords do not match";

    // Check for duplicate email within this owner's staff (excluding current)
    if (empty($errors)) {
        $existing = db_fetch_one("SELECT id FROM staff_users WHERE owner_id = ? AND email = ? AND id != ?", 'isi', [$userId, $email, $staffId]);
        if ($existing) {
            $errors[] = "A staff user with this email already exists";
        }
    }

    if (empty($errors)) {
        $sql = "UPDATE staff_users SET full_name = ?, email = ?, phone = ?, status = ?, updated_at = NOW() WHERE id = ? AND owner_id = ?";
        $params = [$fullName, $email, $phone ?: null, $status, $staffId, $userId];
        $types = 'ssssii';

        if (db_execute($sql, $types, $params)) {
            // Update password if provided
            if ($password) {
                $hashedPassword = password_hash($password, PASSWORD_DEFAULT);
                db_execute("UPDATE staff_users SET password = ? WHERE id = ?", 'si', [$hashedPassword, $staffId]);
            }

            // Update permissions - delete all and re-insert
            db_execute("DELETE FROM staff_permissions WHERE staff_id = ?", 'i', [$staffId]);
            foreach ($permissions as $permission) {
                if (isset($availablePermissions[$permission])) {
                    db_execute("INSERT INTO staff_permissions (staff_id, permission) VALUES (?, ?)", 'is', [$staffId, $permission]);
                }
            }

            logActivity('staff_updated', "Updated staff user: {$fullName}");
            setFlashMessage('Staff user updated successfully!', 'success');
            header('Location: index.php');
            exit;
        } else {
            $errors[] = "Failed to update staff user. Please try again.";
        }
    }

    // Update permissions array for form re-display
    $currentPermissionsArray = $permissions;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Edit Staff User - <?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">Edit Staff User</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">
                <?php if (!empty($errors)): ?>
                <div class="alert alert-danger">
                    <i class="fas fa-exclamation-circle"></i>
                    <ul>
                        <?php foreach ($errors as $error): ?>
                        <li><?php echo htmlspecialchars($error); ?></li>
                        <?php endforeach; ?>
                    </ul>
                </div>
                <?php endif; ?>

                <form method="POST">
                    <div class="card">
                        <div class="card-header">
                            <h3><i class="fas fa-user-edit"></i> User Information</h3>
                        </div>
                        <div class="card-body">
                            <div class="form-group">
                                <label for="full_name">Full Name *</label>
                                <input type="text" name="full_name" id="full_name" class="form-control"
                                       value="<?php echo htmlspecialchars($_POST['full_name'] ?? $staff['full_name']); ?>"
                                       placeholder="e.g., John Mwamba" required>
                            </div>

                            <div class="form-row">
                                <div class="form-group">
                                    <label for="email">Email *</label>
                                    <input type="email" name="email" id="email" class="form-control"
                                           value="<?php echo htmlspecialchars($_POST['email'] ?? $staff['email']); ?>"
                                           placeholder="e.g., john@example.com" required>
                                </div>
                                <div class="form-group">
                                    <label for="phone">Phone</label>
                                    <input type="tel" name="phone" id="phone" class="form-control"
                                           value="<?php echo htmlspecialchars($_POST['phone'] ?? $staff['phone'] ?? ''); ?>"
                                           placeholder="e.g., 0712345678">
                                </div>
                            </div>

                            <div class="form-row">
                                <div class="form-group">
                                    <label for="password">New Password</label>
                                    <input type="password" name="password" id="password" class="form-control"
                                           placeholder="Leave blank to keep current">
                                </div>
                                <div class="form-group">
                                    <label for="confirm_password">Confirm New Password</label>
                                    <input type="password" name="confirm_password" id="confirm_password" class="form-control"
                                           placeholder="Repeat new password">
                                </div>
                            </div>

                            <div class="form-group">
                                <label for="status">Status</label>
                                <select name="status" id="status" class="form-control">
                                    <option value="active" <?php echo ($_POST['status'] ?? $staff['status']) === 'active' ? 'selected' : ''; ?>>Active</option>
                                    <option value="inactive" <?php echo ($_POST['status'] ?? $staff['status']) === 'inactive' ? 'selected' : ''; ?>>Inactive</option>
                                </select>
                            </div>

                            <?php if ($staff['last_login']): ?>
                            <div class="user-stats">
                                <div class="stat-item">
                                    <span class="stat-label">Last Login</span>
                                    <span class="stat-value"><?php echo date('M j, Y H:i', strtotime($staff['last_login'])); ?></span>
                                </div>
                                <div class="stat-item">
                                    <span class="stat-label">Login Count</span>
                                    <span class="stat-value"><?php echo number_format($staff['login_count']); ?></span>
                                </div>
                            </div>
                            <?php endif; ?>
                        </div>
                    </div>

                    <div class="card mt-4">
                        <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-3">Select what this user can access and manage in the system.</p>

                            <div class="permissions-grid">
                                <?php foreach ($availablePermissions 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>
                    </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-check"></i> Update Staff User
                        </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; }

        .form-container { max-width: 700px; }
        .mt-4 { margin-top: 1.5rem; }

        .alert { padding: 1rem 1.5rem; border-radius: 10px; margin-bottom: 1.5rem; display: flex; gap: 0.75rem; }
        .alert-danger { background: #fef2f2; border: 1px solid #fecaca; color: #991b1b; }
        .alert ul { margin: 0; padding-left: 1rem; }

        .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; }

        .form-row { display: grid; grid-template-columns: 1fr 1fr; gap: 1rem; }
        .form-group { margin-bottom: 1.25rem; }
        .form-group:last-child { margin-bottom: 0; }
        .form-group label { display: block; margin-bottom: 0.5rem; font-weight: 500; color: #374151; font-size: 0.875rem; }
        .form-control { width: 100%; padding: 0.75rem 1rem; border: 1px solid #e2e8f0; border-radius: 8px; font-size: 0.9rem; transition: all 0.2s; box-sizing: border-box; }
        .form-control:focus { outline: none; border-color: #667eea; box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1); }

        .user-stats { display: flex; gap: 2rem; padding: 1rem; background: #f8fafc; border-radius: 8px; margin-top: 1rem; }
        .stat-item { }
        .stat-label { display: block; font-size: 0.75rem; color: #64748b; margin-bottom: 0.25rem; }
        .stat-value { font-weight: 600; color: #1e293b; }

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

        .permissions-grid { 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) {
            .form-row { grid-template-columns: 1fr; }
            .permissions-grid { grid-template-columns: 1fr; }
            .form-actions { flex-direction: column-reverse; }
            .form-actions .btn { width: 100%; justify-content: center; }
            .user-stats { flex-direction: column; gap: 1rem; }
        }
    </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);
    }
    </script>
</body>
</html>
