<?php
namespace App\Controllers;

use App\Core\Acl;
use App\Core\Controller;
use App\Core\Dates;
use App\Core\Request;
use App\Services\AgingService;
use App\Services\DashboardService;
use App\Services\ExportService;

/** Laporan aging piutang dengan bucket konfigurabel. */
class AgingController extends Controller
{
    protected string $module = 'aging';

    private function ctx(): array
    {
        $asOf = Request::date('tanggal_lapor') ?: Dates::today();
        $filters = PiutangController::readFilters(false);
        [$s, $sp] = Acl::invoiceScopeSql('i');
        $filters['_scope_sql'] = $s;
        $filters['_scope_params'] = $sp;
        $groupBy = (string)Request::get('grup', 'customer');
        if (!isset(AgingService::groupOptions()[$groupBy])) $groupBy = 'customer';
        $configId = Request::int('konfigurasi', 0) ?: null;
        return [$asOf, $filters, $groupBy, $configId];
    }

    public function index(): void
    {
        [$asOf, $filters, $groupBy, $configId] = $this->ctx();
        $rep = AgingService::report($filters, $groupBy, $asOf, $configId);

        $this->view('aging/index', [
            'judul'    => 'Aging Piutang',
            'subjudul' => 'Konfigurasi "' . $rep['config']['name'] . '" · per ' . Dates::fmtLong($asOf),
            'rep' => $rep, 'asOf' => $asOf, 'groupBy' => $groupBy,
            'configId' => (int)$rep['config']['id'],
            'configs' => AgingService::allConfigs(),
            'groupOptions' => AgingService::groupOptions(),
            'filters' => PiutangController::readFilters(false),
            'opsi' => DashboardService::filterOptions(),
        ]);
    }

    /** Daftar invoice pada satu bucket (drill-down). */
    public function detail(): void
    {
        [$asOf, $filters, $groupBy, $configId] = $this->ctx();
        $bucket = Request::int('bucket', -1);
        $cfg = AgingService::config($configId);
        $rows = $bucket >= 0 ? AgingService::invoicesInBucket($bucket, $filters, $asOf, $configId, 2000) : [];

        $this->view('aging/detail', [
            'judul' => 'Detail Aging — ' . ($cfg['buckets'][$bucket]['label'] ?? 'Semua Bucket'),
            'subjudul' => 'Konfigurasi "' . $cfg['name'] . '" · per ' . Dates::fmtLong($asOf),
            'rows' => $rows, 'cfg' => $cfg, 'bucket' => $bucket, 'asOf' => $asOf,
            'filters' => PiutangController::readFilters(false),
        ]);
    }

    public function export(): void
    {
        [$asOf, $filters, $groupBy, $configId] = $this->ctx();
        $rep = AgingService::report($filters, $groupBy, $asOf, $configId);
        $label = AgingService::groupOptions()[$groupBy] ?? 'Kelompok';

        $columns = [
            ['label' => $label,          'key' => 'grup_label',     'type' => 'text', 'width' => 34, 'pdf_width' => 2.4],
            ['label' => 'Jumlah Invoice','key' => 'jumlah_invoice', 'type' => 'int'],
        ];
        foreach ($rep['buckets'] as $i => $b) {
            $columns[] = ['label' => $b['label'], 'key' => 'b' . $i, 'type' => 'money'];
        }
        $columns[] = ['label' => 'Total Saldo', 'key' => 'total_nilai', 'type' => 'money'];
        $columns[] = ['label' => 'Rata Umur (hari)', 'key' => 'rata_hari', 'type' => 'dec'];

        $total = ['grup_label' => 'TOTAL', 'jumlah_invoice' => $rep['total']['jumlah_invoice'], 'total_nilai' => $rep['total']['total_nilai']];
        foreach ($rep['buckets'] as $i => $b) $total['b' . $i] = $rep['total']['b' . $i];

        ExportService::send((string)Request::get('format', 'xlsx'), [
            'judul' => 'LAPORAN AGING PIUTANG',
            'subjudul' => 'Konfigurasi: ' . $rep['config']['name'] . ' · Basis: '
                . ['outstanding' => 'Saldo Piutang', 'net' => 'Nilai Bersih', 'gross' => 'Nominal Bruto'][$rep['config']['basis']]
                . ' · Dikelompokkan per ' . $label,
            'tanggal_lapor' => Dates::fmt($asOf),
            'filter' => PiutangController::filterLabels(PiutangController::readFilters(false)),
            'nama_berkas' => 'aging_piutang',
            'sheet' => 'Aging Piutang',
            'orientasi' => 'landscape',
        ], $columns, $rep['rows'], $total);
    }
}
