<?php
class OverdueReportController extends Controller
{
    public function index(Request $request): void
    {
        $this->view('reports/overdue', [
            'title' => lang('finance.overdue_invoices'),
            'breadcrumbs' => [
                ['label' => lang('finance.title'), 'url' => '/finance/invoices'],
                ['label' => lang('finance.overdue_invoices')],
            ],
        ]);
    }

    public function datatable(Request $request): void
    {
        $db = $this->db();
        $draw   = (int)$request->get('draw', 1);
        $start  = (int)$request->get('start', 0);
        $length = (int)$request->get('length', 25);

        $total = (int)$db->fetchColumn("SELECT COUNT(*) FROM vw_overdue_invoices");

        $rows = $db->fetchAll(
            "SELECT * FROM vw_overdue_invoices ORDER BY days_overdue DESC LIMIT {$length} OFFSET {$start}"
        );

        $data = [];
        foreach ($rows as $row) {
            $agingBucket = 'current';
            $daysOverdue = (int)$row['days_overdue'];
            if ($daysOverdue > 120)     $agingBucket = '120+';
            elseif ($daysOverdue > 90)  $agingBucket = '91-120';
            elseif ($daysOverdue > 60)  $agingBucket = '61-90';
            elseif ($daysOverdue > 30)  $agingBucket = '31-60';
            else                        $agingBucket = '1-30';

            $data[] = [
                'invoice_number'    => e($row['invoice_number']),
                'member_name'       => e($row['member_name'] ?? '') . '<br><small class="text-muted">' . e($row['membership_number'] ?? '') . '</small>',
                'invoice_type'      => e(ucfirst(str_replace('_', ' ', $row['invoice_type']))),
                'total_amount'      => money($row['total_amount']),
                'balance_due'       => '<strong class="text-danger">' . money($row['balance_due']) . '</strong>',
                'due_date'          => format_date($row['due_date']),
                'days_overdue'      => '<span class="badge bg-danger">' . $daysOverdue . ' ' . lang('finance.days') . '</span>',
                'aging_bucket'      => '<span class="badge bg-dark">' . $agingBucket . '</span>',
                'actions'           => '<a href="/finance/invoices/'.$row['id'].'" class="btn btn-sm btn-outline-primary"><i class="fas fa-eye"></i></a>',
            ];
        }

        $this->json(['draw' => $draw, 'recordsTotal' => $total, 'recordsFiltered' => $total, 'data' => $data]);
    }
}