<?php

namespace Modules\Accounting\Controllers;

use App\Controllers\BaseController;
use App\Traits\ExportsReport;
use Modules\Accounting\Services\TaxReportService;

class TaxReportController extends BaseController
{
    use ExportsReport;

    protected TaxReportService $service;

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

    public function index()
    {
        $from = trim((string) $this->request->getGet('from')) ?: date('Y-m-01');
        $to   = trim((string) $this->request->getGet('to')) ?: date('Y-m-d');

        if (strtotime($to) < strtotime($from)) {
            $to = $from;
        }

        $summary = $this->service->summary($from, $to);

        $sections = [[
            'title'   => 'Summary by Document Type',
            'headers' => ['Document Type', 'Direction', 'Documents', 'Tax Total'],
            'rows'    => array_map(static fn ($block) => [
                $block['label'] ?? '',
                $block['direction'] ?? '',
                (int) ($block['count'] ?? 0),
                number_format((float) ($block['tax_total'] ?? 0), 2),
            ], $summary['breakdown'] ?? []),
        ]];

        foreach ($summary['breakdown'] ?? [] as $block) {
            if ((int) ($block['count'] ?? 0) === 0) {
                continue;
            }
            $sections[] = [
                'title'   => $block['label'] ?? 'Documents',
                'headers' => ['Number', 'Date', 'Party', 'Status', 'Tax', 'Total'],
                'rows'    => array_map(static fn ($row) => [
                    $row['number'] ?? '',
                    $row['doc_date'] ?? '',
                    $row['party_name'] ?? '',
                    $row['status'] ?? '',
                    number_format((float) ($row['tax_amount'] ?? 0), 2),
                    number_format((float) ($row['total'] ?? 0), 2),
                ], $block['rows'] ?? []),
            ];
        }

        if ($export = $this->exportSections(
            'tax_reports',
            'Tax Reports',
            $sections,
            $from . ' to ' . $to . ' | Net VAT ' . number_format((float) ($summary['net'] ?? 0), 2)
        )) {
            return $export;
        }

        return view('Modules\Accounting\Views\tax_reports\index', array_merge($this->baseViewData(), [
            'title'   => 'Tax Reports',
            'filters' => compact('from', 'to'),
            'summary' => $summary,
        ]));
    }
}
