<?php
require_once '../includes/constants.php';
require_once '../includes/session.php';
require_once '../includes/functions.php';

if (!isset($_SESSION['admin_id']) || $_SESSION['admin_role'] !== 'superadmin') {
    die("Access denied");
}

// Handle new admin creation
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['create_admin'])) {
    $hash = password_hash($_POST['password'], PASSWORD_DEFAULT);
    $stmt = $pdo->prepare("INSERT INTO admin_users (username, password_hash, email, role, is_active)
                           VALUES (?, ?, ?, ?, ?)");
    $stmt->execute([
        $_POST['username'],
        $hash,
        $_POST['email'],
        $_POST['role'],
        isset($_POST['is_active']) ? 1 : 0
    ]);
    echo "<p class='success'>✅ Admin created.</p>";
}

// Handle permission update
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_permissions'])) {
    $adminId = $_POST['admin_id'];
    $pdo->prepare("DELETE FROM admin_permissions WHERE admin_id = ?")->execute([$adminId]);

    foreach ($_POST['modules'] as $mod => $perm) {
        $stmt = $pdo->prepare("INSERT INTO admin_permissions (admin_id, module_name, can_view, can_edit)
                               VALUES (?, ?, ?, ?)");
        $stmt->execute([
            $adminId,
            $mod,
            isset($perm['view']) ? 1 : 0,
            isset($perm['edit']) ? 1 : 0
        ]);
    }
    echo "<p class='success'>✅ Permissions updated.</p>";
}

// Fetch admins
$stmt = $pdo->query("SELECT * FROM admin_users ORDER BY role, username");
$admins = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Module list (keys match admin_permissions.module_name)
$modules = [
    'dashboard' => 'admin_dashboard.php',
    'postbacks' => 'admin_postback_logs.php',
    'modules' => 'admin_module_tracker.php',
    'notes' => 'admin_affiliate_notes.php',
    'files' => 'admin_offer_files.php',
    'tracking' => 'admin_offer_tracking.php',
    'tests' => 'admin_affiliate_tests.php',
    'terms' => 'admin_offer_terms.php',
    'delivery' => 'admin_postback_failures.php',
    'caps' => 'admin_offer_caps.php',
    'payouts' => 'admin_payout_summary.php',
    'performance' => 'admin_offer_performance.php',
    'contracts' => 'admin_offer_contracts.php',
    'exports' => 'admin_offer_exports.php',
    'insights' => 'admin_offer_insights.php',
    'history' => 'admin_offer_history.php'
];
?>
<!DOCTYPE html>
<html>
<head>
    <title><?php echo SITE_TITLE . ' | Manage Admin Users'; ?></title>
    <link rel="stylesheet" href="css/admin.css">
</head>
<body>
<div class="container">
<h2>⚙️ Manage Admin Users</h2>
<form method="post">
    <label>Username:<br><input name="username" placeholder="Username" required></label><br>
    <label>Password:<br><input name="password" type="password" placeholder="Password" required></label><br>
    <label>Email:<br><input name="email" placeholder="Email"></label><br>
    <label>Role:
        <select name="role">
            <option value="viewer">Viewer</option>
            <option value="editor">Editor</option>
            <option value="manager">Manager</option>
            <option value="superadmin">Superadmin</option>
        </select>
    </label><br>
    <label><input type="checkbox" name="is_active" checked> Active</label><br>
    <button name="create_admin" type="submit">Create Admin</button>
</form>

<hr><h3>🔐 Set Permissions</h3>
<form method="post">
    <label>Admin:
        <select name="admin_id">
            <?php foreach ($admins as $a): ?>
                <option value="<?php echo htmlspecialchars($a['id']); ?>">
                    <?php echo htmlspecialchars($a['username']) . " (" . htmlspecialchars($a['role']) . ")"; ?>
                </option>
            <?php endforeach; ?>
        </select>
    </label><br>

    <?php foreach ($modules as $key => $link): ?>
        <label><?php echo ucwords(str_replace('_', ' ', $key)); ?>
            <input type="checkbox" name="modules[<?php echo htmlspecialchars($key); ?>][view]" value="1"> View
            <input type="checkbox" name="modules[<?php echo htmlspecialchars($key); ?>][edit]" value="1"> Edit
        </label><br>
    <?php endforeach; ?>

    <button name="update_permissions" type="submit">Update Permissions</button>
</form>
</div>
</body>
</html>