<?php
class SupplierStatementController extends Controller
{
    public function indexAction()
    {
        $asAt   = (string)($_GET['as_at']  ?? date('Y-m-d'));
        $filter = (string)($_GET['filter'] ?? '');
        $m      = new SupplierStatement();
        $rows   = $m->overviewAllVendors($asAt);
        if ($filter === 'outstanding') {
            $rows = array_values(array_filter($rows, fn($r) => (float)$r['total_outstanding'] > 0.01));
        }
        $tot = ['committed' => 0, 'paid' => 0, 'outstanding' => 0, 'current' => 0, '1_30' => 0, '31_60' => 0, '61_90' => 0, '90_plus' => 0];
        foreach ($rows as $r) {
            $tot['committed']   += (float)$r['total_committed'];
            $tot['paid']        += (float)$r['total_paid'];
            $tot['outstanding'] += (float)$r['total_outstanding'];
            $tot['current']     += (float)$r['bucket_current'];
            $tot['1_30']        += (float)$r['bucket_1_30'];
            $tot['31_60']       += (float)$r['bucket_31_60'];
            $tot['61_90']       += (float)$r['bucket_61_90'];
            $tot['90_plus']     += (float)$r['bucket_90_plus'];
        }
        $this->view->setLayout($this->roleLayout());
        $this->view->render('SupplierStatement/index', [
            'page_title' => 'Supplier Statements · AP Ageing',
            'rows'       => $rows,
            'as_at'      => $asAt,
            'filter'     => $filter,
            'totals'     => $tot,
        ]);
    }

    public function viewAction($vendor_id = 0)
    {
        $vid = (int)$vendor_id;
        if ($vid <= 0) {
            $this->view->setLayout($this->roleLayout());
            $this->view->render('generals/fb_page', ['fb_msg' => '<div class="alert alert-danger">vendor_id required.</div>']);
            return;
        }
        $asAt = (string)($_GET['as_at'] ?? date('Y-m-d'));
        $m    = new SupplierStatement();
        $data = $m->forVendor($vid, $asAt);
        if (empty($data)) {
            $this->view->setLayout($this->roleLayout());
            $this->view->render('generals/fb_page', ['fb_msg' => '<div class="alert alert-danger">Vendor not found.</div>']);
            return;
        }
        $this->view->setLayout($this->roleLayout());
        $this->view->render('SupplierStatement/view', array_merge(
            ['page_title' => 'Statement · ' . ($data['vendor']['vendor_name'] ?? '')],
            $data
        ));
    }

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

    private function exportOverview(string $format): void
    {
        $asAt = (string)($_GET['as_at'] ?? date('Y-m-d'));
        $filter = (string)($_GET['filter'] ?? '');
        $rows = (new SupplierStatement())->overviewAllVendors($asAt);
        if ($filter === 'outstanding') $rows = array_values(array_filter($rows, fn($r) => (float)$r['total_outstanding'] > 0.01));

        $data = []; $tot = ['cm' => 0, 'paid' => 0, 'out' => 0, 'c' => 0, 'b1' => 0, 'b2' => 0, 'b3' => 0, 'b4' => 0];
        foreach ($rows as $r) {
            $data[] = [(string)$r['vendor_name'], (float)$r['total_committed'], (float)$r['total_paid'], (float)$r['total_outstanding'],
                       (float)$r['bucket_current'], (float)$r['bucket_1_30'], (float)$r['bucket_31_60'], (float)$r['bucket_61_90'], (float)$r['bucket_90_plus']];
            $tot['cm']   += (float)$r['total_committed'];  $tot['paid'] += (float)$r['total_paid'];
            $tot['out']  += (float)$r['total_outstanding']; $tot['c']  += (float)$r['bucket_current'];
            $tot['b1']   += (float)$r['bucket_1_30'];      $tot['b2']  += (float)$r['bucket_31_60'];
            $tot['b3']   += (float)$r['bucket_61_90'];     $tot['b4']  += (float)$r['bucket_90_plus'];
        }
        $columns = [
            ['label' => 'Supplier',   'width' => 34, 'align' => 'L'],
            ['label' => 'Committed',  'width' => 18, 'align' => 'R', 'type' => 'money'],
            ['label' => 'Paid',       'width' => 18, 'align' => 'R', 'type' => 'money'],
            ['label' => 'Outstanding','width' => 18, 'align' => 'R', 'type' => 'money'],
            ['label' => 'Current',    'width' => 14, 'align' => 'R', 'type' => 'money'],
            ['label' => '1-30',       'width' => 14, 'align' => 'R', 'type' => 'money'],
            ['label' => '31-60',      'width' => 14, 'align' => 'R', 'type' => 'money'],
            ['label' => '61-90',      'width' => 14, 'align' => 'R', 'type' => 'money'],
            ['label' => '90+',        'width' => 14, 'align' => 'R', 'type' => 'money'],
        ];
        $totals = [['label' => 'Totals', 'values' => [null, $tot['cm'], $tot['paid'], $tot['out'], $tot['c'], $tot['b1'], $tot['b2'], $tot['b3'], $tot['b4']]]];
        $title = 'Supplier Statements · AP Ageing';
        $sub   = 'As at ' . $asAt . ($filter === 'outstanding' ? '  ·  Outstanding only' : '');
        $fname = 'supplier_ap_ageing_' . $asAt;
        if ($format === 'xlsx') {
            ExportHelper::xlsxDownload($fname . '.xlsx', 'AP Ageing', $columns, $data, $totals, ['title' => $title, 'subtitle' => $sub]);
        } else {
            ExportHelper::pdfDownload($fname . '.pdf', $title, $sub, $columns, $data, $totals, 'L');
        }
    }
}
