<?php
// Toggle admin status (promote/demote)
header('Content-Type: application/json; charset=utf-8');
session_start();

if (empty($_SESSION['user_id']) || empty($_SESSION['is_admin'])) {
    http_response_code(403);
    echo json_encode(['success' => false, 'message' => 'Access denied']);
    exit;
}

$userId = isset($_POST['user_id']) ? (int)$_POST['user_id'] : 0;
$action = $_POST['action'] ?? '';
if (!$userId || !in_array($action, ['promote','demote'])) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Invalid request']);
    exit;
}

$protectedEmail = 'maham11abc@gmail.com';

// Load DB if available
$dbPath = __DIR__ . '/db_config.php';
if (file_exists($dbPath)) require $dbPath;

// Helper to write JSON admins fallback
function jsonLoadAdmins() {
    $f = __DIR__ . '/data/admins.json';
    if (!file_exists($f)) return [];
    $c = @file_get_contents($f);
    $j = @json_decode($c, true);
    return is_array($j) ? $j : [];
}
function jsonSaveAdmins($arr) {
    $f = __DIR__ . '/data'; if (!is_dir($f)) @mkdir($f,0755,true);
    file_put_contents(__DIR__ . '/data/admins.json', json_encode($arr, JSON_PRETTY_PRINT));
}

// Attempt DB path
if (isset($conn) && $conn) {
    // get email to protect
    $stmt = @$conn->prepare('SELECT email FROM users WHERE id = ? LIMIT 1');
    if ($stmt) {
        $stmt->bind_param('i', $userId);
        $stmt->execute();
        $r = $stmt->get_result();
        $row = $r ? $r->fetch_assoc() : null;
        $email = $row['email'] ?? null;
        $stmt->close();
    } else $email = null;

    if ($email === $protectedEmail) {
        echo json_encode(['success' => false, 'message' => 'Cannot change primary admin']); exit;
    }

    if ($action === 'promote') {
        $ins = @$conn->prepare('INSERT INTO admins (user_id, role_name) VALUES (?, ?)');
        if ($ins) {
            $role = 'admin'; $ins->bind_param('is', $userId, $role); $ok = $ins->execute(); $ins->close();
            if ($ok) { echo json_encode(['success'=>true]); exit; }
        }
    } else {
        $del = @$conn->prepare('DELETE FROM admins WHERE user_id = ?');
        if ($del) { $del->bind_param('i', $userId); $del->execute(); $del->close(); echo json_encode(['success'=>true]); exit; }
    }
    // DB fallback to JSON if something failed
}

// JSON fallback
$admins = jsonLoadAdmins();
if ($action === 'promote') {
    if (!in_array($userId, $admins)) $admins[] = $userId;
    jsonSaveAdmins($admins);
    echo json_encode(['success'=>true]); exit;
} else {
    $admins = array_values(array_diff($admins, [$userId]));
    jsonSaveAdmins($admins);
    echo json_encode(['success'=>true]); exit;
}

?>
