<?php

namespace Modules\Procurement\Controllers;

use App\Controllers\BaseController;
use App\Models\SupplierModel;
use App\Traits\ExportsReport;
use Modules\Procurement\Services\ProcurementReportService;

class ProcurementReportController extends BaseController
{
    use ExportsReport;

    protected ProcurementReportService $reports;
    protected SupplierModel $suppliers;

    public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);
        $this->reports   = new ProcurementReportService();
        $this->suppliers = new SupplierModel();
    }

    public function index()
    {
        $filters = $this->reports->resolveFilters($this->request->getGet());
        $report  = $this->reports->summary($filters);

        if ($export = $this->exportSections(
            'procurement_reports',
            'Procurement Reports',
            [
                [
                    'title'   => 'PO Status',
                    'headers' => ['Status', 'Count'],
                    'rows'    => array_map(static fn ($row) => [
                        ucwords(str_replace('_', ' ', (string) ($row['status'] ?? ''))),
                        (int) ($row['total'] ?? 0),
                    ], $report['poStatusMix']['rows'] ?? []),
                ],
                [
                    'title'   => 'Vendor Bill Status',
                    'headers' => ['Status', 'Count'],
                    'rows'    => array_map(static fn ($row) => [
                        ucwords(str_replace('_', ' ', (string) ($row['status'] ?? ''))),
                        (int) ($row['total'] ?? 0),
                    ], $report['billStatusMix']['rows'] ?? []),
                ],
            ],
            $filters['date_from'] . ' to ' . $filters['date_to']
        )) {
            return $export;
        }

        return view('Modules\Procurement\Views\reports\index', array_merge($this->baseViewData(), [
            'title'     => 'Procurement Reports',
            'filters'   => $filters,
            'report'    => $report,
            'suppliers' => $this->suppliers->getActive(),
        ]));
    }
}
