<?php
require 'auth_check.php';
require '../config/db.php';

// Security: Only Super Admin can access this
if ($_SESSION['role'] !== 'admin') {
    die("Access Denied. Only Super Admins can manage staff.");
}

$msg = "";

// 1. ADD / UPDATE STAFF
if (isset($_POST['save_staff'])) {
    $name = trim($_POST['name']);
    $email = trim($_POST['email']);
    $password = $_POST['password'];
    
    // Permissions Array (e.g. ['orders', 'support'])
    $perms = isset($_POST['perms']) ? json_encode($_POST['perms']) : '[]';
    
    if (!empty($_POST['staff_id'])) {
        // UPDATE
        $id = $_POST['staff_id'];
        $sql = "UPDATE users SET name=?, email=?, role='staff', permissions=? WHERE id=?";
        $params = [$name, $email, $perms, $id];
        
        if (!empty($password)) {
            $sql = "UPDATE users SET name=?, email=?, password_hash=?, role='staff', permissions=? WHERE id=?";
            $params = [$name, $email, password_hash($password, PASSWORD_DEFAULT), $perms, $id];
        }
        $pdo->prepare($sql)->execute($params);
        $msg = "Staff updated!";
    } else {
        // INSERT
        $hash = password_hash($password, PASSWORD_DEFAULT);
        $stmt = $pdo->prepare("INSERT INTO users (name, email, password_hash, role, permissions) VALUES (?, ?, ?, 'staff', ?)");
        $stmt->execute([$name, $email, $hash, $perms]);
        $msg = "Staff added!";
    }
}

// 2. DELETE STAFF
if (isset($_GET['delete'])) {
    $pdo->prepare("DELETE FROM users WHERE id=? AND role='staff'")->execute([$_GET['delete']]);
    header("Location: staff.php"); exit();
}

// 3. FETCH STAFF
$staff_members = $pdo->query("SELECT * FROM users WHERE role='staff' ORDER BY id DESC")->fetchAll();
$edit_staff = null;
if (isset($_GET['edit'])) {
    $edit_staff = $pdo->query("SELECT * FROM users WHERE id=" . $_GET['edit'])->fetch();
}

// Helper to check checked boxes
function hasPerm($key, $user) {
    if (!$user) return false;
    $p = json_decode($user['permissions'], true);
    return is_array($p) && in_array($key, $p);
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Manage Staff</title>
    <link rel="stylesheet" href="admin_style.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        .form-card { background: white; padding: 25px; border-radius: 8px; margin-bottom: 30px; box-shadow: 0 2px 5px rgba(0,0,0,0.05); }
        .perm-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 10px; margin-top: 10px; }
        .perm-item { background: #f9f9f9; padding: 10px; border: 1px solid #eee; border-radius: 5px; cursor: pointer; }
        .perm-item:hover { border-color: #3498db; }
    </style>
</head>
<body>
    <div class="sidebar"><?php include 'sidebar.php'; ?></div>

    <div class="content">
        <h1>Staff Management</h1>
        <?php if($msg): ?><p style="color:green; font-weight:bold;"><?php echo $msg; ?></p><?php endif; ?>

        <div class="form-card">
            <h3><?php echo $edit_staff ? "Edit Staff: " . $edit_staff['name'] : "Add New Staff"; ?></h3>
            <form method="POST">
                <input type="hidden" name="staff_id" value="<?php echo $edit_staff['id'] ?? ''; ?>">
                
                <div style="display:grid; grid-template-columns: 1fr 1fr; gap:20px; margin-bottom:20px;">
                    <input type="text" name="name" placeholder="Full Name" class="form-control" required value="<?php echo $edit_staff['name'] ?? ''; ?>" style="padding:10px;">
                    <input type="email" name="email" placeholder="Email" class="form-control" required value="<?php echo $edit_staff['email'] ?? ''; ?>" style="padding:10px;">
                </div>
                
                <input type="text" name="password" placeholder="<?php echo $edit_staff ? 'Leave blank to keep current password' : 'Password'; ?>" class="form-control" <?php echo $edit_staff ? '' : 'required'; ?> style="padding:10px; width:100%; margin-bottom:20px;">

                <label style="font-weight:bold;">Assign Permissions:</label>
                <div class="perm-grid">
                    <label class="perm-item"><input type="checkbox" name="perms[]" value="orders" <?php if(hasPerm('orders', $edit_staff)) echo 'checked'; ?>> Orders & Sales</label>
                    <label class="perm-item"><input type="checkbox" name="perms[]" value="products" <?php if(hasPerm('products', $edit_staff)) echo 'checked'; ?>> Products & Stock</label>
                    <label class="perm-item"><input type="checkbox" name="perms[]" value="users" <?php if(hasPerm('users', $edit_staff)) echo 'checked'; ?>> Users & Resellers</label>
                    <label class="perm-item"><input type="checkbox" name="perms[]" value="marketing" <?php if(hasPerm('marketing', $edit_staff)) echo 'checked'; ?>> Marketing (Blog/Coupons)</label>
                    <label class="perm-item"><input type="checkbox" name="perms[]" value="support" <?php if(hasPerm('support', $edit_staff)) echo 'checked'; ?>> Support (Tickets/Reviews)</label>
                    <label class="perm-item"><input type="checkbox" name="perms[]" value="settings" <?php if(hasPerm('settings', $edit_staff)) echo 'checked'; ?>> Settings (Admin Only)</label>
                </div>

                <button type="submit" name="save_staff" class="btn btn-primary" style="margin-top:20px; padding:10px 20px; background:#2c3e50; color:white; border:none; cursor:pointer;">Save Staff Member</button>
            </form>
        </div>

        <table style="width:100%; background:white; border-collapse:collapse;">
            <thead><tr style="background:#eee;"><th>Name</th><th>Email</th><th>Permissions</th><th>Action</th></tr></thead>
            <tbody>
                <?php foreach($staff_members as $s): 
                    $p_list = json_decode($s['permissions'] ?? '[]', true);
                    $badges = "";
                    foreach($p_list as $p) { $badges .= "<span style='background:#e0f7fa; color:#006064; padding:2px 6px; border-radius:4px; font-size:11px; margin-right:5px;'>".ucfirst($p)."</span>"; }
                ?>
                <tr>
                    <td style="padding:10px; border-bottom:1px solid #eee;"><?php echo htmlspecialchars($s['name']); ?></td>
                    <td style="padding:10px; border-bottom:1px solid #eee;"><?php echo htmlspecialchars($s['email']); ?></td>
                    <td style="padding:10px; border-bottom:1px solid #eee;"><?php echo $badges ?: 'None'; ?></td>
                    <td style="padding:10px; border-bottom:1px solid #eee;">
                        <a href="staff.php?edit=<?php echo $s['id']; ?>" style="color:blue;">Edit</a> | 
                        <a href="staff.php?delete=<?php echo $s['id']; ?>" style="color:red;" onclick="return confirm('Remove staff?')">Delete</a>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</body>
</html>