<?php

namespace App\Controladores;

use Core\Controller;
use App\Modelos\DivisasMetodos;
use Core\Librerias\Http;
use Core\Vista;

final class DivisasMetodosControlador extends Controller
{
    private $divisasmetodos;
    private $array_errors = [];

    public function __construct()
    {
        parent::__construct();
        $this->divisasmetodos = new DivisasMetodos();
    }

    public function index()
    {
        if ('GET' === $_SERVER['REQUEST_METHOD'] && isAjax()) {
            return Vista::viewAJAX('divisasmetodos/index');
        }
    }

    public function obtenerDivisasMetodos()
    {
        if ('GET' === $_SERVER['REQUEST_METHOD'] && isAjax()) {
            Http::json_response($this->divisasmetodos->dm());
        }
    }

    public function guardar()
    {
        if ('POST' === $_SERVER['REQUEST_METHOD'] && isAjax()) {

            $md_divid = filter_input(INPUT_POST, 'divisa', FILTER_SANITIZE_NUMBER_INT);
            $md_mpid = filter_input(INPUT_POST, 'metodo', FILTER_SANITIZE_NUMBER_INT);

            if (empty($md_divid))
                $this->array_errors[] = 'La divisa es obligatorio.';
            if (empty($md_mpid))
                $this->array_errors[] = 'El metodo es obligatorio.';

            if (empty($this->array_errors)) {

                if ($this->divisasmetodos->dmexiste($md_divid, $md_mpid)) {
                    $this->array_errors[] = 'La relacion que intenta crear ya existe';
                } else {
                    Http::json_response($this->divisasmetodos->guardar([
                        'md_divid' => $md_divid,
                        'md_mpid' => $md_mpid
                    ], true));
                }
            }

            Http::json_response(['errors' => $this->array_errors]);
        }
    }

    public function eliminar(int $id)
    {
        if ('GET' === $_SERVER['REQUEST_METHOD'] && isAjax()) {

            $id = filter_var($id, FILTER_SANITIZE_NUMBER_INT);

            if ($this->divisasmetodos->existe('md_id', $id)) {
                Http::json_response($this->divisasmetodos->eliminar($id));
            } else {
                Http::json_response(false);
            }
        }
    }
}
