<?php
namespace App\Controllers\Configuracion;


use App\Controllers\BaseResourceController;

use App\Models\Collection;

use App\Entities\Configuracion\Maquina;

use App\Models\Configuracion\MaquinaModel;
use App\Services\MaquinaService;
use CodeIgniter\Validation\Validation;

class Maquinas extends \App\Controllers\BaseResourceController
{

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

    protected static $singularObjectName = 'Maquina';
    protected static $singularObjectNameCc = 'maquina';
    protected static $pluralObjectName = 'Maquinas';
    protected static $pluralObjectNameCc = 'maquinas';

    protected static $controllerSlug = 'maquinas';

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

    protected $indexRoute = 'maquinaList';
    protected MaquinaService $maquinaService;
    protected Validation $validation;

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

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

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


    public function index()
    {

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

        ];

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

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

    public function delete($id = null)
    {
        // Sanitizar el ID
        $id = filter_var($id, FILTER_SANITIZE_URL);

        // Validar que el ID es válido
        if (empty($id) || !is_numeric($id)) {
            return $this->respond(['status' => 'error', 'msg' => 'ID no válida']);
        }

        // Buscar la máquina en la base de datos
        $maquina = $this->model->find($id);
        if (!$maquina) {
            $message = lang('Basic.global.notFoundWithIdErr', [mb_strtolower(lang('Maquinas.maquina')), $id]);
            return $this->respond(['status' => 'error', 'msg' => 'ID no válida']);
        }

        // Verificar que el usuario está autenticado
        if (!auth()->user()) {
            return $this->respond(['status' => 'error', 'msg' => 'Usuario no autenticado']);
        }

        // Preparar los datos para actualizar
        $data = [
            'id' => $id,
            'is_deleted' => 1,
            'deleted_at' => date('Y-m-d H:i:s'),
            'user_updated_id' => auth()->user()->id,
        ];

        // Guardar los cambios
        if (!$this->model->save($data)) {
            return $this->respond(['status' => 'error', 'msg' => 'Error al eliminar']);
        }

        // Retornar éxito
        $message = lang('Basic.global.deleteSuccess', [lang('Basic.global.record')]) . '.';
        return $this->respond(['status' => 'error', 'msg' => $message]);
    }


    public function add()
    {
        if ($this->request->getPost()):

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

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

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

            // JJO
            $sanitizedData['user_created_id'] = auth()->user()->id;

            $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);
                        return redirect()->to(site_url('configuracion/maquinas/edit/' . $id))->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['maquina'] = isset($sanitizedData) ? new Maquina($sanitizedData) : new Maquina();
        $this->viewData['maquinaList'] = $this->getMaquinaListItems($maquina->padre_id ?? null);
        $this->viewData['tipoList'] = $this->getTipoOptions();

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

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

        if ($maquina == false):
            $message = lang('Basic.global.notFoundWithIdErr', [mb_strtolower(lang('Maquinas.maquina')), $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('is_padre') == null) {
                $sanitizedData['is_padre'] = false;
            }
            if ($this->request->getPost('is_rotativa') == null) {
                $sanitizedData['is_rotativa'] = false;
            }
            if ($this->request->getPost('is_inkjet') == null) {
                $sanitizedData['is_inkjet'] = false;
            }

            // JJO
            $sanitizedData['user_updated_id'] = auth()->user()->id;
            $noException = true;
            if ($successfulResult = $this->canValidate()): // if ($successfulResult = $this->validate($this->formValidationRules) ) :

                if ($this->canValidate()):
                    //JJO: comprobar alto y ancho impresion < alto y ancho
                    if ($sanitizedData['alto'] < $sanitizedData['alto_impresion']) {
                        $successfulResult = false;
                        $this->viewData['errorMessage'] = lang('Maquinas.validation.alto_menor_alto_impresion');
                        ;
                        $this->session->setFlashdata('formErrors', $this->model->errors());
                    } else if ($sanitizedData['ancho'] < $sanitizedData['ancho_impresion']) {
                        $successfulResult = false;
                        $this->viewData['errorMessage'] = lang('Maquinas.validation.ancho_menor_ancho_impresion');
                        ;
                        $this->session->setFlashdata('formErrors', $this->model->errors());
                    } else {
                        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('Maquinas.maquina'))]);
                    $this->session->setFlashdata('formErrors', $this->model->errors());

                endif;

                $maquina->fill($sanitizedData);

                $thenRedirect = false;
            endif;
            if ($noException && $successfulResult):
                $id = $maquina->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['maquina'] = $maquina;
        $this->viewData['maquinaList'] = $this->getMaquinaListItems($maquina->padre_id ?? null);
        $this->viewData['tipoList'] = $this->getTipoOptions();

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

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


        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;
            $searchValues = get_filter_datatables_columns($reqData);
            $requestedOrder = $reqData['order'] ?? [];

            $resourceData = $this->model->getResource($searchValues);
            foreach ($requestedOrder as $order) {
                $column = $order['column'] ?? 0;
                $dir = $order['dir'] ?? 'asc';
                $orderColumn = MaquinaModel::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([])->countAllResults(),
                $this->model->getResource($searchValues)->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 select(){
        $r = $this->model->getSelectQuery($this->request->getGet("q"));
        return $this->response->setJSON($r);
    }

    protected function getMaquinaListItems($selId = null)
    {
        $data = ['' => lang('Basic.global.pleaseSelectA', [mb_strtolower(lang('Maquinas.maquina'))])];
        if (!empty($selId)):
            $maquinaModel = model('App\Models\Configuracion\MaquinaModel');

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


    protected function getTipoOptions()
    {
        $tipoOptions = [
            '' => lang('Basic.global.pleaseSelect'),
            'impresion' => 'impresion',
            'manipulado' => 'manipulado',
            'acabado' => 'acabado',
        ];
        return $tipoOptions;
    }
    public function duplicate(int $maquina_id)
    {

        $bodyData = $this->request->getPost();
        $validated = $this->validation->run($bodyData,'maquina_duplicate');
        if($validated){
            $this->maquinaService->setMaquina($maquina_id);
            $duplicated = $this->maquinaService->duplicate($bodyData['name']);
            return $this->response->setJSON(["data" => $duplicated]);
        }else{
            return $this->response->setJSON(["errors" => $this->validation->getErrors()])->setStatusCode(400);
        }
        
    }
    public function find_maquina(int $maquina_id){
        $maquinaEntity = $this->model->find($maquina_id);
        return $this->response->setJSON($maquinaEntity);
    }

}
