<?php
class CashflowForecastController extends Controller
{
    public function indexAction()
    {
        $asAt = (string)($_GET['as_at'] ?? date('Y-m-d'));
        $m    = new CashflowForecast();

        $openingCash = $m->currentBankBalance();
        $inflows     = $m->expectedInflowsByBucket($asAt);
        $outflows    = $m->expectedOutflowsByBucket($asAt);
        $inflowLines = $m->inflowLines($asAt);
        $outflowLines= $m->outflowLines($asAt);

        // Per-bucket net + running balance
        $buckets = ['0_30' => '0-30 days', '31_60' => '31-60 days', '61_90' => '61-90 days', '90_plus' => '90+ days'];
        $projection = [];
        $running    = $openingCash;
        foreach ($buckets as $k => $label) {
            $in  = (float)$inflows['bucket_' . $k];
            $out = (float)$outflows['bucket_' . $k];
            $net = $in - $out;
            $running += $net;
            $projection[$k] = [
                'label'      => $label,
                'inflow'     => $in,
                'outflow'    => $out,
                'net'        => $net,
                'running'    => $running,
            ];
        }

        $totalInflow  = (float)$inflows['total_open'];
        $totalOutflow = (float)$outflows['total_open'];
        $closingCash  = $openingCash + $totalInflow - $totalOutflow;

        $this->view->setLayout($this->roleLayout());
        $this->view->render('CashflowForecast/index', [
            'page_title'    => 'Cashflow Forecast',
            'as_at'         => $asAt,
            'opening_cash'  => $openingCash,
            'closing_cash'  => $closingCash,
            'total_inflow'  => $totalInflow,
            'total_outflow' => $totalOutflow,
            'projection'    => $projection,
            'inflow_lines'  => $inflowLines,
            'outflow_lines' => $outflowLines,
        ]);
    }

    public function xlsxAction() { $this->export('xlsx'); }
    public function pdfAction()  { $this->export('pdf'); }

    private function export(string $format): void
    {
        $asAt = (string)($_GET['as_at'] ?? date('Y-m-d'));
        $m    = new CashflowForecast();
        $opening = (float)$m->currentBankBalance();
        $in      = $m->expectedInflowsByBucket($asAt);
        $out     = $m->expectedOutflowsByBucket($asAt);
        $running = $opening;

        $rows = [['Opening', 'today', null, null, null, $opening]];
        $labels = ['0_30' => '0-30 days', '31_60' => '31-60 days', '61_90' => '61-90 days', '90_plus' => '90+ days'];
        foreach ($labels as $k => $lab) {
            $i = (float)$in['bucket_' . $k];
            $o = (float)$out['bucket_' . $k];
            $net = $i - $o;
            $running += $net;
            $rows[] = [$lab, '', $i, $o, $net, $running];
        }
        $totIn  = (float)$in['total_open'];
        $totOut = (float)$out['total_open'];
        $closing = $opening + $totIn - $totOut;
        $rows[] = ['Closing', 'all AR + AP settled', $totIn, $totOut, $totIn - $totOut, $closing];

        $columns = [
            ['label' => 'Period',          'width' => 24, 'align' => 'L'],
            ['label' => 'Note',            'width' => 24, 'align' => 'L'],
            ['label' => 'Inflows',         'width' => 20, 'align' => 'R', 'type' => 'money'],
            ['label' => 'Outflows',        'width' => 20, 'align' => 'R', 'type' => 'money'],
            ['label' => 'Net',             'width' => 20, 'align' => 'R', 'type' => 'money'],
            ['label' => 'Running balance', 'width' => 24, 'align' => 'R', 'type' => 'money'],
        ];
        $title = 'Cashflow Forecast';
        $sub   = 'As at ' . $asAt . '  ·  Projected closing TZS ' . number_format($closing);
        $fname = 'cashflow_forecast_' . $asAt;
        if ($format === 'xlsx') {
            ExportHelper::xlsxDownload($fname . '.xlsx', 'Cashflow Forecast', $columns, $rows, [], ['title' => $title, 'subtitle' => $sub]);
        } else {
            ExportHelper::pdfDownload($fname . '.pdf', $title, $sub, $columns, $rows, [], 'L');
        }
    }
}
