<?php
namespace Incoviba\Controller\API\Ventas;

use DateTimeImmutable;
use DateInterval;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Incoviba\Repository;
use Incoviba\Service;

class Cuotas
{
    public function hoy(ServerRequestInterface $request, ResponseInterface $response, Repository\Venta\Cuota $cuotaRepository): ResponseInterface
    {
        $output = [
            'cuotas' => count($cuotaRepository->fetchHoy()) ?? 0
        ];
        $response->getBody()->write(json_encode($output));
        return $response->withHeader('Content-Type', 'application/json');
    }
    public function pendiente(ServerRequestInterface $request, ResponseInterface $response, Repository\Venta\Cuota $cuotaRepository): ResponseInterface
    {
        $output = [
            'cuotas' => count($cuotaRepository->fetchPendientes()) ?? 0
        ];
        $response->getBody()->write(json_encode($output));
        return $response->withHeader('Content-Type', 'application/json');
    }
    public function porVencer(ServerRequestInterface $request, ResponseInterface $response, Repository\Venta\Cuota $cuotaRepository, Service\Format $formatService): ResponseInterface
    {
        $cuotas = $cuotaRepository->fetchDatosPorVencer();
        $output = [];
        foreach ($cuotas as $row) {
            $fecha = $row['Fecha'];
            $date = new DateTimeImmutable($fecha);
            if (($weekday = $date->format('N')) > 5) {
                $day_diff = 7 - $weekday + 1;
                $date = $date->add(new DateInterval("P{$day_diff}D"));
                $fecha = $date->format('Y-m-d');
            }
            $key = $formatService->localDate($fecha, "EEE. dd 'de' MMMM 'de' yyyy", true);
            if (!isset($output[$key])) {
                $output[$key] = [];
            }
            if (!isset($output[$key][$row['Proyecto']])) {
                $output[$key][$row['Proyecto']] = 0;
            }
            $output[$key][$row['Proyecto']] += $row['Cantidad'];
        }
        foreach ($output as $key => $day) {
            uksort($day, function($a, $b) {
                return strcmp($a, $b);
            });
            $output[$key] = $day;
        }
        $response->getBody()->write(json_encode(['cuotas' => $output]));
        return $response->withHeader('Content-Type', 'application/json');
    }
}
