<?php
ob_start(); // buffer output to prevent early JSON corruption
header('Content-Type: application/json; charset=utf-8');
session_start();

try {

    // Try to use SubAdminPageGuard only when helper is available. Otherwise
    // fall back to simple admin-only session check to avoid fatal errors
    // during FTP sync when helper files may be missing.
    if (file_exists(__DIR__ . '/helpers/subadmin_page_guard.php')) {
        require_once __DIR__ . '/helpers/subadmin_page_guard.php';
        try {
            $pageGuard = new SubAdminPageGuard('manage_users');
            $pageGuard->enforceAction();
        } catch (Throwable $e) {
            error_log('admin_bulk_change_role.php: SubAdminPageGuard failed: ' . $e->getMessage());
            // fall through to session-based check
        }
    } else {
        // helper missing; ensure only full admins can perform bulk role changes
        if (empty($_SESSION['user_id']) || empty($_SESSION['is_admin'])) {
            http_response_code(403);
            ob_clean();
            echo json_encode(['success' => false, 'message' => 'Access denied']);
            exit;
        }
    }

    // Accept either array or single user_id (for compatibility)
    $ids = $_POST['user_ids'] ?? null; // array
    $singleId = isset($_POST['user_id']) ? (int)$_POST['user_id'] : 0;
    $role = $_POST['role'] ?? '';
    if (!$ids && $singleId) $ids = [$singleId];
    if (!is_array($ids) || empty($role)) { 
        http_response_code(400);
        ob_clean();
        echo json_encode(['success'=>false,'message'=>'Invalid request']); 
        exit; 
    }

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

    $protectedEmail = 'maham11abc@gmail.com';

    foreach ($ids as $uid) {
    $uid = (int)$uid; if (!$uid) continue;
    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',$uid); $stmt->execute(); $r=$stmt->get_result(); $row=$r? $r->fetch_assoc():null; $stmt->close(); }
        $email = $row['email'] ?? null;
        if ($email === $protectedEmail) continue;

        if ($role === 'Administrator') {
            $ins = @$conn->prepare('INSERT INTO admins (user_id, role_name) VALUES (?, ?)');
            if ($ins) { $roleName = 'admin'; $ins->bind_param('is',$uid,$roleName); $ins->execute(); $ins->close(); }
            continue;
        }

        if ($role === 'Editor' || $role === 'Sub-admin') {
            // Allow custom permissions to be passed via POST when assigning
            // Editor/Sub-admin. Expect either an array in $_POST['permissions']
            // (permissions[manage_posts]=..., etc) or fall back to sensible defaults.
            $permissions = [];
            if (!empty($_POST['permissions']) && is_array($_POST['permissions'])) {
                $permissions = $_POST['permissions'];
            } else {
                if ($role === 'Editor') {
                    $permissions = [
                        'manage_posts' => 'editor',
                        'manage_pages' => 'editor',
                        'manage_users' => 'none'
                    ];
                }
            }
            $permJson = json_encode($permissions);
            // Determine target table based on role
            $targetTable = ($role === 'Editor') ? 'editors' : 'subadmins';
            // First remove from both tables to avoid duplicates
            @$conn->query("DELETE FROM editors WHERE user_id = $uid");
            @$conn->query("DELETE FROM subadmins WHERE user_id = $uid");
            // Insert into correct table, editor, and subadmin
        $d1 = @$conn->prepare('DELETE FROM admins WHERE user_id = ?'); if ($d1) { $d1->bind_param('i',$uid); $d1->execute(); $d1->close(); }
        $d2 = @$conn->prepare('DELETE FROM editors WHERE user_id = ?'); if ($d2) { $d2->bind_param('i',$uid); $d2->execute(); $d2->close(); }
        $d3 = @$conn->prepare('DELETE FROM subadmins WHERE user_id = ?'); if ($d3) { $d3->bind_param('i',$uid); $d3->execute(); $d3
            continue;
        }

        // For Subscriber/User: remove admin and subadmin
        $d1 = @$conn->prepare('DELETE FROM admins WHERE user_id = ?'); if ($d1) { $d1->bind_param('i',$uid); $d1->execute(); $d1->close(); }
        $d2 = @$conn->prepare('DELETE FROM subadmins WHERE user_id = ?'); if ($d2) { $d2->bind_param('i',$uid); $d2->execute(); $d2->close(); }
        continue;
    }

    // JSON fallback
    $usersFile = __DIR__ . '/data/users.json';
    if (file_exists($usersFile)) {
        $users = json_decode(file_get_contents($usersFile), true); if (!is_array($users)) $users = [];
        foreach ($users as $u) if (isset($u['id']) && $u['id']==$uid && ($u['email'] ?? '') === $protectedEmail) { continue 2; }
    }

    if ($role === 'Administrator') {
        $adminFile = __DIR__ . '/data/admins.json'; $a = file_exists($adminFile) ? json_decode(file_get_contents($adminFile), true) : [];
        if (!is_array($a)) $a = [];
        if (!in_array($uid, $a)) $a[] = $uid; file_put_contents($adminFile, json_encode($a, JSON_PRETTY_PRINT)); continue;
    }
    if ($role === 'Editor' || $role === 'Sub-admin') {
        // Determine target JSON file based on role
        $targetFile = ($role === 'Editor') ? __DIR__ . '/data/editors.json' : __DIR__ . '/data/subadmins.json';
        $s = file_exists($targetFile) ? json_decode(file_get_contents($targetFile), true) : [];
        if (!is_array($s)) $s = [];
        // Also remove from the other file to avoid duplicates
        $otherFile = ($role === 'Editor') ? __DIR__ . '/data/subadmins.json' : __DIR__ . '/data/editors.json';
        if (file_exists($otherFile)) {
            $other = json_decode(file_get_contents($otherFile), true);
            if (is_array($other)) {
                $other = array_filter($other, function($x) use ($uid) { return !isset($x['user_id']) || $x['user_id'] != $uid; });
                file_put_contents($otherFile, json_encode(array_values($other), JSON_PRETTY_PRINT));
            }
        }
        $found = false; foreach ($s as $i=> $row) { if (isset($row['user_id']) && $row['user_id']==$uid) { $found=true; break; } }
        if (!$found) {
            $permissions = [];
            if (!empty($_POST['permissions']) && is_array($_POST['permissions'])) $permissions = $_POST['permissions'];
            else if ($role === 'Editor') $permissions = ['manage_posts' => 'editor','manage_pages' => 'editor','manage_users' => 'none'];
            $s[] = ['user_id'=>$uid,'permissions'=>$permissions];
        } else {
            // update existing entry with provided permissions when present
            if (!empty($_POST['permissions']) && is_array($_POST['permissions'])) {
                $s[$i]['permissions'] = $_POST['permissions'];
            }
        }
        file_put_contents($targetFile, json_encode($s, JSON_PRETTY_PRINT)); continue;
    }
    // Subscriber: remove
    $adminFile = __DIR__ . '/data/admins.json'; if (file_exists($adminFile)) { $a=json_decode(file_get_contents($adminFile), true); if (is_array($a)) { $a=array_values(array_diff($a, [$uid])); file_put_contents($adminFile, json_encode($a, JSON_PRETTY_PRINT)); } }
    $sf = __DIR__ . '/data/subadmins.json'; if (file_exists($sf)) { $s=json_decode(file_get_contents($sf), true); if (is_array($s)) { $s=array_values(array_filter($s, function($x) use ($uid){ return !isset($x['user_id']) || $x['user_id'] != $uid; })); file_put_contents($sf, json_encode($s, JSON_PRETTY_PRINT)); } }
}

    ob_clean();
    echo json_encode(['success'=>true]); 
    exit;
} catch (Throwable $e) {
    ob_clean();
    error_log('admin_bulk_change_role.php: ' . $e->getMessage());
    http_response_code(500);
    echo json_encode(['success'=>false,'message'=>'Server error: '.$e->getMessage()]);
    exit;
}
?>
