<?php
//Developer: core tech web designTechnology
//Whatsapp: +2349162671360
//Telegram: @jeditech

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Use correct config path
$config_path = dirname(__DIR__, 2) . '/include/config.php';
if (file_exists($config_path)) {
    include($config_path);
} else {
    echo json_encode(['status' => '0', 'msg' => 'Configuration file not found']);
    exit();
}

// Verify admin status
$stmt = $pdo->prepare("SELECT is_admin FROM users WHERE id = :user_id");
$stmt->bindParam(':user_id', $_SESSION['user_id'], PDO::PARAM_INT);
$stmt->execute();
$admin = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$admin || $admin['is_admin'] != 1) {
    echo json_encode(['status' => '0', 'msg' => 'Unauthorized access']);
    exit();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $user_id = filter_var($_POST['user_id'], FILTER_VALIDATE_INT);
    
    if (!$user_id) {
        echo json_encode(['status' => '0', 'msg' => 'Invalid user ID']);
        exit();
    }
    
    // Prevent admin from removing their own admin status
    if ($user_id == $_SESSION['user_id']) {
        echo json_encode(['status' => '0', 'msg' => 'You cannot remove your own admin privileges']);
        exit();
    }
    
    try {
        // Check if user exists and get current admin status
        $stmt = $pdo->prepare("SELECT username, is_admin FROM users WHERE id = :user_id");
        $stmt->bindParam(':user_id', $user_id, PDO::PARAM_INT);
        $stmt->execute();
        $user = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$user) {
            echo json_encode(['status' => '0', 'msg' => 'User not found']);
            exit();
        }
        
        if ($user['is_admin'] != 1) {
            echo json_encode(['status' => '0', 'msg' => 'User is not an admin']);
            exit();
        }
        
        // Remove admin privileges
        $stmt = $pdo->prepare("UPDATE users SET is_admin = 0 WHERE id = :user_id");
        $stmt->bindParam(':user_id', $user_id, PDO::PARAM_INT);
        
        if ($stmt->execute()) {
            echo json_encode([
                'status' => '1', 
                'msg' => 'Admin privileges removed from ' . $user['username']
            ]);
        } else {
            echo json_encode(['status' => '0', 'msg' => 'Failed to remove admin privileges']);
        }
        
    } catch (PDOException $e) {
        echo json_encode(['status' => '0', 'msg' => 'Database error: ' . $e->getMessage()]);
    }
} else {
    echo json_encode(['status' => '0', 'msg' => 'Invalid request method']);
}
?>