<?php

namespace Modules\Inventory\Controllers;

use App\Controllers\BaseController;
use App\Models\WarehouseModel;
use App\Traits\ExportsReport;
use Modules\Inventory\Services\InventoryReportService;

class InventoryReportController extends BaseController
{
    use ExportsReport;

    protected InventoryReportService $reports;

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

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

        if ($export = $this->exportSections(
            'inventory_reports',
            'Inventory Reports',
            [
                [
                    'title'   => 'Low Stock',
                    'headers' => ['Product', 'SKU', 'Warehouse', 'Qty', 'Reorder'],
                    'rows'    => array_map(static fn ($row) => [
                        $row['product_name'] ?? '',
                        $row['sku'] ?? '',
                        $row['warehouse_name'] ?? '',
                        number_format((float) ($row['quantity'] ?? 0), 3),
                        number_format((float) ($row['reorder_level'] ?? 0), 3),
                    ], $report['lowStockRows'] ?? []),
                ],
                [
                    'title'   => 'Recent Adjustments',
                    'headers' => ['Number', 'Product', 'Delta', 'Date'],
                    'rows'    => array_map(static fn ($row) => [
                        $row['number'] ?? '',
                        $row['product_name'] ?? '',
                        number_format((float) ($row['delta'] ?? 0), 3),
                        $row['adjustment_date'] ?? '',
                    ], $report['recentAdjustments'] ?? []),
                ],
            ],
            $filters['date_from'] . ' to ' . $filters['date_to']
        )) {
            return $export;
        }

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