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

// Helper functions outside try block
function jsonLoadSubadmins() {
    $f = __DIR__ . '/data/subadmins.json';
    if (!file_exists($f)) return [];
    $c = @file_get_contents($f);
    $j = @json_decode($c, true);
    return is_array($j) ? $j : [];
}
function jsonSaveSubadmins($arr) {
    $d = __DIR__ . '/data'; if (!is_dir($d)) @mkdir($d,0755,true);
    file_put_contents(__DIR__ . '/data/subadmins.json', json_encode($arr, JSON_PRETTY_PRINT));
}

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

    $userId = isset($_POST['user_id']) ? (int)$_POST['user_id'] : 0;
    $role = $_POST['role'] ?? 'subadmin'; // default to subadmin if not specified
    $permissions = isset($_POST['permissions']) ? $_POST['permissions'] : null;
    if (!$userId) { 
        http_response_code(400);
        ob_clean();
        echo json_encode(['success'=>false,'message'=>'Invalid user']); 
        exit; 
    }

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

    // Determine which table to use based on role
    $targetTable = ($role === 'editor') ? 'editors' : 'subadmins';

    // Try DB if available
    if (isset($conn) && $conn && !$conn->connect_error) {
        // ensure users table exists; then insert into appropriate table
        $check = @$conn->prepare('SELECT id FROM users WHERE id = ? LIMIT 1');
        if ($check) { 
            $check->bind_param('i',$userId); 
            $check->execute(); 
            $r=$check->get_result(); 
            $found = ($r && $r->num_rows>0); 
            $check->close(); 
        }
        else $found = false;
        if (!$found) { 
            ob_clean();
            echo json_encode(['success'=>false,'message'=>'User not found']); 
            exit;
        }

        // First remove from both tables to avoid duplicates
        @$conn->query("DELETE FROM editors WHERE user_id = $userId");
        @$conn->query("DELETE FROM subadmins WHERE user_id = $userId");

        // upsert into correct table
        $permJson = $permissions ? json_encode($permissions) : '{}';
        $sql = 'REPLACE INTO ' . $targetTable . ' (user_id, permissions) VALUES (?, ?)';
        $stmt = @$conn->prepare($sql);
        if ($stmt) { 
            $stmt->bind_param('is',$userId,$permJson); 
            $stmt->execute(); 
            $stmt->close();
            ob_clean();
            echo json_encode(['success'=>true]); 
            exit; 
        }
    }

    // JSON fallback - save to appropriate JSON file
    if ($role === 'editor') {
        $editorsFile = __DIR__ . '/data/editors.json';
        $editors = file_exists($editorsFile) ? json_decode(file_get_contents($editorsFile), true) : [];
        if (!is_array($editors)) $editors = [];
        $found = false;
        foreach ($editors as $i => $ed) {
            if (isset($ed['user_id']) && $ed['user_id'] == $userId) {
                $editors[$i]['permissions'] = $permissions ?: [];
                $found = true;
                break;
            }
        }
        if (!$found) $editors[] = ['user_id'=>$userId,'permissions'=>$permissions?:[]];
        @mkdir(__DIR__ . '/data', 0755, true);
        file_put_contents($editorsFile, json_encode($editors, JSON_PRETTY_PRINT));
    } else {
        $subs = jsonLoadSubadmins();
        $found = false;
        for ($i=0;$i<count($subs);$i++) {
            if (isset($subs[$i]['user_id']) && $subs[$i]['user_id']==$userId) { 
                $subs[$i]['permissions'] = $permissions ?: []; 
                $found = true; 
                break; 
            }
        }
        if (!$found) $subs[] = ['user_id'=>$userId,'permissions'=>$permissions?:[]];
        jsonSaveSubadmins($subs);
    }
    ob_clean();
    echo json_encode(['success'=>true]); 
    exit;
} catch (Throwable $e) {
    ob_clean();
    error_log('admin_promote_subadmin.php: ' . $e->getMessage());
    http_response_code(500);
    echo json_encode(['success'=>false,'message'=>'Server error: '.$e->getMessage()]);
    exit;
}
?>
