<?php

namespace App\Controllers\Clientes;

use App\Models\Collection;

use App\Entities\Clientes\ClienteDireccionesEntity;

use App\Models\Clientes\ClienteDireccionesModel;

use App\Models\Usuarios\UserModel;

use DataTables\Editor;
use DataTables\Editor\Field;
use DataTables\Editor\Validate;

class Clientedirecciones extends \App\Controllers\BaseResourceController
{
    protected $modelName = ClienteDireccionesModel::class;
    protected $format = 'json';

    protected static $singularObjectName = 'Direccion de cliente';
    protected static $singularObjectNameCc = 'direccionDeCliente';
    protected static $pluralObjectName = 'Direcciones de cliente';
    protected static $pluralObjectNameCc = 'direccionesDeCliente';

    protected static $controllerSlug = 'clientedirecciones';

    protected static $viewPath = 'themes/vuexy/form/clientes/direcciones/';

    protected $indexRoute = 'clienteDireccionesList';

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

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

        // Breadcrumbs (IMN)
        $this->viewData['breadcrumb'] = [
            ['title' => lang("Clientes.direccionesEnvio"), 'route' => "javascript:void(0);", 'active' => false],

        ];

        $this->viewData['comunidadAutonomaList'] = $this->getComunidadAutonomaListItems($clienteEntity->comunidad_autonoma_id ?? null);
        $this->viewData['provinciaList'] = $this->getProvinciaListItems($clienteEntity->provincia_id ?? null);
        $this->viewData['paisList'] = $this->getPaisListItems($clienteEntity->pais_id ?? null);

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


