<?php
/**
 * /api/admin/exchange_rate.php
 * GET:  سجل سعر الصرف
 * POST: تحديث سعر الصرف (admin only)
 */
require_once __DIR__ . '/../../config.php';
require_once __DIR__ . '/../../engine/Kernel.php';
Kernel::handle(['auth' => 'admin', 'public' => false]);
require_once __DIR__ . '/../engine/Logger.php'; // COVERAGE
require_once '../../engine/PricingEngine.php';

// session_start() removed — Kernel::handle manages sessions

if (empty($_SESSION['admin'])) {
    http_response_code(403);
    die(json_encode(['error' => 'unauthorized']));
}

$adminId = (int)($_SESSION['admin']['id'] ?? 0);
$method  = $_SERVER['REQUEST_METHOD'];

if ($method === 'GET') {
    $history = PricingEngine::getHistory(50);
    $current = PricingEngine::getRate();
    echo json_encode([
        'current_rate' => $current,
        'history'      => $history,
        'preview'      => [
            'plus_sdg'     => PricingEngine::toSDG(5.00),
            'pro_sdg'      => PricingEngine::toSDG(12.20),
            'starter_sdg'  => PricingEngine::toSDG(defined('CORP_STARTER_USD') ? CORP_STARTER_USD : 99),
            'business_sdg' => PricingEngine::toSDG(defined('CORP_BUSINESS_USD') ? CORP_BUSINESS_USD : 249),
        ],
    ], JSON_UNESCAPED_UNICODE);

} elseif ($method === 'POST') {
    $b       = json_decode(file_get_contents('php://input'), true) ?? [];
    $newRate = (float)($b['rate'] ?? 0);
    $note    = mb_substr(trim($b['note'] ?? ''), 0, 200);

    if ($newRate < 100 || $newRate > 100000) {
        http_response_code(400);
        die(json_encode(['error' => 'invalid_rate', 'message' => 'السعر يجب أن يكون بين 100 و 100,000']));
    }

    $result = PricingEngine::updateRate($newRate, $adminId, $note);

    // Log in audit
    try {
        db()->prepare("INSERT INTO audit_logs (user_id, action, details) VALUES (?,?,?)")
           ->execute([$adminId, 'exchange_rate_update', json_encode($result)]);
    } catch (Throwable $ignored) {}

    echo json_encode($result, JSON_UNESCAPED_UNICODE);
} else {
    http_response_code(405);
    echo json_encode(['error' => 'method_not_allowed']);
}
