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

use DateInterval;
use DateTimeImmutable;
use Incoviba\Common\Implement\Exception\EmptyRedis;
use Incoviba\Common\Implement\Exception\EmptyResult;
use Incoviba\Controller\API\withJson;
use Incoviba\Controller\withRedis;
use Incoviba\Repository;
use Incoviba\Service;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;

class Cuotas
{
    use withJson, withRedis;
    public function hoy(ServerRequestInterface $request, ResponseInterface $response,
                        Repository\Venta\Cuota $cuotaRepository, Service\Redis $redisService): ResponseInterface
    {
        $today = new DateTimeImmutable();
        $redisKey = "cuotas:hoy:{$today->format('Y-m-d')}";
        $output = [
            'cuotas' => 0
        ];
        try {
            $output['cuotas'] = $this->fetchRedis($redisService, $redisKey);
        } catch (EmptyRedis) {
            try {
                $output['cuotas'] = count($cuotaRepository->fetchHoy());
                $this->saveRedis($redisService, $redisKey, $output['cuotas']);
            } catch (EmptyResult) {}
        }
        return $this->withJson($response, $output);
    }
    public function pendiente(ServerRequestInterface $request, ResponseInterface $response,
                              Repository\Venta\Cuota $cuotaRepository, Service\Redis $redisService): ResponseInterface
    {
        $today = new DateTimeImmutable();
        $redisKey = "cuotas:pendientes:{$today->format('Y-m-d')}";
        $output = [
            'cuotas' => 0
        ];
        try {
            $output['cuotas'] = $this->fetchRedis($redisService, $redisKey);
        } catch (EmptyRedis) {
            try {
                $output['cuotas'] = count($cuotaRepository->fetchPendientes());
                $this->saveRedis($redisService, $redisKey, $output['cuotas']);
            } catch (EmptyResult) {}
        }
        return $this->withJson($response, $output);
    }
    public function porVencer(ServerRequestInterface $request, ResponseInterface $response,
                              Repository\Venta\Cuota $cuotaRepository, Service\Redis $redisService,
                              Service\Format $formatService): ResponseInterface
    {
        $today = new DateTimeImmutable();
        $redisKey = "cuotas:por_vencer:{$today->format('Y-m-d')}";
        try {
            $output = $this->fetchRedis($redisService, $redisKey);
        } catch (EmptyRedis) {
            $output = [];
            try {
                $cuotas = $cuotaRepository->fetchDatosPorVencer();
                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;
                }
                $this->saveRedis($redisService, $redisKey, $output);
            } catch (EmptyResult) {}
        }
        return $this->withJson($response, ['cuotas' => $output]);
    }
}
