<?php

namespace App\Controllers\Configuracion;


use App\Controllers\BaseResourceController;

// DataTables PHP library

 
// Alias Editor classes so they are easy to use
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;


use App\Models\Collection;
use CodeIgniter\Validation\Validation;



use App\Entities\Configuracion\PapelImpresion;

use App\Models\Configuracion\PapelImpresionModel;

use App\Models\Configuracion\PapelGenericoModel;

use App\Models\Configuracion\PapelImpresionTipologiaModel;
use App\Models\Configuracion\MaquinasPapelesImpresionModel;
use App\Models\Configuracion\MaquinaModel;

class Papelesimpresion extends \App\Controllers\BaseResourceController
{

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

    protected static $singularObjectName = 'Papel Impresion';
    protected static $singularObjectNameCc = 'papelImpresion';
    protected static $pluralObjectName = 'Papeles Impresion';
    protected static $pluralObjectNameCc = 'papelesImpresion';

    protected static $controllerSlug = 'papelesimpresion';

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

    protected $indexRoute = 'papelImpresionList';
    protected Validation $validation;

    public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
    {
        $this->viewData['pageTitle'] = lang('PapelImpresion.moduleTitle');
        $this->viewData['usingSweetAlert'] = true;

        $this->viewData = ['usingServerSideDataTable' => true]; // JJO

        // 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->tpModel = new PapelImpresionTipologiaModel();
        $this->validation = service("validation");

        // Breadcrumbs
        $this->viewData['breadcrumb'] = [
            ['title' => lang("App.menu_configuration"), 'route' => "javascript:void(0);", 'active' => false],
            ['title' => lang("App.menu_papelimpresion"), 'route' => route_to('papelImpresionList'), 'active' => true]
        ];

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


    public function index()
    {

        $viewData = [
            'currentModule' => static::$controllerSlug,
            'pageSubTitle' => lang('Basic.global.ManageAllRecords', [lang('PapelImpresion.papelImpresion')]),
            'papelImpresion' => new PapelImpresion(),
            'usingServerSideDataTable' => true,

        ];

        $viewData = array_merge($this->viewData, $viewData); // merge any possible values from the parent controller class

        return view(static::$viewPath . 'viewPapelImpresionList', $viewData);
    }


    public function add()
    {
        

        if ($this->request->getPost()) :

            $nullIfEmpty = false; // !(phpversion() >= '8.1');

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

            $sanitizedData = $this->sanitized($postData, $nullIfEmpty);


            $noException = true;
            if ($successfulResult = $this->canValidate()) : // if ($successfulResult = $this->validate($this->formValidationRules) ) :


                if ($this->canValidate()) :
                    try {
                        $successfulResult = $this->model->skipValidation(true)->save($sanitizedData);
                    } catch (\Exception $e) {
                        $noException = false;
                        $this->dealWithException($e);
                    }
                else :
                    $this->viewData['errorMessage'] = lang('Basic.global.formErr1', [lang('Basic.global.record')]);
                    $this->session->setFlashdata('formErrors', $this->model->errors());
                endif;

                $thenRedirect = true;  // Change this to false if you want your user to stay on the form after submission
            endif;
            if ($noException && $successfulResult) :

                $id = $this->model->db->insertID();

                $message = lang('Basic.global.saveSuccess', [lang('Basic.global.record')]) . '.';

                if ($thenRedirect) :
                    if (!empty($this->indexRoute)) :
                        return redirect()->to(site_url('/configuracion/papelesimpresion/edit/' . $id))->with('sweet-success', $message);
                        //return redirect()->to(route_to($this->indexRoute))->with('sweet-success', $message);
                    else :
                        return $this->redirect2listView('sweet-success', $message);
                    endif;
                else :
                    $this->session->setFlashData('sweet-success', $message);
                endif;

            endif; // $noException && $successfulResult

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

        $this->viewData['papelImpresion'] = isset($sanitizedData) ? new PapelImpresion($sanitizedData) : new PapelImpresion();
        $this->viewData['papelGenericoList'] = $this->getPapelGenericoListItems($papelImpresion->papel_generico_id ?? null);

        $this->viewData['formAction'] = route_to('createPapelImpresion');

        $this->viewData['boxTitle'] = lang('Basic.global.addNew') . ' ' . lang('PapelImpresion.moduleTitle') . ' ' . lang('Basic.global.addNewSuffix');


        return $this->displayForm(__METHOD__);
    } // end function add()

    public function edit($requestedId = null)
    {

        if ($requestedId == null) :
            return $this->redirect2listView();
        endif;
        $id = filter_var($requestedId, FILTER_SANITIZE_URL);
        $papelImpresion = $this->model->find($id);

        if ($papelImpresion == false) :
            $message = lang('Basic.global.notFoundWithIdErr', [mb_strtolower(lang('PapelImpresion.papelImpresion')), $id]);
            return $this->redirect2listView('sweet-error', $message);
        endif;

        

        if ($this->request->getPost()) :

            $nullIfEmpty = false; // !(phpversion() >= '8.1');

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

            $sanitizedData = $this->sanitized($postData, $nullIfEmpty);

            // JJO
            $sanitizedData['user_updated_id'] =  auth()->user()->id;
            
            
            if ($this->request->getPost('defecto') == null) {
                $sanitizedData['defecto'] = false;
            }
            if ($this->request->getPost('interior') == null) {
                $sanitizedData['interior'] = false;
            }
            if ($this->request->getPost('bn') == null) {
                $sanitizedData['bn'] = false;
            }
            if ($this->request->getPost('color') == null) {
                $sanitizedData['color'] = false;
            }
            if ($this->request->getPost('cubierta') == null) {
                $sanitizedData['cubierta'] = false;
            }
            if ($this->request->getPost('use_for_tapa_dura') == null) {
                $sanitizedData['use_for_tapa_dura'] = false;
            }
            if ($this->request->getPost('sobrecubierta') == null) {
                $sanitizedData['sobrecubierta'] = false;
            }
            if ($this->request->getPost('guardas') == null) {
                $sanitizedData['guardas'] = false;
            }
            if ($this->request->getPost('rotativa') == null) {
                $sanitizedData['rotativa'] = false;
            }
            if ($this->request->getPost('inkjet') == null) {
                $sanitizedData['inkjet'] = false;
            }
            if ($this->request->getPost('isActivo') == null) {
                $sanitizedData['isActivo'] = false;
            }
            if ($this->request->getPost('use_in_client') == null) {
                $sanitizedData['use_in_client'] = false;
            }

            // Hay que asegurarse de que se quitan los consumos de tintas de rotativa 
            // en caso de que se haya deseleccionado la opción rotativa 
            if(!$sanitizedData['rotativa'] && !$sanitizedData['inkjet']){
                $this->tpModel->removeForPapelImpresion($id);
            }


            // Si hay máquinas seleccionadas, hay que guardar las que cumplan las nuevas condiciones
            // y borrar el resto
            $this->updateMaquinas($id, $sanitizedData);
            

            $noException = true;
            if ($successfulResult = $this->canValidate()) : // if ($successfulResult = $this->validate($this->formValidationRules) ) :

                
                if ($this->canValidate()) :
                    try {
                        $successfulResult = $this->model->skipValidation(true)->update($id, $sanitizedData);
                    } catch (\Exception $e) {
                        $noException = false;
                        $this->dealWithException($e);
                    }
                else :
                    $this->viewData['warningMessage'] = lang('Basic.global.formErr1', [mb_strtolower(lang('PapelImpresion.papelImpresion'))]);
                    $this->session->setFlashdata('formErrors', $this->model->errors());

                endif;

                $papelImpresion->fill($sanitizedData);

                $thenRedirect = false;
            endif;
            if ($noException && $successfulResult) :
                $id = $papelImpresion->id ?? $id;
                $message = lang('Basic.global.updateSuccess', [lang('Basic.global.record')]).'.';

                if ($thenRedirect) :
                    if (!empty($this->indexRoute)) :
                        return redirect()->to(route_to($this->indexRoute))->with('sweet-success', $message);
                    else :
                        return $this->redirect2listView('sweet-success', $message);
                    endif;
                else :
                    $this->session->setFlashData('sweet-success', $message);
                endif;

            endif; // $noException && $successfulResult
        endif; // ($requestMethod === 'post')

        $this->viewData['papelImpresion'] = $papelImpresion;
        $this->viewData['papelGenericoList'] = $this->getPapelGenericoListItems($papelImpresion->papel_generico_id ?? null);

        $this->viewData['formAction'] = route_to('updatePapelImpresion', $id);

        $this->viewData['boxTitle'] = lang('Basic.global.edit2') . ' ' . lang('PapelImpresion.moduleTitle') . ' ' . lang('Basic.global.edit3');

        $this->viewData['usingServerSideDataTable'] = true; //JJO

        return $this->displayForm(__METHOD__, $id);
    } // end function edit(...)



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

            if(isset($reqData['id_PI'])){

                $id_PI = $reqData['id_PI'] ?? -1;
            
                if($id_PI>=0){

                    $data = $this->tpModel->findTipologiasForPapelImpresion($id_PI);
                    $resourceData = $data->get()->getResultObject();

                    return $this->respond(Collection::datatable(
                        $resourceData,
                        $this->tpModel->findTipologiasForPapelImpresion($id_PI)->countAllResults(),
                        $this->tpModel->findTipologiasForPapelImpresion($id_PI)->countAllResults()
                    ));
                }
            }
            else{
   
                $id_PG = $reqData['id_PG'] ?? -1;
                $start = $reqData['start'] ?? 0;
                $length = $reqData['length'] ?? 5;
                $search = $reqData['search']['value'];
                $requestedOrder = $reqData['order']['0']['column'] ?? 1;
                $requestedOrder2 = $reqData['order']['1']['column'] ?? $requestedOrder;
                $requestedOrder3 = $reqData['order']['2']['column'] ?? $requestedOrder;
                $requestedOrder4 = $reqData['order']['3']['column'] ?? $requestedOrder;
                $order = PapelImpresionModel::SORTABLE[$requestedOrder >= 0 ? $requestedOrder : 0];
                $order2 = PapelImpresionModel::SORTABLE[$requestedOrder2 >= 0 ? $requestedOrder2 : 0];
                $order3 = PapelImpresionModel::SORTABLE[$requestedOrder3 >= 0 ? $requestedOrder3 : 0];
                $order4 = PapelImpresionModel::SORTABLE[$requestedOrder4 >= 0 ? $requestedOrder4 : 0];
                $dir = $reqData['order']['0']['dir'] ?? 'asc';
                $dir2 = $reqData['order']['1']['dir'] ?? $dir;
                $dir3 = $reqData['order']['2']['dir'] ?? $dir;
                $dir4 = $reqData['order']['3']['dir'] ?? $dir;

                if($id_PG<0){

                    $resourceData = $this->model->getResource($search)->orderBy($order, $dir)->orderBy($order2, $dir2)->orderBy($order3, $dir3)
                                ->orderBy($order4, $dir4)->limit($length, $start)->get()->getResultObject();

                    return $this->respond(Collection::datatable(
                        $resourceData,
                        $this->model->getResource()->countAllResults(),
                        $this->model->getResource($search)->countAllResults()
                    ));
                }else{
                    $resourceData = $this->model->getResource($search, $id_PG)->orderBy($order, $dir)->limit($length, $start)->get()->getResultObject();

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


    
    public function allItemsSelect()
    {
        if ($this->request->isAJAX()) {
            $onlyActiveOnes = true;
            $reqVal = $this->request->getPost('val') ?? 'id';
            $menu = $this->model->getAllForMenu($reqVal . ', nombre', 'nombre', $onlyActiveOnes, false);
            $nonItem = new \stdClass;
            $nonItem->id = '';
            $nonItem->nombre = '- ' . lang('Basic.global.None') . ' -';
            array_unshift($menu, $nonItem);

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

    public function menuItems()
    {
        if ($this->request->isAJAX()) {
            $searchStr = goSanitize($this->request->getPost('searchTerm'))[0];
            $reqId = goSanitize($this->request->getPost('id'))[0];
            $reqText = goSanitize($this->request->getPost('text'))[0];
            $onlyActiveOnes = false;
            $columns2select = [$reqId ?? 'id', $reqText ?? 'nombre'];
            $onlyActiveOnes = false;
            $menu = $this->model->getSelect2MenuItems($columns2select, $columns2select[1], $onlyActiveOnes, $searchStr);
            $nonItem = new \stdClass;
            $nonItem->id = '';
            $nonItem->text = '- ' . lang('Basic.global.None') . ' -';
            array_unshift($menu, $nonItem);

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

    

    protected function getPapelGenericoListItems($selId = null)
    {
        $data = ['' => lang('Basic.global.pleaseSelectA', [mb_strtolower(lang('PapelGenerico.papelGenerico'))])];
        if (!empty($selId)) :
            $papelGenericoModel = model('App\Models\Configuracion\PapelGenericoModel');

            $selOption = $papelGenericoModel->where('is_deleted', 0)->where('id', $selId)->findColumn('nombre');
            if (!empty($selOption)) :
                $data[$selId] = $selOption[0];
            endif;
        endif;
        return $data;
    }

    private function updateMaquinas($id, $data){

        $ma_model = new MaquinaModel(); 
        $ma_pa_model = new MaquinasPapelesImpresionModel();

        $active_values = $ma_pa_model->getInitSelectedMachines($id, $data['rotativa'], $data['inkjet'])->get()->getResult('array');
        
        $ma_pa_model->deleteForPapelImpresion($id);

        // Se obtienen las máquinas que cumplen las condiciones
        $rows = $ma_model->getIdMaquinasForPapelImpresion($id, $data['rotativa'], $data['inkjet'])->get()->getResult('array');
        $ma_pa_model->insertRows($rows);

        // Se actualizan los activos que había en caso de que los hubiera
        if(count($active_values)>0){
            $ma_pa_model->updateRows($active_values);
        }
    }
    /**
     * Duplica el papel impresion y sus relaciones
     *
     * @param int $papel_impresion_id
     * @return Response
     */
    public function duplicate( int $papel_impresion_id) 
    {
        $bodyData = $this->request->getPost();
        $validated = $this->validation->run($bodyData, "papel_impresion_duplicate");
        if($validated){
            $papelImpresionEntity = $this->model->find($papel_impresion_id);
            $papelImpresionService  = service('papel_impresion');
            $duplicated = $papelImpresionService
            ->setPapelImpresionEntity($papelImpresionEntity)
            ->duplicate($bodyData["name"]);
            return $this->response->setJSON(["data" => $duplicated]);

        }else{
            return $this->response->setJSON(["errors" => $this->validation->getErrors()])->setStatusCode(400);
        }
        
    }
    public function papel_impresion_select()
    {
        $q = $this->request->getGet('q');
        $data = $this->model->querySelect($q)->get()->getResultArray();
        return $this->response->setJSON($data);
    }
    public function papel_impresion_find(int $papel_impresion_id)
    {
        $piEntity = $this->model->find($papel_impresion_id);
        return $this->response->setJSON($piEntity);
    }
}
