<?php namespace App\Controllers\Clientes;


use App\Controllers\BaseResourceController;
use App\Models\Collection;

use App\Entities\Clientes\ClientePlantillaPreciosLineasEntity;

use App\Models\Clientes\ClientePlantillaPreciosLineasModel;

use App\Models\Clientes\ClienteContactoModel;
use DataTables\Editor;
use DataTables\Editor\Field;
use DataTables\Editor\Validate;

class Clienteplantillaprecioslineas extends \App\Controllers\BaseResourceController
{

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

    protected static $singularObjectName = 'Cliente plantilla precios lineas';
    protected static $singularObjectNameCc = 'clienteplantillaprecioslineas';
    protected static $pluralObjectName = 'Clientes plantilla precios lineas';
    protected static $pluralObjectNameCc = 'clientesplantillaprecioslineas';

    protected static $controllerSlug = 'clienteplantillaprecioslineas';

    protected static $viewPath = 'themes/vuexy/form/clientes/plantillaprecios/';

    protected $indexRoute = 'clienteplantillapreciosList';


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

        

        if ($this->request->getPost()) :
            
            if ($requestedId == null) :
                return;
            endif;

            $postData = $this->request->getJSON();

            $plantilla_id = $postData->plantilla_id ?? -1;
            
            // Se ha actualizado un registro por lo que no es una plantilla
            if($plantilla_id == -1){
                $this->model->clean_plantilla_id($requestedId);
            }
            else{
                $this->model->copy_from_plantilla($requestedId, $plantilla_id);
            }
            
            $newTokenHash = csrf_hash();
            $csrfTokenName = csrf_token();
            $data = [
                $csrfTokenName => $newTokenHash
            ];
            
            return $this->respond($data);

        endif; // ($requestMethod === 'post')
        
    }


    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;

            $requestedOrder = $reqData['order'] ?? [];
            $searchValues = get_filter_datatables_columns($reqData);

            $plantilla_id = $reqData['plantilla_id'] ?? 0;

            $resourceData = $this->model->getResource($searchValues, $plantilla_id);
            foreach ($requestedOrder as $order) {
                $column = $order['column'] ?? 0;
                $dir = $order['dir'] ?? 'asc';
                $orderColumn = ClientePlantillaPreciosLineasModel::SORTABLE[$column] ?? null;
                if ($orderColumn) {
                    $resourceData->orderBy($orderColumn, $dir);
                }
            }
            $resourceData = $resourceData->limit($length, $start)->get()->getResultObject();

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


    public function getStoredRows()
    {
        if ($this->request->isAJAX()) {
            $reqData = $this->request->getPost();
            $plantilla_id = $reqData['plantilla_id'] ?? 0;

            $resourceData = $this->model->getResource([], $plantilla_id);
            $resourceData = $resourceData->get()->getResultObject();

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

    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, 'cliente_plantilla_precios_lineas' )
                ->fields(
                    Field::inst( 'plantilla_id' ),
                    Field::inst( 'tipo' ),
                    Field::inst( 'tipo_maquina' ),
                    Field::inst( 'tipo_impresion' ),
                    Field::inst( 'user_updated_id' ),
                    Field::inst( 'updated_at' ),
                    Field::inst( 'tiempo_min' )
                        ->getFormatter( 'Format::toDecimalChar')->setFormatter( 'Format::fromDecimalChar')
                        ->validator( 'Validate::notEmpty',array(
                                'message' => lang('ClientePrecios.validation.required'))
                        )
                        ->validator('Validate::numeric', array(
                                "decimal" => ',',
                                'message' => lang('ClientePrecios.validation.decimal'))
                        ),
                    
                    Field::inst( 'tiempo_max' )
                        ->getFormatter( 'Format::toDecimalChar')->setFormatter( 'Format::fromDecimalChar')
                        ->validator( 'Validate::notEmpty',array(
                                'message' => lang('ClientePrecios.validation.required'))
                        )
                        ->validator('Validate::numeric', array(
                            "decimal" => ',',
                            'message' => lang('ClientePrecios.validation.decimal'))
                        ),
                    
                    Field::inst( 'precio_hora' )
                        ->getFormatter( 'Format::toDecimalChar')->setFormatter( 'Format::fromDecimalChar')
                        ->validator( 'Validate::notEmpty',array(
                                'message' => lang('ClientePrecios.validation.required'))
                        )
                        ->validator('Validate::numeric', array(
                            "decimal" => ',',
                            'message' => lang('ClientePrecios.validation.decimal'))
                        ),
                    
                    Field::inst( 'margen' )
                        ->getFormatter( 'Format::toDecimalChar')->setFormatter( 'Format::fromDecimalChar')
                        ->validator( 'Validate::notEmpty',array(
                                'message' => lang('ClientePrecios.validation.required'))
                        )
                        ->validator('Validate::numeric', array(
                                "decimal" => ',',
                                'message' => lang('ClientePrecios.validation.decimal'))
                        ),

                )
                ->on('preCreate', function ($editor, &$values) {
                    $datetime = (new \CodeIgniter\I18n\Time("now"));
                    $editor
                        ->field('user_updated_id')
                        ->setValue(auth()->user()->id);
                    $editor
                        ->field('updated_at')
                        ->setValue($datetime->format('Y-m-d H:i:s'));
                })
                ->on('preEdit', function ($editor, &$values) {
                    
                    $datetime = (new \CodeIgniter\I18n\Time("now"));
                    $editor
                        ->field('user_updated_id')
                        ->setValue(auth()->user()->id);
                    $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);
        }
    }

}
