<?php namespace App\Controllers\Configuracion;


use App\Controllers\BaseResourceController;

use App\Models\Collection;

use App\Models\Configuracion\MaquinasCallesModel;
use App\Entities\Configuracion\MaquinasCallesEntity;

use
    DataTables\Editor,
    DataTables\Editor\Field;


class Maquinascalles extends \App\Controllers\BaseResourceController
{
    protected static $controllerSlug = 'maquinascalles';

    protected $modelName = MaquinasCallesModel::class;
    protected $format = 'json';

    protected static $singularObjectName = 'Maquina calle';
    protected static $singularObjectNameCc = 'maquinaCalle';
    protected static $pluralObjectName = 'Maquinas calles';
    protected static $pluralObjectNameCc = 'maquinasCalles';

    public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
    {
        $this->viewData['pageTitle'] = lang('MaquinasCalles.moduleTitle');
        $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

        parent::initController($request, $response, $logger);
    }


    

    public function datatable_editor()
    {
        if ($this->request->isAJAX()) {

            include(APPPATH . "ThirdParty/DatatablesEditor/DataTables.php");

            // Build our Editor instance and process the data coming from _POST
            $response = Editor::inst($db, 'maquinas_calles')
                ->fields(
                    Field::inst('formas')
                        ->validator('Validate::numeric', array(
                                'message' => lang('MaquinasCalles.validation.formas.integer'))
                        )
                        ->validator('Validate::notEmpty', array(
                                'message' => lang('MaquinasCalles.validation.formas.required'))
                        ),
                    Field::inst('internas')
                        ->getFormatter( 'Format::toDecimalChar')->setFormatter( 'Format::fromDecimalChar')
                        ->validator('Validate::numeric', array(
                                "decimal" => ',',
                                'message' => lang('MaquinasCalles.validation.internas.decimal'))
                        )
                        ->validator('Validate::notEmpty', array(
                                'message' => lang('MaquinasCalles.validation.internas.required'))
                        ),
                    Field::inst('externas')
                        ->getFormatter( 'Format::toDecimalChar')->setFormatter( 'Format::fromDecimalChar')
                        ->validator('Validate::numeric', array(
                                "decimal" => ',',   
                                'message' => lang('MaquinasCalles.validation.externas.decimal'))
                        )
                        ->validator('Validate::notEmpty', array(
                                'message' => lang('MaquinasCalles.validation.externas.required'))
                        ),
                    Field::inst('maquina_id'),
                    Field::inst('user_created_id'),
                    Field::inst('created_at'),
                    Field::inst('user_updated_id'),
                    Field::inst('updated_at'),
                    Field::inst('is_deleted'),
                    Field::inst('deleted_at'),

                )
                ->validator(function ($editor, $action, $data) {
                    if ($action === Editor::ACTION_CREATE || $action === Editor::ACTION_EDIT) {
                        foreach ($data['data'] as $pkey => $values) {
                            // Si no se quiere borrar...
                            if ($data['data'][$pkey]['is_deleted'] != 1) {
                                $process_data['formas'] = $data['data'][$pkey]['formas'];
                                $process_data['maquina_id'] = $data['data'][$pkey]['maquina_id'];
                                $response = $this->model->checkDuplicatedFormas($process_data, $pkey);
                                // No se pueden duplicar valores al crear o al editar
                                if (!empty($response)) {
                                    return $response;
                                }
                            }
                        }
                    }
                })
                ->on('preCreate', function ($editor, &$values) {
                    $session = session();
                    $datetime = (new \CodeIgniter\I18n\Time("now"));
                    $editor
                        ->field('user_created_id')
                        ->setValue($session->id_user);
                    $editor
                        ->field('created_at')
                        ->setValue($datetime->format('Y-m-d H:i:s'));
                })
                ->on('preEdit', function ($editor, &$values) {
                    $session = session();
                    $datetime = (new \CodeIgniter\I18n\Time("now"));
                    $editor
                        ->field('user_updated_id')
                        ->setValue($session->id_user);
                    $editor
                        ->field('updated_at')
                        ->setValue($datetime->format('Y-m-d H:i:s'));
                })
                ->debug(true)
                ->process($_POST)
                ->data();

            $newTokenHash = csrf_hash();
            $csrfTokenName = csrf_token();

            $response[$csrfTokenName] = $newTokenHash;

            echo json_encode($response);

        } else {
            return $this->failUnauthorized('Invalid request', 403);
        }
    }

    public function datatable()
    {
        if ($this->request->isAJAX()) {

            $reqData = $this->request->getPost();
            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;
            }
            $start = $reqData['start'] ?? 0;
            $length = $reqData['length'] ?? 5;
            $search = $reqData['search']['value'];
            $requestedOrder = $reqData['order']['0']['column'] ?? 0;
            $order = MaquinasCallesModel::SORTABLE[$requestedOrder >= 0 ? $requestedOrder : 0];
            $dir = $reqData['order']['0']['dir'] ?? 'asc';

            $id_M = $reqData['maquina_id'] ?? -1;

            $resourceData = $this->model->getResource("", $id_M)->orderBy($order, $dir)->limit($length, $start)->get()->getResultObject();

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


    public function menuItems()
    {
        if ($this->request->isAJAX()) {

            $provTipoModel = new ProveedorTipoModel();
            $provModel = new ProveedorModel();

            $tipoId = $provTipoModel->getTipoId("Encuadernacion");
            $provList = $provModel->getProvList($tipoId);

            $newTokenHash = csrf_hash();
            $csrfTokenName = csrf_token();

            $data = [
                'data' => $provList,
                $csrfTokenName => $newTokenHash
            ];
            return $this->respond($data);
        } else {
            return $this->failUnauthorized('Invalid request', 403);
        }
    }
    
}

