<?php

namespace App\Controllers\Presupuestos;

use App\Controllers\BaseResourceController;
use App\Entities\Configuracion\Maquina;
use App\Models\Collection;

use App\Entities\Presupuestos\PresupuestoEntity;
use App\Models\Presupuestos\BuscadorModel;
use App\Models\Presupuestos\PresupuestoDireccionesModel;
use App\Models\Configuracion\PapelGenericoModel;
use App\Models\Configuracion\TipoPresupuestoModel;
use App\Models\Presupuestos\PresupuestoModel;


use App\Services\PresupuestoService;
use App\Models\Configuracion\PapelImpresionModel;
use App\Models\Configuracion\MaquinaModel;
use Exception;

class Buscador extends \App\Controllers\BaseResourceController
{

    protected $modelName = "BuscadorModel";
    protected $format = 'json';

    protected static $singularObjectName = 'Buscador';
    protected static $singularObjectNameCc = 'buscador';
    protected static $pluralObjectName = 'Buscadores';
    protected static $pluralObjectNameCc = 'buscadores';

    protected static $controllerSlug = 'buscador';

    protected static $viewPath = 'themes/vuexy/form/presupuestos/buscador/';

    protected $indexRoute = 'buscadorPresupuestosList';


    public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
    {

        $this->viewData['usingSweetAlert'] = true;

        // Se indica que este controlador trabaja con soft_delete
        $this->soft_delete = true;
        // Se indica el flag para los ficheros borrados
        $this->delete_flag = 1;

        $this->viewData = ['usingServerSideDataTable' => true]; // JJO

        // Breadcrumbs (IMN)
        $this->viewData['breadcrumb'] = [
            ['title' => lang("App.menu_presupuestos"), 'route' => "javascript:void(0);", 'active' => false],
            ['title' => lang("App.menu_presupuesto_buscador"), 'route' => route_to("buscadorPresupuestosList"), 'active' => true]
        ];

        parent::initController($request, $response, $logger);
        $this->model = new BuscadorModel();
    }


    public function index()
    {
        checkPermission('presupuesto.menu');

        $viewData = [
            'currentModule' => static::$controllerSlug,
            'pageSubTitle' => lang('Basic.global.ManageAllRecords', [lang('Presupuestos.presupuesto')]),
            'presupuestoEntity' => new PresupuestoEntity(),
            'usingServerSideDataTable' => true
        ];

        $viewData = array_merge($this->viewData, $viewData); // merge any possible values from the parent controller class

        return view(static::$viewPath . 'viewBuscadorList', $viewData);
    }


    public function datatable()
    {
        if ($this->request->isAJAX()) {
            $reqData = $this->request->getPost();

            $type = $reqData['type'] ?? null;

            if (is_null($type)) {
                if (!isset($reqData['draw']) || !isset($reqData['columns'])) {
                    $errstr = 'No data available in response to this specific request.';
                    $response = $this->respond(Collection::datatable([], 0, 0, $errstr), 400, $errstr);
                    return $response;
                }
                $search = $reqData['search']['value'];
            }
            $start = $reqData['start'] ?? 0;
            $length = $reqData['length'] ?? 5;

            $requestedOrder1 = $reqData['order']['0']['column'] ?? 0;
            $order1 = PresupuestoModel::SORTABLE[$requestedOrder1 >= 0 ? $requestedOrder1 : 0];
            $dir1 = $reqData['order']['0']['dir'] ?? 'asc';
            $requestedOrder2 = $reqData['order']['1']['column'] ?? 0;
            $order2 = PresupuestoModel::SORTABLE[$requestedOrder2 >= 0 ? $requestedOrder2 : 0];
            $dir2 = $reqData['order']['1']['dir'] ?? 'asc';
            $requestedOrder3 = $reqData['order']['2']['column'] ?? 0;
            $order3 = PresupuestoModel::SORTABLE[$requestedOrder3 >= 0 ? $requestedOrder3 : 0];
            $dir3 = $reqData['order']['2']['dir'] ?? 'asc';

            $searchValues = get_filter_datatables_columns($reqData);

            $resourceData = $this->model->getResource($searchValues)->orderBy($order1, $dir1)->orderBy($order2, $dir2)
                ->orderBy($order3, $dir3)->limit($length, $start)->get()->getResultObject();

            return $this->respond(Collection::datatable(
                $resourceData,
                $this->model->getResource("")->countAllResults(),
                $this->model->getResource($searchValues)->countAllResults()
            ));
        } else {
            return $this->failUnauthorized('Invalid request', 403);
        }
    }

}
