<?php
namespace App\Controllers\Clientes;


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

use App\Entities\Clientes\ClientePreciosEntity;

use App\Models\Clientes\ClientePreciosModel;

use DataTables\Editor;
use DataTables\Editor\Field;
use DataTables\Editor\Validate;

class ClientePrecios extends \App\Controllers\BaseResourceController
{

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

    protected static $singularObjectName = 'Cliente precios';
    protected static $singularObjectNameCc = 'ClientePrecios';
    protected static $pluralObjectName = 'Clientes precios';
    protected static $pluralObjectNameCc = 'clientesprecios';

    protected static $controllerSlug = 'ClientePrecios';

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

    protected $indexRoute = 'clientepreciosList';


    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 updatePlantilla()
    {

        if ($this->request->isAJAX()) {

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

            $cliente_id = $postData['cliente_id'] ?? -1;
            $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($cliente_id);
            } else if ($cliente_id == -1) { // actualizar todos los clientes que usan una plantilla
                $this->model->update_from_plantilla($plantilla_id);
            } else {
                $this->model->copy_from_plantilla($cliente_id, $plantilla_id);
            }

            $newTokenHash = csrf_hash();
            $csrfTokenName = csrf_token();
            $data = [
                $csrfTokenName => $newTokenHash
            ];

            return $this->respond($data);

        } 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;

            $requestedOrder = $reqData['order'] ?? [];

            $searchValues = get_filter_datatables_columns($reqData);

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

            $resourceData = $this->model->getResource($searchValues, $cliente_id);
            foreach ($requestedOrder as $order) {
                $column = $order['column'] ?? 0;
                $dir = $order['dir'] ?? 'asc';
                $orderColumn = ClientePreciosModel::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($searchValues, $cliente_id)->countAllResults(),
                $this->model->getResource($searchValues, $cliente_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_precios')
                ->fields(
                    Field::inst('plantilla_id'),
                    Field::inst('cliente_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')
                            )
                        ),

                )
                ->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...
                                $process_data['tiempo_min'] = $data['data'][$pkey]['tiempo_min'];
                                $process_data['tiempo_max'] = $data['data'][$pkey]['tiempo_max'];
                                $process_data['tipo'] = $data['data'][$pkey]['tipo'];
                                $process_data['tipo_maquina'] = $data['data'][$pkey]['tipo_maquina'];
                                $process_data['tipo_impresion'] = $data['data'][$pkey]['tipo_impresion'];

                                $response = $this->model->checkIntervals($process_data, $pkey, $data['data'][$pkey]['cliente_id']);
                                // No se pueden duplicar valores al crear o al editar
                                if (!empty($response)) {
                                    return $response;
                                }
                        }
                    }
                })
                ->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);
        }
    }

    public function getCurrentPlantilla()
    {

        if ($this->request->isAJAX()) {
            $cliente_id = $this->request->getGet('cliente_id');
            $plantilla = $this->model->getPlantilla($cliente_id);
            return $this->respond($plantilla);
        } else {
            return $this->failUnauthorized('Invalid request', 403);
        }
    }

}
