<?php

namespace App\Controllers;

use CodeIgniter\Exceptions\PageNotFoundException;
use CodeIgniter\HTTP\ResponseInterface;
use Dompdf\Dompdf;
use Dompdf\Options;

class ReportsController extends BaseController
{
    public function index(): string
    {
        $data = service('reports')->getIndexData($this->request->getGet(), auth()->user());

        return view('reports/index', $data);
    }

    public function export(string $format): ResponseInterface
    {
        if (! in_array($format, ['csv', 'pdf'], true)) {
            throw PageNotFoundException::forPageNotFound();
        }

        $export = service('reports')->getExportData($this->request->getGet(), auth()->user());

        if ($format === 'csv') {
            return $this->response
                ->setHeader('Content-Type', 'text/csv; charset=UTF-8')
                ->setHeader('Content-Disposition', 'attachment; filename="' . $export['file_basename'] . '.csv"')
                ->setBody(service('reports')->buildCsv($export));
        }

        $options = new Options([
            'defaultFont' => 'DejaVu Sans',
            'isRemoteEnabled' => false,
            'isHtml5ParserEnabled' => true,
        ]);
        $dompdf = new Dompdf($options);
        $dompdf->setPaper('A4', count($export['report']['columns'] ?? []) > 4 ? 'landscape' : 'portrait');
        $dompdf->loadHtml(view('reports/pdf', $export), 'UTF-8');
        $dompdf->render();

        return $this->response
            ->setHeader('Content-Type', 'application/pdf')
            ->setHeader('Content-Disposition', 'attachment; filename="' . $export['file_basename'] . '.pdf"')
            ->setBody($dompdf->output());
    }
}
