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

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;

class Nosotros {
  public function __invoke(Request $request, Response $response, View $view, Container $container) {
    $filename = implode(DIRECTORY_SEPARATOR, [
      $container->get('folders.data'),
      'nosotros.json'
    ]);
    $nosotros = trim(json_decode(trim(file_get_contents($filename))));
    return $view->render($response, 'admin.nosotros', compact('nosotros'));
  }
  public function guardar(Request $request, Response $response, Container $container) {
    $post = $request->getParsedBody();
    $filename = implode(DIRECTORY_SEPARATOR, [
      $container->get('folders.data'),
      'nosotros.json'
    ]);
    $nosotros = trim(json_decode(trim(file_get_contents($filename))));
    $data = trim(json_decode(json_encode($post['nosotros'])));

    $status = false;
    if ($nosotros != $data) {
      $status = (file_put_contents($filename, json_encode($post['nosotros'])) !== false);
    }
    $code = 301;
    if ($status) {
      $code = 302;
    }
    return $response
      ->withHeader('Location', implode('/', [$container->get('urls')->admin, 'nosotros']))
      ->withStatus($code);
  }
}
