<?php

namespace App\Traits;

use App\Libraries\ReportExporter;
use CodeIgniter\HTTP\ResponseInterface;
use Modules\Tpin\Services\TpinService;

trait ExportsReport
{
    protected function exportFormat(): ?string
    {
        $format = strtolower((string) ($this->request->getGet('export') ?? ''));

        return in_array($format, ['csv', 'pdf', 'word', 'docx'], true) ? $format : null;
    }

    /**
     * Block CSV/PDF/Word generation until TPIN is confirmed (when required for the user).
     */
    protected function guardReportExport(): ?ResponseInterface
    {
        $userId = (int) (session()->get('user_id') ?? 0);
        $result = (new TpinService())->assertConfirmedForAction($userId);
        if ($result['ok']) {
            return null;
        }

        if (! empty($result['redirect'])) {
            return redirect()->to($result['redirect'])->with('error', $result['error'] ?? '');
        }

        return redirect()->back()->with('error', $result['error'] ?? 'TPIN confirmation is required for this action.');
    }

    /**
     * @param list<string>                         $headers
     * @param list<list<string|int|float|null>>    $rows
     */
    protected function exportTable(
        string $filename,
        string $title,
        array $headers,
        array $rows,
        ?string $subtitle = null
    ): ?ResponseInterface {
        $format = $this->exportFormat();
        if ($format === null) {
            return null;
        }

        if ($denied = $this->guardReportExport()) {
            return $denied;
        }

        return (new ReportExporter())->download($format, $filename, $title, $headers, $rows, $subtitle);
    }

    /**
     * @param list<array{title?: ?string, headers: list<string>, rows: list<list<string|int|float|null>>}> $sections
     */
    protected function exportSections(
        string $filename,
        string $title,
        array $sections,
        ?string $subtitle = null
    ): ?ResponseInterface {
        $format = $this->exportFormat();
        if ($format === null) {
            return null;
        }

        if ($denied = $this->guardReportExport()) {
            return $denied;
        }

        return (new ReportExporter())->downloadSections($format, $filename, $title, $sections, $subtitle);
    }

    /**
     * @param array<string, mixed> $query
     */
    protected function exportQuery(array $query = []): array
    {
        $get = $this->request->getGet() ?? [];
        unset($get['export']);

        return array_merge($get, $query);
    }
}
