<?php
/**
 * ============================================================
 * ADMIN AJAX: Block/Unblock User
 * ============================================================
 */

// Initialize
define('BASE_PATH', dirname(dirname(dirname(__DIR__))));
require_once BASE_PATH . '/app/config/config.php';

// Start session
if (session_status() === PHP_SESSION_NONE) {
    session_name(SESSION_NAME);
    session_start();
}

// Must be POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Content-Type: application/json');
    echo json_encode(['success' => false, 'message' => 'Invalid request']);
    exit;
}

// Must be admin
if (!isAdminLoggedIn()) {
    header('Content-Type: application/json');
    echo json_encode(['success' => false, 'message' => 'অ্যাডমিন লগইন প্রয়োজন']);
    exit;
}

// Get data
$userId = (int)post('user_id');
$action = sanitize(post('action')); // 'block' or 'unblock'

if ($userId < 1) {
    Response::error('অবৈধ ইউজার');
}

if (!in_array($action, ['block', 'unblock'])) {
    Response::error('অবৈধ অ্যাকশন');
}

// Check user exists
$user = Database::fetchOne("SELECT id, full_name FROM users WHERE id = ?", [$userId]);
if (!$user) {
    Response::notFound('ইউজার পাওয়া যায়নি');
}

// Update block status
$isBlocked = $action === 'block' ? 1 : 0;
Database::execute(
    "UPDATE users SET is_blocked = ? WHERE id = ?",
    [$isBlocked, $userId]
);

$message = $action === 'block' 
    ? $user['full_name'] . ' কে ব্লক করা হয়েছে' 
    : $user['full_name'] . ' কে আনব্লক করা হয়েছে';

Response::success($message, [
    'user_id' => $userId,
    'is_blocked' => $isBlocked
]);
