<?php
namespace Incoviba\Common\Controller;

use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response;
use \Model;
use Incoviba\Common\Define\Controller\Json;
use Incoviba\Operador;
use Incoviba\TipoAgente;

class Operadores {
  use Json;

  public function __invoke(Request $request, Response $response): Response {
    $tipo = Model::factory(TipoAgente::class)->where('descripcion', 'operador')->find_one();
    $ids = array_map(function($item) {
      return $item->agente;
    }, $tipo->agente_tipos());
    $operadores = [];
    foreach ($ids as $id) {
      $operadores []= Model::factory(Operador::class)->find_one($id);
    }
    usort($operadores, function($a, $b) {
      return strcmp($a->abreviacion, $b->abreviacion);
    });
    array_walk($operadores, function(&$item) {
      $item = $item->as_array();
    });
    $output = compact('operadores');
    return $this->withJson($response, $output);
  }
  public function show(Request $request, Response $response, $id_operador): Response {
    $operador = Model::factory(Operador::class)->find_one($id_operador);
    $output = ['operador' => null];
    if ($operador) {
      $output = ['operador' => $operador->as_array()];
    }
    return $this->withJson($response, $output);
  }
  public function add(Request $request, Response $response): Response {
    $post = $request->getParsedBody();
    $output = Operador::add($post);
    return $this->withJson($response, $output);
  }
  public function ventas(Request $request, Response $response, $id_operador): Response {
    $operador = Model::factory(Operador::class)->find_one($id_operador);
    $output = [
      'operador' => $operador->as_array(),
      'ventas' => array_map(function($item) {
        return $item->as_array();
      }, $operador->ventas())
    ];
    return $this->withJson($response, $output);
  }
  public function add_proyecto(Request $request, Response $response, $id_operador): Response {
    $operador = Model::factory(Operador::class)->find_one($id_operador);
    $post = $request->getParsedBody();
    $output = $operador->addProyecto($post);
    return $this->withJson($response, $output);
  }
}
