<?php

namespace App\Controllers\Tarifas\Acabados;

use App\Controllers\BaseResourceController;
use App\Entities\Tarifas\Acabados\ServicioAcabadoEntity;
use App\Models\Tarifas\Acabados\ServicioAcabadoModel;
use CodeIgniter\I18n\Time;
use Hermawan\DataTables\DataTable;

class ServiciosAcabado extends BaseResourceController
{

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

    protected static $singularObjectName = 'Servicio Acabado';
    protected static $singularObjectNameCc = 'serviciosAcabado';
    protected static $pluralObjectName = 'Servicios Acabado';
    protected static $pluralObjectNameCc = 'serviciosAcabado';

    protected static $controllerSlug = 'serviciosacabado';

    protected static $viewPath = 'themes/vuexy/form/tarifas/acabado/';

    protected $indexRoute = 'serviciosAcabadoList';


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

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

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

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


    public function index()
    {

        checkPermission('tarifa-acabado.menu');

        $viewData = [
            'currentModule' => static::$controllerSlug,
            'pageSubTitle' => lang('Basic.global.ManageAllRecords', [lang('Servicioacabado.serviciosacabado')]),
            'servicioacabadoEntity' => new ServicioAcabadoEntity(),
            'usingServerSideDataTable' => true,
        ];

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

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

    public function add()
    {

        checkPermission('tarifa-acabado.create', $this->indexRoute);

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

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

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

            $tarifasSeleccionadas = $postData['tarifasAcabado'] ?? [];
            unset($postData['tarifasAcabado']);

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

            $sanitizedData['user_updated_id'] = auth()->user()->id;

            if ($this->request->getPost('mostrar_en_presupuesto_cliente') == null) {
                $sanitizedData['mostrar_en_presupuesto'] = false;
            }

            if ($this->request->getPost('acabado_cubierta') == null) {
                $sanitizedData['acabado_cubierta'] = false;
            }

            if ($this->request->getPost('acabado_sobrecubierta') == null) {
                $sanitizedData['acabado_sobrecubierta'] = false;
            }

            $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')]) . '.';

                $modelTable = model("App\Models\Tarifas\Acabados\TarifasAcabadoServiciosAcabadoModel");
                
                foreach ($tarifasSeleccionadas as $tarifaId) {
                    $modelTable->insert(['servicio_id' => $id, 'tarifa_id' => $tarifaId, 'user_updated_id' => auth()->user()->id]);
                }

                if ($thenRedirect) :
                    if (!empty($this->indexRoute)) :
                        return redirect()->to(site_url('/serviciosacabado/edit/' . $id))->with('message', $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['tarifasSeleccionadas'] = [];
        $this->viewData['servicio'] = isset($sanitizedData) ? new ServicioAcabadoEntity($sanitizedData) : new ServicioAcabadoEntity();
        $this->viewData['formAction'] = route_to('createServicioAcabado');
        $this->viewData['boxTitle'] = lang('Basic.global.addNew') . ' ' . lang('ServicioAcabado.moduleTitle') . ' ' . lang('Basic.global.addNewSuffix');


        return $this->displayForm(__METHOD__);
    }


    public function edit($requestedId = null)
    {

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

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

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

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

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

            $tarifasSeleccionadas = $postData['tarifasAcabado'] ?? [];
            unset($postData['tarifasAcabado']);

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

            $sanitizedData['user_updated_id'] = auth()->user()->id;

            if ($this->request->getPost('mostrar_en_presupuesto_cliente') == null) {
                $sanitizedData['mostrar_en_presupuesto'] = false;
            }

            if ($this->request->getPost('acabado_cubierta') == null) {
                $sanitizedData['acabado_cubierta'] = false;
            }

            if ($this->request->getPost('acabado_sobrecubierta') == null) {
                $sanitizedData['acabado_sobrecubierta'] = false;
            }


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

                endif;

                $servicio->fill($sanitizedData);

                $modelTable = model("App\Models\Tarifas\Acabados\TarifasAcabadoServiciosAcabadoModel");
                
                $modelTable->where('servicio_id',$id)->delete();
                foreach ($tarifasSeleccionadas as $tarifaId) {
                    $modelTable->insert(['servicio_id' => $id, 'tarifa_id' => $tarifaId, 'user_updated_id' => auth()->user()->id]);
                }

                $thenRedirect = false;
            endif;

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

        $this->viewData['tarifasSeleccionadas'] = $this->getTarifasSeleccionadasForView($id);

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

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


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


    public function datatable()
    {

        $model = model(ServicioAcabadoModel::class);
        $q = $model->getDatatableQuery();
        //return $this->response->setJSON($q->get());
        return DataTable::of($q)
            ->add("action", callback: function ($q) {
                return '<span class="edit"><a href="javascript:void(0);"><i class="ti ti-pencil ti-sm btn-edit mx-2" data-id="' . $q->id . '"></i></a></span>'
                    . (auth()->user()->can("servicio-acabado.delete") ?
                        '<span class="delete"><a href="javascript:void(0);"><i class="ti ti-trash ti-sm btn-delete mx-2" data-id="' . $q->id . '"></i></a></span>'
                        : '');
            })
            ->edit(
                "updated_at",
                fn($q) => Time::createFromFormat("Y-m-d H:i:s", $q->updated_at)->format("d/m/Y")
            )
            ->toJson(returnAsObject: true);
    }


    public function getTarifasSeleccionadasForView($servicioId){

        $model = model("App\Models\Tarifas\Acabados\TarifasAcabadoServiciosAcabadoModel");
        $ids = $model->getTarifasForServicio($servicioId);

        return $ids;
    }


    public function getTarifasSeleccionadas()
    {
        $model = model("App\Models\Tarifas\Acabados\TarifaAcabadoModel");
        $ids = $this->request->getGet('ids');
        
        if (empty($ids)) {
            return $this->response->setJSON([]);
        }

        $query = $model->select('lg_tarifa_acabado.id, lg_tarifa_acabado.nombre')->whereIn('lg_tarifa_acabado.id', $ids);

        $query->where('lg_tarifa_acabado.deleted_at', null);
        
        $tarifas = $query->findAll(); 
        
        return $this->response->setJSON($tarifas);
    }

    public function getTarifas()
    {
        $model = model("App\Models\Tarifas\Acabados\TarifaAcabadoModel");

        $search = $this->request->getGet('search'); // Obtiene el parámetro de búsqueda
        
        $acabado_cubierta = $this->request->getGet('acabado_cubierta');
        $acabado_sobrecubierta = $this->request->getGet('acabado_sobrecubierta');

        $query = $model->select('lg_tarifa_acabado.id, lg_tarifa_acabado.nombre');
        
        if (!empty($search)) {
            $query->like('lg_tarifa_acabado.nombre', $search);
        }

        if($acabado_cubierta){
            $query->where('lg_tarifa_acabado.acabado_cubierta', $acabado_cubierta);
        }
        if($acabado_sobrecubierta){
            $query->where('lg_tarifa_acabado.acabado_sobrecubierta', $acabado_sobrecubierta);
        }
        
        $query->where('lg_tarifa_acabado.deleted_at', null);

        $tarifas = $query->findAll(); 

        return $this->response->setJSON($tarifas);
    }

}