<?php

declare(strict_types=1);

namespace App\Controllers;

use App\Core\Controller;
use App\Core\Request;
use App\Services\ReportService;

class AdminReportController extends Controller
{
    private ReportService $reports;

    public function __construct()
    {
        $this->reports = new ReportService();
    }

    public function index(Request $request): string
    {
        require_role('admin');

        $filters = $this->filters($request);
        $report = $this->reports->overview($filters);

        return $this->view('admin/reports/index', [
            'title' => 'Relatorios',
            'report' => $report,
            'filters' => $report['filters'],
        ]);
    }

    public function export(Request $request): void
    {
        require_role('admin');

        $rows = $this->reports->exportRows($this->filters($request));
        $filename = 'relatorio-mozcursos-' . date('Ymd-His') . '.csv';

        header('Content-Type: text/csv; charset=UTF-8');
        header('Content-Disposition: attachment; filename="' . $filename . '"');
        header('Pragma: no-cache');
        header('Expires: 0');

        echo "\xEF\xBB\xBF";
        $output = fopen('php://output', 'w');

        foreach ($rows as $row) {
            fputcsv($output, $row, ';');
        }

        fclose($output);
        exit;
    }

    private function filters(Request $request): array
    {
        return [
            'date_from' => (string) $request->input('date_from', ''),
            'date_to' => (string) $request->input('date_to', ''),
            'status' => (string) $request->input('status', ''),
            'search' => (string) $request->input('search', ''),
        ];
    }
}
