<?php
namespace ProVM\KI\Common\Controller\Web;

use Psr\Container\ContainerInterface as Container;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response;
use Slim\Views\Blade as View;
use ProVM\Common\Factory\Model as ModelFactory;
use ProVM\KI\Producto;

class Productos {
  public function __invoke(Request $request, Response $response, Container $container, View $view): Response {
    $filename = implode(DIRECTORY_SEPARATOR, [
      $container->get('folders.data'),
      'segmentos.json'
    ]);
    $segmentos = json_decode(trim(file_get_contents($filename)));
    return $view->render($response, 'productos.list', compact('segmentos'));
  }
  public function show(Request $request, Response $response, View $view, ModelFactory $factory, $producto): Response {
    $producto = $factory->find(Producto::class)->where([['id', $producto]])->one();
    return $view->render($response, 'productos.show', compact('producto'));
  }
  public function segmento(Request $request, Response $response, ModelFactory $factory, $segmento): Response {
    $productos = $factory->find(Producto::class);
    if ($segmento != 'todo') {
      $productos = $productos->where([['segmento', ucwords($segmento)]]);
    }
    $productos = $productos->many();
    $output = [
      'information' => [
        'segmento' => $segmento
      ],
      'productos' => array_map(function($item) {
        return $item->id;
      }, $productos)
    ];
    $response->getBody()->write(json_encode($output));
    return $response
      ->withHeader('Content-Type', 'application/json')
      ->withStatus(201);
  }
  public function destacados(Request $request, Response $response, Container $container, $page): Response {
    $filename = implode(DIRECTORY_SEPARATOR, [
      $container->get('folders.data'),
      'destacados.json'
    ]);
    $destacados = json_decode(trim(file_get_contents($filename)));
    $max = ceil(count($destacados) / 4);
    $output = [
      'information' => [
        'page' => $page
      ],
      'destacados' => []
    ];
    $n = min(4, count($destacados));
    for ($i = ($page - 1) * $n; $i < $page * $n; $i ++) {
      $output['destacados'] []= $destacados[$i];
    }
    $response->getBody()->write(json_encode($output));
    return $response
      ->withHeader('Content-Type', 'application/json')
      ->withStatus(201);
  }
  public function ficha(Request $request, Response $response, View $view, ModelFactory $factory, $producto): Response {
    $producto = $factory->find(Producto::class)->where([['id', $producto]])->one();
    return $view->render($response, 'productos.ficha', compact('producto'));
  }
}
