<?php

namespace App\Controllers\Facturacion;

use App\Models\Facturas\FacturaPagoModel;
use App\Models\Collection;
use DataTables\Editor;
use DataTables\Editor\Field;
use DataTables\Editor\Validate;
use DataTables\Editor\Format;

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

    protected static $controllerSlug = 'factura-pagos';


    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 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_pagos' )
                ->fields(
                    Field::inst( 'id' ),
                    Field::inst( 'forma_pago_id' ),
                    Field::inst( 'notes' ),
                    Field::inst( 'fecha_pago_at' )
                        ->validator( Validate::dateFormat( 'Y-m-d H:i:s' ) )
                        ->getFormatter( Format::dateSqlToFormat( 'Y-m-d H:i:s' ) )
                        ->setFormatter( Format::dateFormatToSql( 'Y-m-d H:i:s' ) ),
                    Field::inst( 'fecha_vencimiento_at' )
                        ->validator( Validate::dateFormat( 'Y-m-d H:i:s' ) )
                        ->getFormatter( Format::dateSqlToFormat( 'Y-m-d H:i:s' ) )
                        ->setFormatter( Format::dateFormatToSql( 'Y-m-d H:i:s' ) ),
                    Field::inst( 'total' )
                        ->validator('Validate::numeric', array(
                            'message' => lang('Facturas.validation.numerico'))
                        )
                        ->validator('Validate::notEmpty', array(
                            'message' => lang('Facturas.validation.requerido'))
                        ),
                    Field::inst( 'factura_id' ),
                    Field::inst( 'user_updated_id' ),
                )
                ->on('preCreate', function ($editor, &$values) {
                    /*
                    $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) {
                    /*
                    $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);
        }
    }

}