<?php

namespace App\Controllers\Configuracion;


use App\Controllers\BaseResourceController;

use App\Models\Collection;

use App\Entities\Configuracion\PapelGenerico;

use App\Models\Configuracion\PapelGenericoModel;

class Papelesgenericos extends \App\Controllers\BaseResourceController
{

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

    protected static $singularObjectName = 'Papel Generico';
    protected static $singularObjectNameCc = 'papelGenerico';
    protected static $pluralObjectName = 'Papeles Genericos';
    protected static $pluralObjectNameCc = 'papelesGenericos';

    protected static $controllerSlug = 'papelesgenericos';

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

    protected $indexRoute = 'papelGenericoList';



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

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

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


    public function index()
    {

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

        ];

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

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


    public function add()
    {





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

            $nullIfEmpty = true; // !(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(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['papelGenerico'] = isset($sanitizedData) ? new PapelGenerico($sanitizedData) : new PapelGenerico();

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

        $this->viewData['boxTitle'] = lang('Basic.global.addNew') . ' ' . lang('PapelGenerico.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);
        $papelGenerico = $this->model->find($id);

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



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

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

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

            $sanitizedData = $this->sanitized($postData, $nullIfEmpty);
            if ($this->request->getPost('show_in_client') == null) {
                $sanitizedData['show_in_client'] = false;
            }
            if ($this->request->getPost('activo') == null) {
                $sanitizedData['activo'] = false;
            }
            if ($this->request->getPost('show_in_client_special') == null) {
                $sanitizedData['show_in_client_special'] = false;
            }

            if ($sanitizedData['show_in_client_special']) {
                $sanitizedData['show_in_client'] = true;
            }
            if ($sanitizedData['activo']) {
                $sanitizedData['activo'] = true;
            }

            $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('PapelGenerico.papelGenerico'))]);
                    $this->session->setFlashdata('formErrors', $this->model->errors());

                endif;

                $papelGenerico->fill($sanitizedData);

                $thenRedirect = false;
            endif;
            if ($noException && $successfulResult):
                $id = $papelGenerico->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['papelGenerico'] = $papelGenerico;

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

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

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

        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;
            }
            $start = $reqData['start'] ?? 0;
            $length = $reqData['length'] ?? 5;
            $search = $reqData['search']['value'];
            $requestedOrder = $reqData['order']['0']['column'] ?? 1;
            $order = PapelGenericoModel::SORTABLE[$requestedOrder >= 0 ? $requestedOrder : 1];
            $dir = $reqData['order']['0']['dir'] ?? 'asc';

            $resourceData = $this->model->getResource($search)->orderBy($order, $dir)->limit($length, $start)->get()->getResultObject();

            return $this->respond(Collection::datatable(
                $resourceData,
                $this->model->getResource()->countAllResults(),
                $this->model->getResource($search)->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, true);
            $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);
        }
    }

    public function getPapelCliente()
    {
        if ($this->request->isAJAX()) {

            $tirada = goSanitize($this->request->getGet('tirada'))[0] ?? null;
            $POD = null;
            if ($tirada != null) {
                $POD_value = model('App\Models\Configuracion\ConfigVariableModel')->getVariable('POD')->value;
                if (intval($tirada) <= intval($POD_value)) {
                    $POD = true;
                } else {
                    $POD = false;
                }
            }
            $tipo = goSanitize($this->request->getGet('tipo'))[0];
            $selected_papel = goSanitize($this->request->getGet('papel'))[0] ?? null;
            $cubierta = goSanitize($this->request->getGet('cubierta'))[0] ?? 0;
            $tapa_dura = goSanitize($this->request->getGet('tapa_dura'))[0] ?? null;
            $sobrecubierta = goSanitize($this->request->getGet('sobrecubierta'))[0] ?? 0;
            $guardas = goSanitize($this->request->getGet('guardas'))[0] ?? 0;

            $ancho = floatval($this->request->getGet('ancho') ?? 0);
            $alto = floatval($this->request->getGet('alto') ?? 0);
            $solapas = floatval($this->request->getGet('solapas') ?? 0);
            $lomo = floatval($this->request->getGet('lomo') ?? 0);

            $forSelect2 = intval($this->request->getGet('forSelect2') ?? 0);

            $anchoLibro = $ancho;

            if(intval($cubierta) == 1 || intval($sobrecubierta) == 1){
                $anchoLibro = 2 * $ancho + 2 * $solapas + $lomo;
            }

            $menu = $this->model->getPapelCliente($tipo, $cubierta, $sobrecubierta, $guardas, $selected_papel, $tapa_dura, false, $POD, $anchoLibro, $alto, $tirada);
            $menu2 = $this->model->getPapelCliente($tipo, $cubierta, $sobrecubierta, $guardas, $selected_papel, $tapa_dura, true, $POD, $anchoLibro, $alto, $tirada);

            if ($forSelect2) {
                $menu = array_map(function ($item) {
                    if (isset($item->id)) {
                        return [
                            'id' => $item->id,
                            'name' => $item->nombre
                        ];
                    } else {
                        return [
                            'id' => $item->gramaje,
                            'name' => $item->gramaje
                        ];
                    }
                }, $menu);

                return $this->respond($menu);
            }

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


    public function selectPapelEspecial()
    {

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

            $tirada = goSanitize($this->request->getGet('tirada'))[0] ?? null;
            $POD = null;
            if ($tirada != null) {
                $POD_value = model('App\Models\Configuracion\ConfigVariableModel')->getVariable('POD')->value;
                if (intval($tirada) <= intval($POD_value)) {
                    $POD = true;
                } else {
                    $POD = false;
                }
            }
            $tipo = goSanitize($this->request->getGet('tipo'))[0];
            $cubierta = goSanitize($this->request->getGet('cubierta'))[0] ?? 0;
            $sobrecubierta = goSanitize($this->request->getGet('sobrecubierta'))[0] ?? 0;

            $ancho = floatval($this->request->getGet('ancho') ?? 0);
            $alto = floatval($this->request->getGet('alto') ?? 0);
            $solapas = floatval($this->request->getGet('solapas') ?? 0);
            $lomo = floatval($this->request->getGet('lomo') ?? 0);

            $tapa_dura = $this->request->getGet('tapa_dura') ?? 0;

            $anchoLibro = 2 * $ancho + 2 * $solapas + $lomo;

            $items = $this->model->getPapelCliente($tipo, $cubierta, $sobrecubierta, false, null, $tapa_dura, true, $POD, $anchoLibro, $alto, $tirada);
            $items = array_map(function ($item) {
                return [
                    'id' => $item->id,
                    'name' => $item->nombre
                ];
            }, $items);
            return $this->response->setJSON($items);

        } else {
            return $this->failUnauthorized('Invalid request', 403);
        }
    }
}
