<?php

namespace App\Controllers\Facturacion;

use App\Models\Facturas\FacturaModel;
use App\Entities\Facturas\FacturaEntity;
use App\Models\Clientes\ClienteModel;
use App\Models\Collection;
use Hermawan\DataTables\DataTable;
use Exception;

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

    protected static $singularObjectNameCc = 'factura';
    protected static $singularObjectName = 'Factura';
    protected static $pluralObjectName = 'Facturas';
    protected static $controllerSlug = 'factura';

    protected static $viewPath = 'themes/vuexy/form/facturas/';

    protected $indexRoute = 'facturaList';

    public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
    {
        $this->viewData['pageTitle'] = lang('Facturas.facturas');
        // Se indica que este controlador trabaja con soft_delete

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

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

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

    }

    public function index()
    {
        checkPermission('facturas.menu');

        if (auth()->user()->inGroup('cliente-admin') || auth()->user()->inGroup('cliente-editor')) {
            // Se obtiene el cliente ID a partir del usuario de la sesion
            $model_user = model('App\Models\Usuarios\UserModel');
            $user = $model_user->find(auth()->user()->id);
            $clienteId = $user->cliente_id;
        } else {
            $clienteId = -1;
        }

        $this->viewData['cliente_id'] = $clienteId;

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

        $this->viewData['pageSubTitle'] = lang('Basic.global.ManageAllRecords', [lang('Tarifaextra.tarifaextra')]);
        parent::index();
    }


    public function list()
    {
        checkGroups(['admin', 'cliente-admin', 'cliente-editor', 'contabilidad']);

        $viewData = [
            'currentModule' => static::$controllerSlug,
            'pageSubTitle' => lang('Basic.global.ManageAllRecords', [lang('Facturas.facturas')]),
            'usingServerSideDataTable' => true,
            'pageTitle' => lang('Facturas.facturas'),
            ['title' => lang("App.menu_facturas"), 'route' => site_url('facturas/list'), 'active' => true]
        ];

        $viewData['breadcrumb'] = [
            ['title' => lang("App.menu_facturas"), 'route' => "javascript:void(0);", 'active' => false],
            ['title' => lang("Facturas.facturaList"), 'route' => "javascript:void(0);", 'active' => true]
        ];

        if (auth()->user()->inGroup('cliente-admin') || auth()->user()->inGroup('cliente-editor')) {
            // Se obtiene el cliente ID a partir del usuario de la sesion
            $model_user = model('App\Models\Usuarios\UserModel');
            $user = $model_user->find(auth()->user()->id);
            $clienteId = $user->cliente_id;
        } else {
            $clienteId = -1;
        }

        $viewData['cliente_id'] = $clienteId;

        // Establecer el idioma (opcional, si no está configurado en app/Config/App.php)
        $locale = explode('-', config('Basics')->i18n)[0]; // Or dynamically set it: \Config\Services::language()->getLocale();
        // Specify the language file name (without .php)
        $fileName = 'datePicker';
        // Build the path to the language file
        $filePath = APPPATH . "Language/{$locale}/{$fileName}.php";
        // Load the entire language file as an array
        $viewData['datepickerLang'] = json_encode(file_exists($filePath) ? require $filePath : []);
        $viewData['datepickerLocale'] = config('Basics')->i18n;

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


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

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

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

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

            $noException = true;
            $allData = true;

            if (!isset($postData['cliente_id']) || !isset($postData['serie_id'])) {

                $this->viewData['errorMessage'] = lang('Facturas.errors.requiredFields');
                $this->session->setFlashdata('formErrors', $this->model->errors());

                $allData = false;
                $noException = false;
            }

            try {
                $clienteModel = model('App\Models\Clientes\ClienteModel');
                $datosCliente = $clienteModel->getClienteDataFacturas($postData['cliente_id']);
                if (count($datosCliente) > 0) {
                    // add array data datosCliente to postData
                    $postData = array_merge($postData, $datosCliente[0]);
                }
            } catch (\Exception $e) {
                $noException = false;
                $this->dealWithException($e);
            }


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

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

            if (!$sanitizedData['creditoAsegurado']) {
                $sanitizedData['creditoAsegurado'] = 0;
            }

            if ($allData && $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;

            endif;
            if ($noException && $successfulResult):

                $id = $this->model->db->insertID();

                $message = lang('Basic.global.saveSuccess', [lang('Basic.global.record')]) . '.';

                return redirect()->to(route_to('editarFactura', $id))->with('sweet-success', $message);


            endif; // $noException && $successfulResult

        endif; // ($requestMethod === 'post')

        $this->viewData['factura'] = isset($sanitizedData) ? new FacturaEntity($sanitizedData) : new FacturaEntity();

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

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


        helper('form');

        $this->viewData['breadcrumb'] = [
            ['title' => lang("App.menu_facturas"), 'route' => "javascript:void(0);", 'active' => false],
            ['title' => lang("Facturas.facturaList"), 'route' => route_to('facturasList'), 'active' => true]
        ];

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

        $validation = \Config\Services::validation();

        $this->viewData['validation'] = $validation;

        $viewFilePath = static::$viewPath . 'viewAddFactura';

        return view($viewFilePath, $this->viewData);
    } // end function add()


    public function edit($id = null)
    {
        checkPermission('facturas.edit');

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

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


        $this->obtenerDatosFormulario($factura);

        $this->viewData['breadcrumb'] = [
            ['title' => lang("App.menu_facturas"), 'route' => "javascript:void(0);", 'active' => false],
            ['title' => lang("Facturas.facturaList"), 'route' => route_to('facturasList'), 'active' => true]
        ];

        $userModel = model('App\Models\Usuarios\UserModel');
        $factura->created_by = $userModel->getFullName($factura->user_created_id);
        $factura->updated_by = $userModel->getFullName($factura->user_updated_id);
        $factura->created_at_footer = $factura->created_at ? date(' H:i d/m/Y', strtotime($factura->created_at)) : '';
        $factura->updated_at_footer = $factura->updated_at ? date(' H:i d/m/Y', strtotime($factura->updated_at)) : '';

        $factura->showDeleteButton = model('App\Models\Facturas\FacturaPagoModel')
            ->where('factura_id', $factura->id)->countAllResults() == 0; 

        $this->viewData['facturaEntity'] = $factura;

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

        return $this->displayForm(__METHOD__, $id);
    }


    public function datatable()
    {

        $dataForClienteForm = false;
        if (auth()->user()->inGroup('cliente-admin') || auth()->user()->inGroup('cliente-editor')) {
            // Se obtiene el cliente ID a partir del usuario de la sesion
            $model_user = model('App\Models\Usuarios\UserModel');
            $user = $model_user->find(auth()->user()->id);
            $clienteId = $user->cliente_id;
        } else {
            $temp = $this->request->getGet('cliente_id');
            $clienteId = ($temp && $temp != null && $temp != "") ? $temp : -1;
            $dataForClienteForm = ($temp && $temp != null && $temp != "") ? true : false;
        }

        $model = model(FacturaModel::class);
        $q = $model->getDatatableQuery($clienteId);

        $searchValue = $this->request->getGet('fecha_factura') ?? '';

        if (!empty($searchValue)) {
            // Extraer las fechas del formato "YYYY-MM-DD|YYYY-MM-DD"
            $dates = explode('|', $searchValue);
            if (count($dates) == 2) {
                $q->where('t1.fecha_factura_at >=', $dates[0] . ' 00:00:00')
                    ->where('t1.fecha_factura_at <=', $dates[1] . ' 23:59:59');
            }
        }


        $result = DataTable::of($q)
            ->edit(
                "creditoAsegurado",
                function ($row, $meta) {
                    switch ($row->creditoAsegurado) {
                        case "0":
                            return lang('Basic.global.no');
                        case "1":
                            return lang('Basic.global.yes');
                        default:
                            return '--';    // Debug
                    }
                }
            )
            ->edit(
                "estado",
                function ($row, $meta) {
                    switch ($row->estado) {
                        case "borrador":
                            return lang('Facturas.borrador');
                        case "validada":
                            return lang('Facturas.validada');
                        default:
                            return '--';    // Debug
                    }
                }
            )
            ->edit(
                "estado_pago",
                function ($row, $meta) {
                    switch ($row->estado_pago) {
                        case "pendiente":
                            return lang('Facturas.pendiente');
                        case "pagada":
                            return lang('Facturas.pagada');
                        case "insolvente":
                            return lang('Facturas.insolvente');
                        default:
                            return '--';    // Debug
                    }
                }
            )
            ->edit(
                "forma_pago",
                function ($row, $meta) {
                    switch ($row->forma_pago) {
                        case "cheque":
                            return lang('Facturas.cheque');
                        case "compensada":
                            return lang('Facturas.compensada');
                        case "confirming":
                            return lang('Facturas.confirming');
                        case "giroDomiciliado":
                            return lang('Facturas.giroDomiciliado');
                        case "pagare":
                            return lang('Facturas.pagare');
                        case "transferencia":
                            return lang('Facturas.transferencia');
                        default:
                            return $row->forma_pago;    // Debug
        
                    }
                }
            )
            ->add("action", callback: function ($q) {
                if (auth()->user()->can('facturas.edit')) {
                    if ($q->estado == 'borrador') {
                        return '
                            <div class="btn-group btn-group-sm">
                                <a href="javascript:void(0);"><i class="ti ti-pencil ti-sm btn-edit mx-2" data-id="' . $q->id . '"></i></a>
                            </div>
                        ';
                    } else {
                        return '
                        <div class="btn-group btn-group-sm">
                            <a href="javascript:void(0);"><i class="ti ti-eye ti-sm btn-edit mx-2" data-id="' . $q->id . '"></i></a>
                        </div>
                    ';
                    }
                } else
                    return '';
            });
        if ($clienteId != -1) {
            $result->hide('cliente');
            $result->hide('creditoAsegurado');
            if (!$dataForClienteForm) {
                $result->hide('estado');
                $result->hide('estado_pago');
            }
            $result->hide('forma_pago');
            $result->hide('vencimiento');
            $result->hide('dias_vencimiento');
        }

        return $result->toJson(returnAsObject: true);
    }

    public function getDatosFacturacionClienteForm($cliente_id)
    {

        return $this->respond($this->model->getSumatoriosFacturacionCliente($cliente_id));
    }


    public function datatablePedidos()
    {

        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'] ?? 0;
            $order = FacturaModel::SORTABLE_PEDIDOS[$requestedOrder >= 0 ? $requestedOrder : 0];
            $dir = $reqData['order']['0']['dir'] ?? 'asc';

            $pedido_id = $reqData['pedido_id'] ?? 0;

            $resourceData = $this->model->getResourcePedidos($pedido_id)->orderBy($order, $dir)->limit($length, $start)->get()->getResultObject();

            return $this->respond(Collection::datatable(
                $resourceData,
                $this->model->getResourcePedidos($pedido_id)->countAllResults(),
                $this->model->getResourcePedidos($pedido_id)->countAllResults()
            ));
        } else {
            return $this->failUnauthorized('Invalid request', 403);
        }
    }

    public function update($id = null)
    {

        if ($this->request->isAJAX()) {
            $newTokenHash = csrf_hash();
            $csrfTokenName = csrf_token();

            if ($id == null):
                $data = [
                    'error' => 2,
                    $csrfTokenName => $newTokenHash
                ];
                return $this->respond($data);
            endif;
            $id = filter_var($id, FILTER_SANITIZE_URL);
            $facturaEntity = $this->model->find($id);

            if ($facturaEntity == false):
                $message = lang('Basic.global.notFoundWithIdErr', [mb_strtolower(lang('Factura.factura')), $id]);
                $data = [
                    'error' => $message,
                    $csrfTokenName => $newTokenHash
                ];
                return $this->respond($data);
            endif;

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

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

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

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

                // JJO
                $sanitizedData['user_updated_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)->update($id, $sanitizedData);
                        } catch (\Exception $e) {
                            $noException = false;
                            $this->dealWithException($e);
                        }
                    else:
                        $this->viewData['warningMessage'] = lang('Basic.global.formErr1', [mb_strtolower(lang('Facturas.factura'))]);
                        $this->session->setFlashdata('formErrors', $this->model->errors());

                    endif;

                    $facturaEntity->fill($sanitizedData);

                endif;
                if ($noException && $successfulResult):
                    $id = $facturaEntity->id ?? $id;
                    $message = lang('Basic.global.updateSuccess', [lang('Basic.global.record')]) . '.';

                    $data = [
                        'error' => 0,
                        $csrfTokenName => $newTokenHash
                    ];
                    return $this->respond($data);

                endif; // $noException && $successfulResult
            endif; // ($requestMethod === 'post')

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

    public function delete($id = null)
    {

        $user_id = auth()->user()->id;
        $datetime = (new \CodeIgniter\I18n\Time("now"));
        $rawResult = $this->model->where('id', $id)
            ->set([
                'deleted_at' => $datetime->format('Y-m-d H:i:s'),
                'user_updated_id' => $user_id,
            ])
            ->update();
        if (!$rawResult) {
            return $this->failNotFound(lang('Basic.global.deleteError', [$objName]));
        }

        $modelLineas = model('\App\Models\Facturas\FacturaLineaModel');
        $rawResult = $modelLineas->where('factura_id', $id)
            ->set([
                'deleted_at' => $datetime->format('Y-m-d H:i:s'),
                'user_updated_id' => $user_id,
            ])
            ->update();

        $this->model->db->query('DELETE FROM facturas_pedidos_lineas WHERE factura_id=' . $id);

        // $message = lang('Basic.global.deleteSuccess', [$objName]); IMN commented
        $message = lang('Basic.global.deleteSuccess', [lang('Basic.global.record')]);
        $response = $this->respondDeleted(['id' => $id, 'msg' => $message]);
        return $response;
    }


    public function menuPedidosPendientes($cliente_id)
    {

        if ($this->request->isAJAX()) {
            $model = model('\App\Models\Pedidos\PedidoLineaModel');

            $pedidos = [];
            try {
                $pedidos = $model->obtenerLineasPedidoSinFacturar($cliente_id);
            } catch (Exception $e) {

            }

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

    public function duplicate($factura_id = 0)
    {
        if ($this->request->isAJAX()) {

            $factura_origen = $this->model->find($factura_id);
            // se quita la key "id" del objeto
            unset($factura_origen->id);
            $factura_origen->estado = 'borrador';
            $factura_origen->estado_pago = 'pendiente';
            $factura_origen->base = 0;
            $factura_origen->total = 0;
            $factura_origen->pendiente = 0;
            $factura_origen->total_pagos = 0;
            $factura_origen->user_created_id = auth()->user()->id;
            $factura_origen->user_updated_id = null;

            $this->model->insert($factura_origen);
            $id = $this->model->getInsertID();

            $newTokenHash = csrf_hash();
            $csrfTokenName = csrf_token();
            $data = [
                'id' => $id,
                $csrfTokenName => $newTokenHash
            ];
            return $this->respond($data);

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

    public function updateTotales($factura_id = 0)
    {
        if ($this->request->isAJAX()) {

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

            $pendiente = $postData['pendiente'] ?? 0;
            $total = $postData['total'] ?? 0;

            $data = [
                'base' => $postData['base'] ?? 0,
                'total' => $total,
                'pendiente' => $pendiente,
                'total_pagos' => $postData['total_pagos'] ?? 0,
                'user_updated_id' => auth()->user()->id,
                'estado_pago' => (intval($pendiente) == 0 && intval($total) != 0) ? 'pagada' : 'pendiente',
            ];

            $newTokenHash = csrf_hash();
            $csrfTokenName = csrf_token();
            $data_ret = [
                $csrfTokenName => $newTokenHash
            ];

            if ($factura_id == 0) {
                return $this->respond($data_ret);
            }

            $data_ret['estado_pago'] = $data['estado_pago'];
            $model = model('\App\Models\Facturas\FacturaModel');
            $model->update($factura_id, $data);

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

    public function addExcedentes($factura_id)
    {

        if ($this->request->isAJAX()) {
            $model_factura_linea = model('\App\Models\Facturas\FacturaLineaModel');

            $postData = $this->request->getPost();
            $cantidad = $postData['cantidad'] ?? 0;
            $precio_unidad = $postData['precio_unidad'] ?? 0;
            $iva = $postData['iva'] ?? 0;
            $descripcion = $postData['descripcion'] ?? '';
            $descuento = $postData['descuento'] ?? 0;
            $pedido_linea_impresion_id = $postData['pedido_linea_impresion_id'] ?? null;
            $pedido_linea_maquetacion_id = $postData['pedido_linea_maquetacion_id'] ?? null;
            $pedido_id = $postData['pedido_id'] ?? 0;

            $nuevo_precio_unidad = round($precio_unidad * (100 - floatval($descuento)) / 100, 4);
            $base = round($cantidad * $nuevo_precio_unidad, 2);
            $total_iva = round($base * $iva / 100, 2);

            $data = (object) [
                'factura_id' => $factura_id,
                'pedido_linea_impresion_id' => $pedido_linea_impresion_id,
                'pedido_linea_maquetacion_id' => $pedido_linea_maquetacion_id,
                'descripcion' => $newString = preg_replace_callback('/Impresión de (\d+) ejemplares/', function ($matches) use ($cantidad) {
                    return 'Impresión de ' . $cantidad . ' ejemplares';
                }, $descripcion),
                'cantidad' => $cantidad,
                'precio_unidad' => $nuevo_precio_unidad,
                'iva' => $iva,
                'base' => $base,
                'total_iva' => $total_iva,
                'total' => round($base + $total_iva, 2),
                'user_updated_id' => auth()->user()->id,
            ];

            $model_factura_linea->insert($data);

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

    public function addLineaPedidoImpresion($factura_id, $data = -1)
    {

        if ($this->request) {
            if ($this->request->isAJAX())
                $pedido_linea_id = $this->request->getPost('lineaPedido') ?? 0;
        } else {
            if ($data == -1) {
                return "Error: sin datos";
            }
            $pedido_linea_id = $data;
        }

        $model_pedido_linea = model('\App\Models\Pedidos\PedidoLineaModel');
        $model_presupuesto = model('\App\Models\Presupuestos\PresupuestoModel');
        $model_factura_linea = model('\App\Models\Facturas\FacturaLineaModel');
        $model_factura = model('\App\Models\Facturas\FacturaModel');

        try {

            $linea = $model_pedido_linea->find($pedido_linea_id);

            $factura = $model_factura->find($factura_id);

            if ($factura) {

                if ($linea) {
                    $presupuesto = $model_presupuesto->find($linea->presupuesto_id);

                    if ($presupuesto) {
                        // Se añade la linea de factura
                        $descripcion = $model_presupuesto->generarLineaPedido($presupuesto->id, true, $linea->pedido_id);
                        $cantidad = intval($presupuesto->tirada) - intval($model_factura->getCantidadLineaPedidoFacturada($linea->id));
                        $base = 
                            floatval($presupuesto->total_aceptado_revisado && $presupuesto->total_aceptado_revisado != 0 ? 
                            $presupuesto->total_aceptado_revisado : $presupuesto->total_aceptado);
                        $base = round($base, 2);
                        $total_iva = $base * ($presupuesto->iva_reducido == 1 ? 0.04 : 0.21);
                        // se redondea a dos decimales
                        $total_iva = round($total_iva, 2);
                        $total = $base + $total_iva;

                        $data = (object) [
                            'factura_id' => $factura_id,
                            'pedido_linea_impresion_id' => $pedido_linea_id,
                            'descripcion' => $descripcion[0]->concepto,
                            'cantidad' => $cantidad,
                            'iva' => $presupuesto->iva_reducido == 1 ? 4 : 21,
                            'base' => $base,
                            'total_iva' => $total_iva,
                            'total' => $total,
                            'user_updated_id' => auth()->user()->id,
                        ];

                        $model_factura_linea->insert($data);

                        $id = $model_factura_linea->getInsertID();

                        if ($id) {

                            $model_factura_linea->addFacturaPedidoLinea($factura_id, $linea->id, $cantidad);

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

                            $data = [
                                'error' => 0,
                                'id' => $id,
                                $csrfTokenName => $newTokenHash
                            ];
                            if ($this->request) {
                                if ($this->request->isAJAX())
                                    return $this->respond($data);
                            } else {
                                // remove csrf token
                                unset($data[$csrfTokenName]);
                                return $data;
                            }
                        }
                    }
                }
            }
        } catch (Exception $e) {
            $newTokenHash = csrf_hash();
            $csrfTokenName = csrf_token();
            $data = [
                'error' => 1,
                'error_text' => $e->getMessage(),
                $csrfTokenName => $newTokenHash
            ];
            if ($this->request) {
                if ($this->request->isAJAX())
                    return $this->respond($data);
            } else {
                unset($data[$csrfTokenName]);
                return $data;
            }
        }
    }

    public function deleteLineaPedidoImpresion()
    {

        if ($this->request->isAJAX()) {

            $postData = $this->request->getPost();
            $factura_id = $postData['factura_id'] ?? 0;
            $linea_id = $postData['linea_id'] ?? 0;
            $cantidad = $postData['cantidad'] ?? 0;

            $model_factura_linea = model('\App\Models\Facturas\FacturaLineaModel');
            $model_factura_linea->deleteFacturasLineasPedido($factura_id, $linea_id, $cantidad);

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


    public function validar($factura_id)
    {

        if ($this->request->isAJAX()) {

            $factura = $this->model->find($factura_id);

            if ($factura) {
                $model_series = model('\App\Models\Configuracion\SeriesFacturasModel');
                $numero = $model_series->getSerieNumerada($factura->serie_id);

                $data = [
                    'estado' => 'validada',
                    'numero' => $numero,
                    'user_updated_id' => auth()->user()->id,
                ];

                if ((strpos($numero, "REC ") === 0)) {
                    $data['estado_pago'] = 'pagada';
                }

                $this->model->update($factura_id, $data);
            }


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


    public function updateCabecera($factura_id)
    {

        if ($this->request->isAJAX()) {
            if ($factura_id == 0) {
                return;
            }
            $factura = $this->model->find($factura_id);
            if ($factura) {
                $postData = $this->request->getPost();

                $dataName = $postData['name'] ?? '';
                $dataValue = $postData['value'] ?? '';

                if ($dataName == 'factura_rectificativa_id') {
                    // se actualiza la factura donde el campo 'numero' sea igual al valor de $dataValue. El campo a actualizar es 'factura_rectificada_id'
                    $factura_rectificada = $this->model->where('numero', $dataValue)->first();
                    if ($factura_rectificada) {
                        $data2 = [
                            'factura_rectificada_id' => $factura->numero,
                            'user_updated_id' => auth()->user()->id,
                        ];
                        $this->model->update($factura_rectificada->id, $data2);
                    }
                }

                $data = [
                    $dataName => $dataValue,
                    'user_updated_id' => auth()->user()->id,
                ];

                $this->model->update($factura_id, $data);

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

    /*************************************
     * FUNCIONES AUXILIARES
     ************************************/

    private function obtenerDatosFormulario(&$factura)
    {

        if ($factura->estado == 'borrador') {
            $serieModel = model('App\Models\Configuracion\SeriesFacturasModel');
            $serie = $serieModel->find($factura->serie_id);
            if ($serie) {
                $factura->numero = str_replace("{numero}", $serie->next, $serie->formato);
            }
        }

        $clienteModel = model('App\Models\Clientes\ClienteModel');
        $cliente = $clienteModel->find($factura->cliente_id);
        $factura->cliente_alias = $cliente->alias;

        $serieModel = model('App\Models\Configuracion\SeriesFacturasModel');
        $serie = $serieModel->find($factura->serie_id);
        $factura->serie_nombre = $serie->nombre;

        $formaPagoModel = model('App\Models\Configuracion\FormaPagoModel');
        $factura->formas_pago = $formaPagoModel->getMenuItems();

        $factura->fecha_factura_at_text = $factura->fecha_factura_at ? date('d/m/Y', strtotime($factura->fecha_factura_at)) : '';
    }

}