    public function index()
    {

        $id = auth()->user()->id;
        $user_model = new UserModel();
        $user = $user_model->find($id);
        $cliente_id = $user->cliente_id;

        $viewData = [
            'currentModule' => static::$controllerSlug,
            'pageSubTitle' => lang('Basic.global.ManageAllRecords', [lang('Clientes.cliente')]),
            'cliente_id' => $cliente_id,
            "user_id" => $id,
            'usingServerSideDataTable' => true,

        ];

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

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

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

            $reqData = $this->request->getPost();
            $cliente_id = $reqData['cliente_id'] ?? -1;
            $att = $reqData['att'] ?? "";
            $email = $reqData['email'] ?? "";
            $direccion = $reqData['direccion'] ?? "";
            $pais_id = $reqData['pais_id'] ?? -1;
            $provincia = $reqData['provincia'] ?? "";
            $municipio = $reqData['municipio'] ?? "";
            $cp = $reqData['cp'] ?? "";
            $telefono = $reqData['telefono'] ?? "";
            $alias = $reqData['alias'] ?? "";

            $data = [
                "cliente_id" => $cliente_id,
                "att" => $att,
                "email" => $email,
                "direccion" => $direccion,
                "pais_id" => $pais_id,
                "provincia" => $provincia,
                "municipio" => $municipio,
                "cp" => $cp,
                "telefono" => $telefono,
                "alias" => $alias,
            ];
            $response = $this->model->insert($data);

            $data_ret = [
                'data' => $response,
            ];
            return $this->respond($data_ret);
        } else {
            return $this->failUnauthorized('Invalid request', 403);
        }
    }


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

            $reqData = $this->request->getPost();
            $cliente_id = $reqData['cliente_id'] ?? -1;

            $clienteDireccionesModel = model('App\Models\Clientes\ClienteDireccionesModel');
            $menu = $clienteDireccionesModel->getMenuDirecciones($cliente_id);
            //$menu = $this->model->getMenuItems($cliente_id);

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


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

            $cliente_id = $this->request->getGet('cliente_id');


            $query = $this->model->builder()->select(
                [
                    "id",
                    "alias as name"
                ]
            )
                ->where("cliente_id", $cliente_id)
                ->orderBy("alias", "asc");
            if ($this->request->getGet("q")) {
                $query->groupStart()
                    ->orLike("clientes.nombre", $this->request->getGet("q"))
                    ->groupEnd();
            }

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


    public function datatable()
    {
        if ($this->request->isAJAX()) {
            $reqData = $this->request->getPost();

            $tipo = $reqData['tipo'] ?? null;

            if (is_null($tipo)) {
                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 = ClienteDireccionesModel::SORTABLE[$requestedOrder >= 0 ? $requestedOrder : 1];
                $dir = $reqData['order']['0']['dir'] ?? 'asc';

                $id_C = $reqData['cliente_id'] ?? -1;


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


                return $this->respond(Collection::datatable(
                    $resourceData,
                    $this->model->getResource()->countAllResults(),
                    $this->model->getResource("", $id_C)->countAllResults()
                ));
            } else {

                $id = $reqData['id'] ?? -1;

                $resourceData = $this->model->getDireccion($id);


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


    public function get($id)
    {
        try {
            $resourceData = $this->model->getDireccion($id);
            $response = (object)[
                'error' => false,
                'data' => $resourceData
            ];
            return $this->respond($response);
        } catch (\Exception $e) {
            $response = (object)[
                'error' => true,
                'message' => $e->getMessage()
            ];
            return $this->fail($response);
        }
    }

    public function getDireccionPresupuesto($id)
    {
        try {
            $model = model('App\Models\Presupuestos\PresupuestoDireccionesModel');
            $resourceData = $model->getDireccion($id);
            if(count($resourceData) > 0){
                $resourceData[0]->direccionId = $id;
            }
            
            $response = (object)[
                'error' => false,
                'data' => $resourceData
            ];
            return $this->respond($response);
        } catch (\Exception $e) {
            $response = (object)[
                'error' => true,
                'message' => $e->getMessage()
            ];
            return $this->fail($response);
        }
    }

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

            include(APPPATH . "ThirdParty/DatatablesEditor/DataTables.php");

            // Build our Editor instance and process the data coming from _POST
            $response = Editor::inst($db, 'cliente_direcciones')
                ->fields(
                    Field::inst('att')
                        ->validator(
                            'Validate::notEmpty',
                            array(
                                'message' => lang('ClienteDirecciones.validation.required')
                            )
                        )
                        ->validator(
                            Validate::maxLen(100),
                            array(
                                'message' => lang('ClienteDirecciones.validation.max_length')
                            )
                        ),
                    Field::inst('alias')
                        ->validator(
                            'Validate::notEmpty',
                            array(
                                'message' => lang('ClienteDirecciones.validation.required')
                            )
                        )
                        ->validator(
                            Validate::maxLen(100),
                            array(
                                'message' => lang('ClienteDirecciones.validation.max_length')
                            )
                        ),
                    Field::inst('email')
                        ->validator(
                            'Validate::notEmpty',
                            array(
                                'message' => lang('ClienteDirecciones.validation.required')
                            )
                        )
                        ->validator(
                            Validate::maxLen(100),
                            array(
                                'message' => lang('ClienteDirecciones.validation.max_length')
                            )
                        ),
                    Field::inst('direccion')
                        ->validator(
                            'Validate::notEmpty',
                            array(
                                'message' => lang('ClienteDirecciones.validation.required')
                            )
                        )
                        ->validator(
                            Validate::maxLen(255),
                            array(
                                'message' => lang('ClienteDirecciones.validation.max_length')
                            )
                        ),
                    Field::inst('municipio')
                        ->validator(
                            'Validate::notEmpty',
                            array(
                                'message' => lang('ClienteDirecciones.validation.required')
                            )
                        )
                        ->validator(
                            Validate::maxLen(100),
                            array(
                                'message' => lang('ClienteDirecciones.validation.max_length')
                            )
                        ),
                    Field::inst('cp')
                        ->validator(
                            'Validate::notEmpty',
                            array(
                                'message' => lang('ClienteDirecciones.validation.required')
                            )
                        )
                        ->validator(
                            Validate::maxLen(20),
                            array(
                                'message' => lang('ClienteDirecciones.validation.max_length')
                            )
                        ),
                    Field::inst('telefono')
                        ->validator(
                            'Validate::notEmpty',
                            array(
                                'message' => lang('ClienteDirecciones.validation.required')
                            )
                        )
                        ->validator(
                            Validate::maxLen(40),
                            array(
                                'message' => lang('ClienteDirecciones.validation.max_length')
                            )
                        ),
                    Field::inst('provincia')
                        ->validator(
                            function ($val, $data, $field, $host) {
                                if ($data['pais_id'] == 1) { // Si es españa provincia y CCAA es obligatorio
                                    if (strlen($val) > 100)
                                        return lang('ClienteDirecciones.validation.max_length');
                                    else if (strlen($val) == 0)
                                        lang('ClienteDirecciones.validation.required');
                                    else
                                        return true;
                                }
                                return true;
                            }
                        ),
                    Field::inst('pais_id')->validator('Validate::notEmpty', array(
                        'message' => lang('ClienteDirecciones.validation.required')
                    )),
                    Field::inst('cliente_id'),
                )

                ->debug(true)
                ->process($_POST)
                ->data();

            $newTokenHash = csrf_hash();
            $csrfTokenName = csrf_token();

            $response[$csrfTokenName] = $newTokenHash;

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


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

        return $data;
    }

    protected function getComunidadAutonomaListItems($selId = null)
    {
        $data = ['' => lang('Basic.global.pleaseSelectA', [mb_strtolower(lang('ComunidadesAutonomas.comunidadAutonoma'))])];
        if (!is_null($selId)) :
            $comunidadAutonomaModel = model('App\Models\Configuracion\ComunidadAutonomaModel');

            $selOption = $comunidadAutonomaModel->where('id', $selId)->findColumn('nombre');
            if (!empty($selOption)) :
                $data[$selId] = $selOption[0];
            endif;
        endif;
        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;
    }
}
