<?php

namespace App\Controllers\Api\V1;

use App\Controllers\BaseController;
use App\Services\Reporting\AgencyReportingService;
use App\Services\Reporting\ReportExportService;

class AgencyReportController extends BaseController
{
    private AgencyReportingService $reporting;

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

    public function recruiterPerformance()
    {
        $user = $this->currentUser();
        return $this->maybeExport($this->reporting->recruiterPerformance($user->agency_id), 'recruiter-performance', 'Recruiter Performance');
    }

    public function candidateViews()
    {
        $user = $this->currentUser();
        [$from, $to] = $this->dateRange();
        return $this->maybeExport($this->reporting->candidateViews($user->agency_id, $from, $to), 'candidate-views', 'Candidate Views');
    }

    public function contactReveals()
    {
        $user = $this->currentUser();
        [$from, $to] = $this->dateRange();
        return $this->maybeExport($this->reporting->contactReveals($user->agency_id, $from, $to), 'contact-reveals', 'Contact Reveals');
    }

    public function hires()
    {
        $user = $this->currentUser();
        [$from, $to] = $this->dateRange();
        return $this->maybeExport($this->reporting->hires($user->agency_id, $from, $to), 'hires', 'Hires');
    }

    public function interviews()
    {
        $user = $this->currentUser();
        [$from, $to] = $this->dateRange();
        return $this->maybeExport($this->reporting->interviews($user->agency_id, $from, $to), 'interviews', 'Interviews');
    }

    public function conversionRates()
    {
        $user = $this->currentUser();
        $jobId = $this->request->getGet('job_id') ? (int) $this->request->getGet('job_id') : null;
        return $this->jsonSuccess($this->reporting->conversionRates($user->agency_id, $jobId));
    }

    private function dateRange(): array
    {
        $from = $this->request->getGet('from') ?? date('Y-m-d', strtotime('-30 days'));
        $to = $this->request->getGet('to') ?? date('Y-m-d');
        return [$from, $to];
    }

    private function maybeExport(array $data, string $filenameBase, string $title)
    {
        $format = $this->request->getGet('export');
        if (! $format) {
            return $this->jsonSuccess($data);
        }

        $exporter = new ReportExportService();
        try {
            $path = match ($format) {
                'pdf'   => $exporter->toPdf($data, $filenameBase, $title),
                'excel' => $exporter->toExcel($data, $filenameBase, $title),
                'csv'   => $exporter->toCsv($data, $filenameBase),
                default => null,
            };
        } catch (\RuntimeException $e) {
            return $this->jsonError([['code' => 'EXPORT_UNAVAILABLE', 'message' => $e->getMessage()]], 501);
        }

        if (! $path) {
            return $this->jsonError([['code' => 'INVALID_EXPORT_FORMAT', 'message' => 'export must be pdf, excel, or csv.']], 400);
        }

        return $this->response->download($path, null);
    }
}
