<?php
namespace App\Controllers;

use App\Core\Controller;
use App\Models\Dashboard;

class DashboardController extends Controller
{
    public function index()
    {
        $this->requireAuth();

        $dashboardModel = new Dashboard();

        // Quick stats
        $totalClients = (new \App\Models\Client())->getAll();
        $totalClientBalance = $dashboardModel->getTotalClientBalance();
        $todayForexVolume = $dashboardModel->getTodayForexVolume();
        $monthlyRentCollected = $dashboardModel->getMonthlyRentCollected();

        // Chart data
        $balanceTrend = $dashboardModel->getClientBalanceTrend(7);
        $forexPositions = $dashboardModel->getForexPositions();
        $rentMonthly = $dashboardModel->getRentCollectionMonthly(6);

        // Prepare JSON for Chart.js
        $balanceDates = array_column($balanceTrend, 'date');
        $balanceValues = array_column($balanceTrend, 'total');

        $forexLabels = array_column($forexPositions, 'code');
        $forexValues = []; // need KES equivalent using current rate - simplified for now
        // In a real app, fetch rates from API to compute KES equivalent.
        // For demo, we'll multiply closing_balance by a dummy rate or average_cost.
        foreach ($forexPositions as $pos) {
            $forexValues[] = round($pos['closing_balance'] * $pos['average_cost'], 2);
        }

        $rentLabels = array_column($rentMonthly, 'month');
        $rentValues = array_column($rentMonthly, 'total');

        $this->render('dashboard/index', compact(
            'totalClients', 'totalClientBalance', 'todayForexVolume', 'monthlyRentCollected',
            'balanceDates', 'balanceValues',
            'forexLabels', 'forexValues',
            'rentLabels', 'rentValues'
        ));
    }
}