<?php
require_once __DIR__ . '/../app/bootstrap.php';

use App\Core\Auth;
use App\Core\Response;
use App\Core\Security;
use App\Core\WalletService;

Auth::requireLogin('public/login.php');
if ($_SERVER['REQUEST_METHOD'] !== 'POST' || !verify_csrf()) {
    Response::json(['ok' => false, 'message' => 'Invalid request.'], 419);
}
if (!Security::rateLimit('wallet-transfer:' . Auth::id(), 20, 3600)) {
    Response::json(['ok' => false, 'message' => 'Too many wallet transfers. Try again later.'], 429);
}

$data = request_data();
$amount = round((float)($data['amount'] ?? 0), 2);
$from = strtolower((string)($data['from'] ?? 'cash'));
$to = strtolower((string)($data['to'] ?? 'purchase'));
if (!is_finite($amount) || $amount <= 0 || $amount > 999999999.99) {
    Response::json(['ok' => false, 'message' => 'Enter a valid amount.'], 422);
}

try {
    $ok = WalletService::transfer((int)Auth::id(), $from, $to, $amount);
    if ($ok) {
        Security::logActivity(Auth::id(), 'wallet_transferred', ['from' => $from, 'to' => $to, 'amount' => $amount]);
    }
    Response::json([
        'ok' => $ok,
        'message' => $ok ? 'Wallet transfer completed.' : 'Transfer is not allowed.',
        'balances' => [
            'cash' => WalletService::balance((int)Auth::id(), 'cash'),
            'purchase' => WalletService::balance((int)Auth::id(), 'purchase'),
        ],
    ], $ok ? 200 : 422);
} catch (Throwable $exception) {
    error_log('Wallet transfer failed: ' . $exception->getMessage());
    Response::json(['ok' => false, 'message' => $exception instanceof RuntimeException ? $exception->getMessage() : 'Wallet transfer failed.'], 422);
}
