<?php
namespace App\Controllers;

use App\Core\Controller;
use App\Models\Currency;
use App\Models\ForexTrade;
use App\Models\CurrencyHolding;
use App\Services\ExchangeRateService;
use App\Core\Model;

class ForexController extends Controller
{
    /**
     * List all forex trades
     */
    public function index()
    {
        $this->requireAuth();
        $tradeModel = new ForexTrade();
        $trades = $tradeModel->getAll();
        $this->render('forex/index', ['trades' => $trades]);
    }

    /**
     * Show form to record a new trade
     */
    public function createForm()
    {
        $this->requireAuth();
        $currencyModel = new Currency();
        $currencies = $currencyModel->getAll();
        $this->render('forex/create', ['currencies' => $currencies]);
    }

    /**
     * Store a new trade
     */
    public function store()
    {
        $this->requireAuth();
        $trade = new ForexTrade();
        $data = [
            'trade_date' => date('Y-m-d H:i:s'),
            'currency_id' => $_POST['currency_id'],
            'trade_type' => $_POST['trade_type'],
            'amount' => $_POST['amount'],
            'rate' => $_POST['rate'],
            'counterparty' => $_POST['counterparty'] ?? null,
            'notes' => $_POST['notes'] ?? null,
            'recorded_by' => $_SESSION['user_id']
        ];
        $trade->create($data);
        $_SESSION['success'] = 'Forex trade recorded successfully.';
        $this->redirect('/forex/trades');
    }

    /**
     * Display profit/loss report with realised and unrealised P&L using live rates
     */
    public function profitLoss()
    {
        $this->requireAuth();
        $tradeModel = new ForexTrade();
        $holdingModel = new CurrencyHolding();
        $rateService = new ExchangeRateService();

        // Realised profit for selected period (default this month)
        $fromDate = $_GET['from'] ?? date('Y-m-01');
        $toDate = $_GET['to'] ?? date('Y-m-t');
        $realised = $tradeModel->getRealisedProfit(null, $fromDate, $toDate);

        // Get current positions
        $positions = $holdingModel->getCurrentPositions();
        $unrealisedTotal = 0;
        $unrealisedByCurrency = [];

        // Fetch live rates efficiently
        $baseCurrency = 'USD'; // API works well with USD as base
        $allRates = $rateService->getAllRates($baseCurrency);
        $usdToKes = $allRates['KES'] ?? $rateService->getRate('USD', 'KES') ?? 130;

        foreach ($positions as $pos) {
            $currencyCode = $pos['code'];
            $balance = $pos['closing_balance'];
            $avgCost = $pos['average_cost'];

            // Skip zero balances
            if ($balance <= 0) {
                continue;
            }

            // Calculate current market rate in KES per unit
            $currentRate = null;
            if ($currencyCode === 'KES') {
                $currentRate = 1;
            } elseif ($currencyCode === 'USD') {
                $currentRate = $usdToKes;
            } else {
                // For other currencies, convert via USD
                $usdToCurrency = $allRates[$currencyCode] ?? $rateService->getRate('USD', $currencyCode);
                if ($usdToCurrency && $usdToKes) {
                    $currentRate = $usdToKes / $usdToCurrency;
                }
            }

            if ($currentRate !== null) {
                $marketValue = $balance * $currentRate;
                $costValue = $balance * $avgCost;
                $unrealised = $marketValue - $costValue;
                $unrealisedTotal += $unrealised;
                $unrealisedByCurrency[] = [
                    'code' => $currencyCode,
                    'balance' => $balance,
                    'avg_cost' => $avgCost,
                    'current_rate' => $currentRate,
                    'market_value' => $marketValue,
                    'unrealised' => $unrealised
                ];
            }
        }

        // Get last update time of cached rates
        $lastRateUpdate = $this->getLastRateUpdate();

        $this->render('forex/profit_loss', [
            'realised' => $realised,
            'unrealisedTotal' => $unrealisedTotal,
            'unrealisedDetails' => $unrealisedByCurrency,
            'fromDate' => $fromDate,
            'toDate' => $toDate,
            'lastRateUpdate' => $lastRateUpdate
        ]);
    }

    /**
     * Force refresh exchange rates (admin only)
     */
    public function refreshRates()
    {
        $this->requireAuth();
        
        // Optional: restrict to admin only
        if (($_SESSION['user_role'] ?? '') !== 'admin') {
            $_SESSION['error'] = 'You do not have permission to refresh rates.';
            $this->redirect('/forex/profit-loss');
            return;
        }

        $rateService = new ExchangeRateService();
        $rateService->refreshAllRates('USD');
        $_SESSION['success'] = 'Exchange rates refreshed successfully from API.';
        $this->redirect('/forex/profit-loss');
    }

    /**
     * Get the timestamp of the most recent exchange rate update
     */
    private function getLastRateUpdate()
    {
        $pdo = Model::getPDO();
        $stmt = $pdo->query("SELECT MAX(last_updated) FROM exchange_rates");
        return $stmt->fetchColumn();
    }
}