<?php
class CustomerStatementController extends Controller
{
    public function indexAction()
    {
        $asAt   = (string)($_GET['as_at'] ?? date('Y-m-d'));
        $filter = (string)($_GET['filter'] ?? '');
        $m      = new CustomerStatement();
        $rows   = $m->overviewAllCustomers($asAt);
        if ($filter === 'outstanding') {
            $rows = array_values(array_filter($rows, fn($r) => (float)$r['total_outstanding'] > 0.01));
        }
        // Portfolio totals
        $tot = ['invoiced' => 0, 'paid' => 0, 'outstanding' => 0, 'current' => 0, '1_30' => 0, '31_60' => 0, '61_90' => 0, '90_plus' => 0];
        foreach ($rows as $r) {
            $tot['invoiced']    += (float)$r['total_invoiced'];
            $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('CustomerStatement/index', [
            'page_title' => 'Customer Statements · AR Ageing',
            'rows'       => $rows,
            'as_at'      => $asAt,
            'filter'     => $filter,
            'totals'     => $tot,
        ]);
    }

    public function viewAction($customer_id = 0)
    {
        $cid = (int)$customer_id;
        if ($cid <= 0) {
            $this->view->setLayout($this->roleLayout());
            $this->view->render('generals/fb_page', ['fb_msg' => '<div class="alert alert-danger">customer_id required.</div>']);
            return;
        }
        $asAt = (string)($_GET['as_at'] ?? date('Y-m-d'));
        $m    = new CustomerStatement();
        $data = $m->forCustomer($cid, $asAt);
        if (empty($data)) {
            $this->view->setLayout($this->roleLayout());
            $this->view->render('generals/fb_page', ['fb_msg' => '<div class="alert alert-danger">Customer not found.</div>']);
            return;
        }
        $this->view->setLayout($this->roleLayout());
        $this->view->render('CustomerStatement/view', array_merge(
            ['page_title' => 'Statement · ' . trim(($data['customer']['fname'] ?? '') . ' ' . ($data['customer']['lname'] ?? ''))],
            $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 CustomerStatement())->overviewAllCustomers($asAt);
        if ($filter === 'outstanding') $rows = array_values(array_filter($rows, fn($r) => (float)$r['total_outstanding'] > 0.01));

        $data = []; $tot = ['inv' => 0, 'paid' => 0, 'out' => 0, 'c' => 0, 'b1' => 0, 'b2' => 0, 'b3' => 0, 'b4' => 0];
        foreach ($rows as $r) {
            $name = trim(($r['fname'] ?? '') . ' ' . ($r['lname'] ?? ''));
            $data[] = [$name, (float)$r['total_invoiced'], (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['inv']  += (float)$r['total_invoiced'];  $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' => 'Customer',   'width' => 34, 'align' => 'L'],
            ['label' => 'Invoiced',   '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['inv'], $tot['paid'], $tot['out'], $tot['c'], $tot['b1'], $tot['b2'], $tot['b3'], $tot['b4']]]];
        $title = 'Customer Statements · AR Ageing';
        $sub   = 'As at ' . $asAt . ($filter === 'outstanding' ? '  ·  Outstanding only' : '');
        $fname = 'customer_ar_ageing_' . $asAt;
        if ($format === 'xlsx') {
            ExportHelper::xlsxDownload($fname . '.xlsx', 'AR Ageing', $columns, $data, $totals, ['title' => $title, 'subtitle' => $sub]);
        } else {
            ExportHelper::pdfDownload($fname . '.pdf', $title, $sub, $columns, $data, $totals, 'L');
        }
    }
}
