<?php
namespace App\Controllers\Clientes;


use App\Controllers\BaseResourceController;

use App\Models\Clientes\ClienteUsuariosModel;
use App\Models\Collection;

use App\Entities\Clientes\ClienteContactoEntity;

use App\Models\Clientes\ClienteModel;

use App\Models\Clientes\ClienteContactoModel;
use DataTables\Editor;
use DataTables\Editor\Field;
use DataTables\Editor\Validate;

class Clienteusuarios extends \App\Controllers\BaseResourceController
{

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

    protected static $singularObjectName = 'Contacto de cliente';
    protected static $singularObjectNameCc = 'contactoDeCliente';
    protected static $pluralObjectName = 'Contactos de cliente';
    protected static $pluralObjectNameCc = 'contactosDeCliente';

    protected static $controllerSlug = 'cliente-contactos';

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

    protected $indexRoute = 'contactoDeClienteList';


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

    public function removeClienteFromUser($user_id)
    {
        if ($this->request->isAJAX()) {
            if (intval($user_id) > 0) {
                $this->model->removeClienteFromUser($user_id);
                return $this->respond(['status' => 'success', 'msg' => 'Usuario eliminado correctamente']);
            }
        } else {
            return $this->failUnauthorized('Invalid request', 403);
        }
    }

    public function addUserToClient(){
        
        if ($this->request->isAJAX()) {
            $user_id = $this->request->getPost("user_id");
            $cliente_id = $this->request->getPost("cliente_id");
            if (intval($user_id) > 0 && intval($cliente_id) > 0) {
                $this->model->addUserToClient($user_id, $cliente_id);
                return $this->respond(['status' => 'success', 'msg' => 'Usuario añadido correctamente']);
            }
        } else {
            return $this->failUnauthorized('Invalid request', 403);
        }
    }

    public function getAvailableUsers()
    {
        if ($this->request->isAJAX()) {
            $query = $this->model->builder()->select(
                [
                    "id",
                    "CONCAT(first_name, ' ', last_name) as name"
                ]
            )
            ->where("deleted_at", null)
            ->where("cliente_id", null);

            if ($this->request->getGet("q")) {
                $column = "CONCAT(first_name, ' ', last_name)";
                $value = $this->request->getGet("q");
                $query->groupStart()
                    ->where("LOWER(CONVERT($column USING utf8)) COLLATE utf8_general_ci LIKE", "%" . strtolower($value) . "%")
                    ->groupEnd();
            }

            $items = $query->get()->getResultObject();
            return $this->response->setJSON($items);

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


    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;
            $requestedOrder = $reqData['order'] ?? [];
            $id_C = $reqData['id_cliente'] ?? -1;

            $resourceData = $this->model->getResource("", $id_C);
            foreach ($requestedOrder as $order) {
                $column = $order['column'] ?? 0;
                $dir = $order['dir'] ?? 'asc';
                $orderColumn = ClienteUsuariosModel::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("", $id_C)->countAllResults()
            ));
        } else {
            return $this->failUnauthorized('Invalid request', 403);
        }
    }



}
