<?php
/**
 * GET /api/wallet/summary.php
 * WAVE E — Full Kernel Replace
 * Wallet balance + recent transactions + cashflow
 */
require_once __DIR__ . '/../../config.php';
require_once __DIR__ . '/../../engine/Kernel.php';
require_once __DIR__ . '/../../engine/CashFlowEngine.php';
require_once __DIR__ . '/../../engine/SmartLimits.php';

$ctx    = Kernel::handle(['auth' => true, 'rate' => 'api']);
$userId = (int)$ctx['user']['id'];
$period = in_array($_GET['period'] ?? '', ['7d','30d','90d']) ? $_GET['period'] : '30d';

try {
    $cashflow = CashFlowEngine::analyze($userId, $period);
    $limits   = SmartLimits::check($userId, 1);

    $txnQ = db()->prepare(
        "SELECT id, type, amount_sdg, description, ref_type, ref_id, created_at, balance_after
         FROM wallet_transactions WHERE user_id=? ORDER BY created_at DESC LIMIT 50"
    );
    $txnQ->execute([$userId]);
    $transactions = $txnQ->fetchAll(PDO::FETCH_ASSOC);

    $resQ = db()->prepare(
        "SELECT COALESCE(SUM(reserved_sdg),0) FROM task_reservations
         WHERE user_id=? AND status IN ('pending','active') AND expires_at>NOW()"
    );
    $resQ->execute([$userId]);
    $reservedSdg = (float)$resQ->fetchColumn();

    Kernel::respond([
        'cashflow'     => $cashflow,
        'limits'       => $limits,
        'transactions' => $transactions,
        'reserved_sdg' => $reservedSdg,
        'generated_at' => date('Y-m-d H:i:s'),
    ]);

} catch (Throwable $e) {
    Logger::error('wallet_summary_failed', ['user_id' => $userId, 'error' => $e->getMessage()]);
    Kernel::fail('summary_failed', 'تعذّر تحميل بيانات المحفظة', 500);
}
