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

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

class Cartolas extends Controller
{
    use withJson;

    public function procesar(ServerRequestInterface        $request, ResponseInterface $response,
                             Repository\Inmobiliaria       $inmobiliariaRepository,
                             Repository\Contabilidad\Banco $bancoRepository,
                             Service\Contabilidad\Cartola  $cartolaService): ResponseInterface
    {
        $body = $request->getParsedBody();
        $output = [
            'input' => $body,
            'movimientos' => []
        ];
        try {
            $inmobiliaria = $inmobiliariaRepository->fetchById($body['inmobiliaria']);
            $banco = $bancoRepository->fetchById($body['banco']);
            $mes = new DateTimeImmutable($body['mes']);
            $file = $request->getUploadedFiles()['file'];
            $output['movimientos'] = $cartolaService->process($banco, $file);
        } catch (EmptyResult) {}
        return $this->withJson($response, $output);
    }
    public function exportar(ServerRequestInterface        $request, ResponseInterface $response,
                             Repository\Inmobiliaria       $inmobiliariaRepository,
                             Repository\Contabilidad\Banco $bancoRepository,
                             Service\Contabilidad\Cartola  $cartolaService): ResponseInterface
    {
        $body = $request->getParsedBody();
        $output = [
            'input' => $body,
            'filename' => ''
        ];
        try {
            $inmobiliaria = $inmobiliariaRepository->fetchById($body['inmobiliaria']);
            $banco = $bancoRepository->fetchById($body['banco']);
            $mes = new DateTimeImmutable($body['mes']);
            $output['filename'] = $cartolaService->export($inmobiliaria, $banco, $mes, json_decode($body['movimientos']));
        } catch (EmptyResult) {}
        return $this->withJson($response, $output);
    }
    public function diaria(ServerRequestInterface         $request, ResponseInterface $response,
                           Repository\Inmobiliaria\Cuenta $cuentaRepository,
                           Service\Contabilidad\Cartola   $cartolaService): ResponseInterface
    {
        $body = $request->getParsedBody();
        $output = [
            'input' => $body,
            'cartolas' => []
        ];
        $fields = json_decode($body['fields']);
        foreach ($fields as $field) {
            try {
                $cuenta = $cuentaRepository->fetchById($body["cuenta_id{$field}"]);
                $fecha = new DateTimeImmutable($body["fecha{$field}"]);
                if (array_key_exists("manual{$field}", $body)) {
                    $file = json_decode($body["file{$field}"], JSON_OBJECT_AS_ARRAY);
                    $output['cartolas'][$field] = $cartolaService->diariaManual($cuenta, $fecha, $file);
                    continue;
                }
                $file = $request->getUploadedFiles()["file{$field}"];

                $output['cartolas'][$field] = $cartolaService->diaria($cuenta, $fecha, $file);
            } catch (EmptyResult $exception) {
                $this->logger->debug($exception);
            }
        }
        return $this->withJson($response, $output);
    }
    public function ayer(ServerRequestInterface          $request, ResponseInterface $response,
                         Repository\Inmobiliaria\Cuenta  $cuentaRepository,
                         Repository\Contabilidad\Cartola $cartolaRepository): ResponseInterface
    {
        $body = $request->getParsedBody();
        $output = [
            'input' => $body,
            'cartola' => []
        ];
        try {
            $cuenta = $cuentaRepository->fetchById($body['cuenta_id']);
            $fecha = new DateTimeImmutable($body['fecha']);
            $output['cartola'] = $cartolaRepository->fetchByCuentaAndFecha($cuenta->id, $fecha);
        } catch (EmptyResult) {}
        return $this->withJson($response, $output);
    }
    public function importar(ServerRequestInterface        $request, ResponseInterface $response,
                             Service\Contabilidad\Cartola  $cartolaService): ResponseInterface
    {
        $body = $request->getParsedBody();
        $files = $request->getUploadedFiles();

        $output = [
            'input' => $body,
            'movimientos' => [],
            'errors' => []
        ];

        $errors = [
            UPLOAD_ERR_OK => 'Ok',
            UPLOAD_ERR_INI_SIZE => 'El archivo excede el tamaño máximo permitido',
            UPLOAD_ERR_FORM_SIZE => 'El archivo excede el tamaño máximo permitido',
            UPLOAD_ERR_PARTIAL => 'El archivo fue subido parcialmente',
            UPLOAD_ERR_NO_FILE => 'No se subió ningún archivo',
            UPLOAD_ERR_NO_TMP_DIR => 'Falta la carpeta temporal',
            UPLOAD_ERR_CANT_WRITE => 'No se pudo escribir el archivo',
            UPLOAD_ERR_EXTENSION => 'Una extensión de PHP detuvo la subida del archivo'
        ];
        if (is_array($files['file'])) {
            foreach ($files['file'] as $i => $file) {
                if ($file->getError() !== UPLOAD_ERR_OK) {
                    $output['errors'] []= ['filename' => $file->getClientFilename(), 'error' => $errors[$file->getError()]];
                    continue;
                }
                try {
                    $output['movimientos'] = array_merge($output['movimientos'], $cartolaService->import($body['cuenta_id'][$i], $file));
                } catch (EmptyResult) {}
            }
        } else {
            $file = $files['file'];
            if ($file->getError() !== UPLOAD_ERR_OK) {
                $output['errors'][] = ['filename' => $file->getClientFilename(), 'error' => $errors[$file->getError()]];
            } else {
                try {
                    $output['movimientos'] = $cartolaService->import($body['cuenta_id'], $file);
                } catch (EmptyResult) {}
            }
        }
        return $this->withJson($response, $output);
    }
    public function update(ServerRequestInterface         $request, ResponseInterface $response,
                           Service\Contabilidad\Cartola $cartolaService): ResponseInterface
    {
        $output = [
            'cartolas' => []
        ];
        try {
            $cuentas = $cartolaService->check();
            if (count($cuentas) > 0) {
                $output['cartolas'] = $cartolaService->update($cuentas);
            }
        } catch (EmptyResult) {}
        return $this->withJson($response, $output);
    }
}
