<?php namespace App\Controllers\Configuracion;


use App\Models\Collection;

use App\Entities\Configuracion\PapelImpresionMargen;

use App\Models\Configuracion\PapelImpresionMargenModel;

use
    DataTables\Editor,
    DataTables\Database,
    DataTables\Editor\Field,
    DataTables\Editor\Format,
    DataTables\Editor\Mjoin,
    DataTables\Editor\Options,
    DataTables\Editor\Upload,
    DataTables\Editor\Validate,
    DataTables\Editor\ValidateOptions;


class Papelimpresionmargenes extends \App\Controllers\BaseResourceController
{

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

    protected static $singularObjectName = 'Papel Impresion Margen';
    protected static $singularObjectNameCc = 'papelImpresionMargen';
    protected static $pluralObjectName = 'Papel Impresion Margenes';
    protected static $pluralObjectNameCc = 'papelImpresionMargenes';

    protected static $controllerSlug = 'papelimpresionmargenes';

    protected static $viewPath = 'themes/vuexy/form/configuracion/papelesimpresion/';

    protected $indexRoute = 'papelesImpresionList';


    public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
    {
        // 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['usingSweetAlert'] = true;
        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, 'papel_impresion_margenes')
                ->fields(
                    Field::inst('paginas_min')
                        ->getFormatter( 'Format::toDecimalChar')->setFormatter( 'Format::fromDecimalChar')
                        ->validator('Validate::numeric', array(
                                "decimal" => ',',
                                'message' => lang('PapelImpresionMargenesvalidation.paginas_min.decimal'))
                        )
                        ->validator('Validate::notEmpty', array(
                                'message' => lang('PapelImpresionMargenesvalidation.paginas_min.required'))
                        ),
                    Field::inst('paginas_max')
                        ->getFormatter( 'Format::toDecimalChar')->setFormatter( 'Format::fromDecimalChar')
                        ->validator('Validate::numeric', array(
                                "decimal" => ',',
                                'message' => lang('PapelImpresionMargenesvalidation.paginas_max.decimal'))
                        )
                        ->validator('Validate::notEmpty', array(
                                'message' => lang('PapelImpresionMargenesvalidation.paginas_max.required'))
                        ),
                    Field::inst('margen')
                        ->getFormatter( 'Format::toDecimalChar')->setFormatter( 'Format::fromDecimalChar')
                        ->validator('Validate::numeric', array(
                                "decimal" => ',',
                                'message' => lang('PapelImpresionMargenesvalidation.margen.decimal'))
                        )
                        ->validator('Validate::notEmpty', array(
                                'message' => lang('PapelImpresionMargenesvalidation.margen.required'))
                        ),
                    Field::inst('papel_impresion_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['paginas_min'] = $data['data'][$pkey]['paginas_min'];
                                $process_data['paginas_max'] = $data['data'][$pkey]['paginas_max'];
                                $response = $this->model->checkIntervals($process_data, $pkey, $data['data'][$pkey]['papel_impresion_id']);
                                // 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 = PapelImpresionMargenModel::SORTABLE[$requestedOrder >= 0 ? $requestedOrder : 0];
            $dir = $reqData['order']['0']['dir'] ?? 'asc';

            $id_PI = $reqData['id_PI'] ?? -1;

            $resourceData = $this->model->getResource("", $id_PI)->orderBy($order, $dir)->limit($length, $start)->get()->getResultObject();
  
            return $this->respond(Collection::datatable(
                $resourceData,
                $this->model->getResource()->countAllResults(),
                $this->model->getResource("", $id_PI)->countAllResults()
            ));
        } else {
            return $this->failUnauthorized('Invalid request', 403);
        }
    }

}
