<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With");
header("Content-Type: application/json");

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

include_once __DIR__ . '/config.php';

$data = json_decode(file_get_contents("php://input"), true);
if (!is_array($data)) {
    echo json_encode(["success"=>false,"message"=>"Invalid JSON body"]);
    exit;
}

$userId = isset($data['user_id']) ? intval($data['user_id']) : 0;
$email = isset($data['email']) ? trim($data['email']) : '';
$action = isset($data['action']) ? strtolower(trim($data['action'])) : 'block';

if (!$userId && !$email) {
    echo json_encode(["success"=>false,"message"=>"Provide user_id or email"]);
    exit;
}

if (!in_array($action, ['block','unblock'])) {
    echo json_encode(["success"=>false,"message"=>"Invalid action"]);
    exit;
}

if (!$userId) {
    $stmt = $conn->prepare("SELECT id,email,trading_status,suspend FROM loginusers WHERE email = ? LIMIT 1");
    $stmt->bind_param("s", $email);
    $stmt->execute();
    $res = $stmt->get_result();
    $row = $res->fetch_assoc();
    if (!$row) {
        echo json_encode(["success"=>false,"message"=>"User not found"]);
        exit;
    }
    $userId = intval($row['id']);
    $email = $row['email'];
    $stmt->close();
}

$newStatus = ($action === 'block') ? 1 : 0;

$stmt = $conn->prepare("UPDATE loginusers SET trading_status = ? WHERE id = ?");
$stmt->bind_param("ii", $newStatus, $userId);
$stmt->execute();
$affected = $stmt->affected_rows;
$stmt->close();

echo json_encode([
    "success"=>true,
    "message"=> ($action === 'block' ? 'Withdrawals blocked' : 'Withdrawals unblocked'),
    "user_id"=>$userId,
    "email"=>$email,
    "trading_status"=>$newStatus,
    "rows_affected"=>$affected
]);
?>
