<?php namespace App\Controllers\Tarifas;


use App\Controllers\BaseResourceController;

use App\Models\Collection;

use App\Entities\Tarifas\TarifaEncuadernacionTirada;

use App\Models\Tarifas\TarifaEncuadernacionLineaHorasModel;
use App\Models\Tarifas\TarifaEncuadernacionTiradaModel;
use App\Models\Tarifas\TarifaEncuadernacionLineaModel;
use App\Models\Compras\ProveedorModel;
use App\Models\Compras\ProveedorTipoModel;

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 Tarifaencuadernaciontiradas extends \App\Controllers\BaseResourceController
{
    protected static $controllerSlug = 'tarifaencuadernaciontiradas';

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

    protected static $singularObjectName = 'Tarifa Encuadernacion Tirada';
    protected static $singularObjectNameCc = 'tarifaEncuadernacionTirada';
    protected static $pluralObjectName = 'Tarifa Encuadernacion Tiradas';
    protected static $pluralObjectNameCc = 'tarifaEncuadernacionTiradas';

    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 = ['usingServerSideDataTable' => true]; // JJO

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


    public function delete($id = null)
    {
        if (!empty(static::$pluralObjectNameCc) && !empty(static::$singularObjectNameCc)) {
            $objName = mb_strtolower(lang(ucfirst(static::$pluralObjectNameCc).'.'.static::$singularObjectNameCc));
        } else {
            $objName = lang('Basic.global.record');
        }
        
        if (!$this->soft_delete){

            if (!$this->model->delete($id)) {
                return $this->failNotFound(lang('Basic.global.deleteError', [$objName]));
            }
        }
        else{
            $datetime = (new \CodeIgniter\I18n\Time("now"));

            $lineaModel = new TarifaEncuadernacionLineaModel();
            $lineaHorasModel = new TarifaEncuadernacionLineaHorasModel();
            $lineaResult = $lineaModel->removeAllEncuadernacionLineas($id, $datetime, $this->delete_flag);
            $lineaResult2 = $lineaHorasModel->removeAllEncuadernacionLineasHoras($id, $datetime, $this->delete_flag);

            $rawResult = $this->model->where('id',$id)
                ->set(['deleted_at' =>  $datetime->format('Y-m-d H:i:s'),
                        'is_deleted' => $this->delete_flag])
                ->update();

            if (!$rawResult && !$lineaResult && !$lineaResult2) {
                return $this->failNotFound(lang('Basic.global.deleteError', [$objName]));
            }

        }
        
        // $message = lang('Basic.global.deleteSuccess', [$objName]); IMN commented
        $message = lang('Basic.global.deleteSuccess', [lang('Basic.global.record')]);
        $response = $this->respondDeleted(['id' => $id, 'msg' => $message]);
        return $response;
    }


    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, 'tarifa_encuadernacion_tiradas')
                ->fields(
                    Field::inst('tirada_min')
                        ->getFormatter( 'Format::toDecimalChar')->setFormatter( 'Format::fromDecimalChar')
                        ->validator('Validate::numeric', array(
                                "decimal" => ',',
                                'message' => lang('TarifaEncuadernacionTiradas.validation.tirada_min.decimal'))
                        )
                        ->validator('Validate::notEmpty', array(
                                'message' => lang('TarifaEncuadernacionTiradas.validation.tirada_min.required'))
                        ),
                    Field::inst('tirada_max')
                        ->getFormatter( 'Format::toDecimalChar')->setFormatter( 'Format::fromDecimalChar')
                        ->validator('Validate::numeric', array(
                                "decimal" => ',',
                                'message' => lang('TarifaEncuadernacionTiradas.validation.tirada_max.decimal'))
                        )
                        ->validator('Validate::notEmpty', array(
                                'message' => lang('TarifaEncuadernacionTiradas.validation.tirada_max.required'))
                        ),
                    Field::inst('importe_fijo')
                        ->getFormatter( 'Format::toDecimalChar')->setFormatter( 'Format::fromDecimalChar')
                        ->validator('Validate::numeric', array(
                                "decimal" => ',',
                                'message' => lang('TarifaEncuadernacionTiradas.validation.tirada_min.decimal'))
                        )
                        ->validator('Validate::notEmpty', array(
                                'message' => lang('TarifaEncuadernacionTiradas.validation.tirada_min.required'))
                        ),
                    Field::inst('proveedor_id')
                        ->validator('Validate::notEmpty', array(
                            'message' => lang('TarifaEncuadernacionTiradas.validation.tirada_max.required'))
                    ),
                    Field::inst('tarifa_encuadernacion_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['tirada_min'] = $data['data'][$pkey]['tirada_min'];
                                $process_data['tirada_max'] = $data['data'][$pkey]['tirada_max'];
                                $process_data['proveedor_id'] = $data['data'][$pkey]['proveedor_id'];
                                $response = $this->model->checkIntervals($process_data, $pkey, $data['data'][$pkey]['tarifa_encuadernacion_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'];

            $requestedOrder0 = $reqData['order']['0']['column'] ?? 0;
            $order0 = TarifaEncuadernacionTiradaModel::SORTABLE[$requestedOrder0 >= 0 ? $requestedOrder0 : 1];
            $dir0 = $reqData['order']['0']['dir'] ?? 'asc';
            $requestedOrder1 = $reqData['order']['1']['column'] ?? $requestedOrder0;
            $order1 = TarifaEncuadernacionTiradaModel::SORTABLE[$requestedOrder1 >= 0 ? $requestedOrder1 : 1];
            $dir1 = $reqData['order']['1']['dir'] ?? 'asc';
            $requestedOrder2 = $reqData['order']['2']['column'] ?? $requestedOrder0;
            $order2 = TarifaEncuadernacionTiradaModel::SORTABLE[$requestedOrder2 >= 0 ? $requestedOrder2 : 1];
            $dir2 = $reqData['order']['2']['dir'] ?? 'asc';

            $id_TM = $reqData['id_tarifaencuadernacion'] ?? -1;

            $model = new TarifaEncuadernacionTiradaModel();

            $resourceData = $model->getResource("", $id_TM)->
                orderBy($order0, $dir0)->orderBy($order1, $dir1)->orderBy($order2, $dir2)->
                limit($length, $start)->get()->getResultObject();
            return $this->respond(Collection::datatable(
                $resourceData,
                $model->getResource()->countAllResults(),
                $model->getResource($search, $id_TM)->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);
        }
    }
    
}

