<?php

declare(strict_types=1);

namespace App\Controllers;

use App\Repositories\ReporteRepository;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;

class ReporteController
{
    private ReporteRepository $reportes;

    public function __construct(ReporteRepository $reportes)
    {
        $this->reportes = $reportes;
    }

    public function resumen(Request $request, Response $response): Response
    {
        return $this->json($response, $this->reportes->resumenGeneral());
    }

    public function ventas(Request $request, Response $response): Response
    {
        [$desde, $hasta] = $this->rango($request);

        return $this->json($response, $this->reportes->ventasPorRango($desde, $hasta));
    }

    public function comisiones(Request $request, Response $response): Response
    {
        [$desde, $hasta] = $this->rango($request);
        $porcentaje = (float) ($request->getQueryParams()['porcentaje'] ?? 0.20);

        return $this->json($response, $this->reportes->comisionesPorRepartidor($desde, $hasta, $porcentaje));
    }

    private function rango(Request $request): array
    {
        $params = $request->getQueryParams();
        $desde = $params['desde'] ?? date('Y-m-d', strtotime('-30 days'));
        $hasta = $params['hasta'] ?? date('Y-m-d');

        return [$desde . ' 00:00:00', $hasta . ' 23:59:59'];
    }

    private function json(Response $response, $data, int $status = 200): Response
    {
        $response->getBody()->write(json_encode($data));

        return $response->withHeader('Content-Type', 'application/json')->withStatus($status);
    }
}
