<?php

namespace App\Controllers\Facturacion;

use App\Models\Facturas\FacturaLineaModel;
use App\Models\Collection;
use DataTables\Editor;
use DataTables\Editor\Field;
use DataTables\Editor\Validate;

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

    protected static $controllerSlug = 'factura-lineas';


    public function datatable($factura_id = null){

        if ($this->request->isAJAX() && $factura_id != null) {

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

            $resourceData = $this->model->getResource($factura_id)->orderBy(1, $dir)->limit($length, $start)->get()->getResultObject();

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


    public function deleteLinea($factura_linea_id = 0){
        
        if (!empty(static::$pluralObjectNameCc) && !empty(static::$singularObjectNameCc)) {
            $objName = mb_strtolower(lang(ucfirst(static::$pluralObjectNameCc).'.'.static::$singularObjectNameCc));
        } else {
            $objName = lang('Basic.global.record');
        }

        if($factura_linea_id == 0){
            return $this->failNotFound(lang('Basic.global.deleteError', [$objName]));
        }

        $facturaLinea = $this->model->find($factura_linea_id);
        if($facturaLinea == null){
            return $this->failNotFound(lang('Basic.global.deleteError', [$objName]));
        }

        if($facturaLinea->pedido_linea_impresion_id != null){
            $this->model->deleteFacturasLineasPedido($facturaLinea->factura_id, $facturaLinea->pedido_linea_impresion_id, $facturaLinea->cantidad);    
        }

        if($facturaLinea->pedido_maquetacion_id != null){
            //$this->model->deleteFacturasLineasPedido($facturaLinea->factura_id, $facturaLinea->pedido_maquetacion_id, $facturaLinea->cantidad);    
        }
        
        $facturaLinea = $this->model->delete($factura_linea_id);
        $message = lang('Basic.global.deleteSuccess', [lang('Basic.global.record')]);
        $response = $this->respondDeleted(['id' => $factura_linea_id, 'msg' => $message]);
        return $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, 'facturas_lineas' )
                ->fields(
                    Field::inst( 'id' ),
                    Field::inst( 'base' ),
                    Field::inst( 'total_iva' ),
                    Field::inst( 'total' ),
                    Field::inst( 'cantidad' )
                        ->validator('Validate::numeric', array(
                            'message' => lang('Facturas.validation.numerico'))
                        )
                        ->validator('Validate::notEmpty', array(
                            'message' => lang('Facturas.validation.requerido'))
                        ),
                    Field::inst( 'descripcion' ) 
                        ->validator('Validate::notEmpty', array(
                        'message' => lang('Facturas.validation.requerido'))
                        ),
                    Field::inst( 'iva' )
                        ->validator('Validate::numeric', array(
                            'message' => lang('Facturas.validation.numerico'))
                        )
                        ->validator('Validate::notEmpty', array(
                            'message' => lang('Facturas.validation.requerido'))
                        ),
                    Field::inst( 'pedido_linea_impresion_id' )
                        ->setFormatter(function($val, $data, $opts) {
                            return $val === '' ? null : $val;
                        }),
                    Field::inst( 'factura_id' ),
                    Field::inst( 'user_updated_id' ),
                )
                ->on('preCreate', function ($editor, &$values) {
                    $totales = $this->generate_totales(
                        $values['factura_id'], 
                        $values['pedido_linea_impresion_id'], 
                        $values['total'], 
                        $values['iva'], 
                        $values['cantidad'],
                        $values['old_cantidad']);
                    $editor
                        ->field('user_updated_id')
                        ->setValue(auth()->user()->id);
                    $editor
                        ->field('base')
                        ->setValue($totales['base']);
                    $editor
                        ->field('total_iva')
                        ->setValue($totales['total_iva']);
                    $editor
                        ->field('total')
                        ->setValue($totales['total']);
                    $editor
                        ->field('user_updated_id')
                        ->setValue(auth()->user()->id);
                })
                ->on('preEdit', function ($editor, $id, &$values) {
                    $totales = $this->generate_totales(
                        $values['factura_id'], 
                        $values['pedido_linea_impresion_id'], 
                        $values['total'], 
                        $values['iva'], 
                        $values['cantidad'],
                        $values['old_cantidad']);
                    $editor
                        ->field('factura_id')
                        ->setValue($values['factura_id']);
                    $editor
                        ->field('pedido_linea_impresion_id')
                        ->setValue(null);
                    $editor
                        ->field('pedido_maquetacion_id')
                        ->setValue(null);
                    $editor
                        ->field('user_updated_id')
                        ->setValue(auth()->user()->id);
                    $editor
                        ->field('base')
                        ->setValue($totales['base']);
                    $editor
                        ->field('total_iva')
                        ->setValue($totales['total_iva']);
                    $editor
                        ->field('total')
                        ->setValue($totales['total']);
                })
                ->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);
        }
    }

    public function updateTotalesFactura($factura_id = 0){
        if($factura_id == 0){
            return;
        }

        $model = model('\App\Models\Facturas\FacturaModel');
        $model->updateTotales($factura_id);
    }

    private function generate_totales($factura_id, $pedido_linea_id, $total, $iva, $cantidad, $old_cantidad)
    {
        
        // si es una linea que se refiere a pedido
        if ($pedido_linea_id != null && $factura_id != null) {
            // se actualiza la cantidad de la linea de pedido en la tabla pivote facturas_pedidos_lineas
            $this->model->updateFacturaPedidoLinea($factura_id, $pedido_linea_id, $old_cantidad, $cantidad);
        }
        
        // se calcula y se actualiza el subtotal, total_iva y total
        // redondeando a 4 decimales el precio_unidad y a dos el resto
        $precio_unidad = round($total / $old_cantidad, 4);
        $base = round($precio_unidad * $cantidad, 2);
        $total_iva = round($base * $iva / 100, 2);
        $total = round($base + $total_iva, 2);
        $values = [];
        $values['base'] = $base;
        $values['total_iva'] = $total_iva;
        $values['total'] = $total;
        
        return $values;
    }
}

