<?php  namespace App\Controllers\Compras;

use stdClass;
use App\Controllers\BaseResourceController;

use App\Models\Collection;

use App\Entities\Compras\ProveedorEntity;

use App\Models\Compras\ProveedorModel;

class Proveedores extends \App\Controllers\BaseResourceController {

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

    protected static $singularObjectName = 'Proveedor';
    protected static $singularObjectNameCc = 'proveedor';
    protected static $pluralObjectName = 'Proveedores';
    protected static $pluralObjectNameCc = 'proveedores';

    protected static $controllerSlug = 'proveedores';

    protected static $viewPath = 'themes/vuexy/form/compras/proveedores/';

    protected $indexRoute = 'proveedorList';

    

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

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


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

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


    public function index() {

        checkPermission('proveedores.menu');
        
        $viewData = [
                'currentModule' => static::$controllerSlug,
                'pageSubTitle' => lang('Basic.global.ManageAllRecords', [lang('Proveedores.proveedor')]),
                'proveedorEntity' => new ProveedorEntity(),
                'usingServerSideDataTable' => true,
                
            ];

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

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


    public function add() {
        
        checkPermission('proveedores.create');        

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

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

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

            // Rellenar el campo "propiedades" si es necesario
            $postData = $this->getPropiedadesFromPost($postData);
            
			$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', [mb_strtolower(lang('Proveedores.proveedor'))]);
						$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', [mb_strtolower(lang('Proveedores.proveedor'))]).'.';
                $message .= anchor( "admin/proveedores/{$id}/edit" , lang('Basic.global.continueEditing').'?');
                $message = ucfirst(str_replace("'", "\'", $message));

                if ($thenRedirect) :
                    if (!empty($this->indexRoute)) :
                        return redirect()->to(site_url('/compras/proveedores/edit/' . $id))->with('message', $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['proveedorEntity'] = isset($sanitizedData) ? new ProveedorEntity($sanitizedData) : new ProveedorEntity();
		$this->viewData['proveedorTipoList'] = $this->getProveedorTipoListItems($proveedorEntity->tipo_id ?? null);
		$this->viewData['provinciaList'] = $this->getProvinciaListItems($proveedorEntity->provincia_id ?? null);
		$this->viewData['paisList'] = $this->getPaisListItems();

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

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

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

    public function edit($requestedId = null) {

        checkPermission('proveedores.edit');
        
        if ($requestedId == null) :
            return $this->redirect2listView();
        endif;
        $id = filter_var($requestedId, FILTER_SANITIZE_URL);
        $proveedorEntity = $this->model->find($id);
        
        // Propiedades para proveedores tipo transporte
        if(!is_null($proveedorEntity->propiedades))
        {
            $proveedorEntity = $this->getPropiedadesFromEntity($proveedorEntity);
        }
        

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

        

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

            $nullIfEmpty = true; // !(phpversion() >= '8.1');
        
            $postData = $this->request->getPost();
            
            // Rellenar el campo "propiedades" si es necesario
            $postData = $this->getPropiedadesFromPost($postData);
            
            $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)->update($id, $sanitizedData);
            	    } catch (\Exception $e) {
            	        $noException = false;
            	        $this->dealWithException($e);
            	    }
            	else:
            	    $this->viewData['warningMessage'] = lang('Basic.global.formErr1', [mb_strtolower(lang('Proveedores.proveedor'))]);
            	    $this->session->setFlashdata('formErrors', $this->model->errors());
            	
            	endif;
            	
            	$proveedorEntity->fill($sanitizedData);

            	$thenRedirect = true;
            endif;
            if ($noException && $successfulResult) :
                $id = $proveedorEntity->id ?? $id;
                $message = lang('Basic.global.updateSuccess', [lang('Basic.global.record')]).'.';
                //$message = lang('Basic.global.updateSuccess', [mb_strtolower(lang('Proveedores.proveedor'))]).'.';
                //$message .= anchor( "admin/proveedores/{$id}/edit" , lang('Basic.global.continueEditing').'?');
                //$message = ucfirst(str_replace("'", "\'", $message));

                if ($thenRedirect) :
                    if (!empty($this->indexRoute)) :
                        //return redirect()->to(route_to( $this->indexRoute )  )->with('sweet-success', $message);
                        $this->session->setFlashData('sweet-success', $message);
                        return redirect()->to(site_url('/compras/proveedores/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['proveedorEntity'] = $proveedorEntity;
		$this->viewData['proveedorTipoList'] = $this->getProveedorTipoListItems($proveedorEntity->tipo_id ?? null);
		$this->viewData['provinciaList'] = $this->getProvinciaListItems($proveedorEntity->provincia_id ?? null);
		$this->viewData['paisList'] = $this->getPaisListItems();

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

        $this->viewData['boxTitle'] = lang('Basic.global.edit2').' '.lang('Proveedores.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;
            $search = $reqData['search']['value'];
            $requestedOrder = $reqData['order']['0']['column'] ?? 1;
            $order = ProveedorModel::SORTABLE[$requestedOrder >= 0 ? $requestedOrder : 0];
            $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);
            $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 getProveedorTipoListItems($selId = null) { 
		$data = [''=>lang('Basic.global.pleaseSelectA', [mb_strtolower(lang('Proveedores.tipoId'))])];
        if (!empty($selId)) :
            		$proveedorTipoModel = model('App\Models\Compras\ProveedorTipoModel');

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


	protected function getPaisListItems() { 
		$paisModel = model('App\Models\Configuracion\PaisModel');
		$onlyActiveOnes = true;
		$data = $paisModel->getAllForMenu('id, nombre','nombre', $onlyActiveOnes );

		return $data;
	}


	protected function getProvinciaListItems($selId = null) { 
		$data = [''=>lang('Basic.global.pleaseSelectA', [mb_strtolower(lang('Provincias.provincia'))])];
        if (!empty($selId)) :
            		$provinciaModel = model('App\Models\Configuracion\ProvinciaModel');

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


    private function getPropiedadesFromEntity($entity){

        $temp_data = $entity;
        $config = json_decode($temp_data->propiedades);
        if (in_array("palets",$config->config)){
            $temp_data->palets=1;
        }
        if (in_array("cajas",$config->config)){
            $temp_data->cajas=1;
        }
        return $temp_data;
    }

    private function getPropiedadesFromPost($postData){

        if (array_key_exists("cajas",$postData) || array_key_exists("palets",$postData)){

            $temp_data = $postData;
            $prop = new stdClass();
            $prop->config = [];
            if (array_key_exists("cajas",$temp_data)){
                array_push($prop->config, "cajas");
                unset($temp_data["cajas"]);
            }
            if (array_key_exists("palets",$temp_data)){
                array_push($prop->config, "palets");
                unset($temp_data["palets"]);
            }
            $temp_data["propiedades"] = json_encode($prop);
            return $temp_data;
        }
        else{
            $temp_data = $postData;
            $temp_data["propiedades"] = null;
            return $temp_data;
        }
    }

    public function getForSelect(){
        
        if ($this->request->isAJAX()) {
            $tipo_id = $this->request->getGet("tipo_id");
            $query = $this->model->builder()->select(
                [
                    "id",
                    "nombre as name"
                ]
            )->where('tipo_id', $tipo_id)->where('deleted_at', null)->orderBy("nombre", "asc");
            if ($this->request->getGet("q")) {
                $query->groupStart()
                    ->orLike("lg_proveedores.nombre", $this->request->getGet("q"))
                    ->groupEnd();
            }

            return $this->response->setJSON($query->get()->getResultObject());
        } else {
            return $this->failUnauthorized('Invalid request', 403);
        }
    }

}
