<?php

namespace App\Controllers;

use App\Controllers\BaseController;
use CodeIgniter\HTTP\ResponseInterface;

use App\Models\ConfigsModel;
use App\Models\ClientesModel;
use App\Models\OrdenesModel;
use App\Models\CotizacionesModel;
use App\Models\CotizacionesarticulosModel;
use App\Models\ProductosModel;

use App\Models\NdeModel;
use App\Models\NdearticulosModel;

use App\Models\CajaModel;

class NdeController extends BaseController
{
    public function __construct()
    {
        helper(["url", "form", "session", "epscolor"]);
        $this->epsconfig_lib = new \App\Libraries\EpsConfig_Lib();

        $this->configs = new ConfigsModel();
        $this->clientes = new ClientesModel();
        $this->ordenes = new OrdenesModel();
        $this->cotizaciones = new CotizacionesModel();
        $this->cotizacionesarticulos = new CotizacionesarticulosModel();        
        $this->productos = new ProductosModel();
        $this->nde = new NdeModel();
        $this->ndearticulos = new NdearticulosModel();
        $this->caja = new CajaModel();
    }

    public function index()
    {
        //
    }

    public function listande() {
        $respuesta = $this->nde->orderBy('id', 'desc')->get()->getResultArray();
        echo json_encode($respuesta);
    }

    public function nde_list(): string
    {
        $data['dataConfig'] = $this->epsconfig_lib->getData();

        $data['tablaurl'] = 'nde/listande';
        return view ('nde/nde_list', $data);
    }

    public function add_nde()
    {
        if ($this->request->getPost()) {
            $usuario = session()->get('user_name');

            $json_ar = $this->request->getVar("data_ar");
            $Array_ar = json_decode($json_ar, true);

            $json_arto = $this->request->getVar("data_arto");
            $Array_arto = json_decode($json_arto, true);

            $id_cliente = formato_uppercase($this->request->getVar('id_cliente'));
            $id_cotizacion = formato_uppercase($this->request->getVar('id_cotizacion'));
            if($id_cotizacion){$id_cotizacion = formato_uppercase($this->request->getVar('id_cotizacion')); } else {$id_cotizacion = null; }
            $id_orden = formato_uppercase($this->request->getVar('id_orden'));
            if($id_orden){$id_orden = formato_uppercase($this->request->getVar('id_orden')); } else {$id_orden = null; }

            $categoria = formato_capitalize($this->request->getVar('categoria'));
            $vendedor = formato_capitalize($this->request->getVar('vendedor'));
            $notas = ucwords($this->request->getVar('notas'));
            $informe = trim($this->request->getVar('informe'));
            if($informe){$informe = trim($this->request->getVar('informe')); } else {$informe = ''; }

            $estado = 'Realizada';

            $data1 = [
                "id_cliente" => $id_cliente,
                "id_orden" => $id_orden,
                "id_cotizacion" => $id_cotizacion,
                              
                "total_d" => $Array_arto[0]['total_d'],
                "subtotal_d" => $Array_arto[0]['subtotal_d'],
                "total_bs" => $Array_arto[0]['total_d'] * $Array_ar[0]['tasa'],
                "subtotal_bs" => $Array_arto[0]['subtotal_d'] * $Array_ar[0]['tasa'],
                "tasa" => $Array_ar[0]['tasa'],
                "iva" => $Array_arto[0]['iva'],

                "estado" => $estado,
                "categoria" => $categoria,
                "notas" => $notas,
                "vendedor" => $vendedor,
                "usuario" => $usuario,
            ];
            $id_nde = $this->nde->insert($data1);
            $data1 = $this->nde->find($id_nde);

            if ($data1) {

                $data2 = array();
                $count = count($Array_ar);
                //print_r($count);
                for ($i = 0; $i < $count; $i++) {
                    $data2[] = array(

                        'id_nde' => $id_nde,
                        'id_cliente' => $id_cliente,
                        'id_orden' => $id_orden,
                        'id_producto' => $Array_ar[$i]['id_producto'],

                        'codigo' => $Array_ar[$i]['codigo'],
                        'descripcion' => $Array_ar[$i]['descripcion'],
                        'cantidad' => $Array_ar[$i]['cantidad'],
                        'stock' => $Array_ar[$i]['stock'],
                        
                        'costo_d' => $Array_ar[$i]['costo_d'],
                        'precio_d' => $Array_ar[$i]['precio_d'],
                        'subtotal_d' => $Array_ar[$i]['subtotal_d'],
                        'precio_bs' => $Array_ar[$i]['precio_bs'],
                        'tasa' => $Array_ar[$i]['tasa'],

                        'condicion' => $Array_ar[$i]['condicion'],
                        'categoria' => $Array_ar[$i]['categoria'],

                    );
                }
                $this->ndearticulos->insertBatch($data2);


                if ((isset($id_orden)) && (!empty($id_orden))) {
                    $data4 = array(
                        'estado' => 'Nota de Entrega',
                    );
                    $this->ordenes->update($id_orden, $data4);
                }

                $data5 = array();
                $count = count($Array_ar);
                for ($i = 0; $i < $count; $i++) {

                    $data5[] = array(
                        'id_producto' => $Array_ar[$i]['id'],
                        'stock' => $Array_ar[$i]['cantidad'],
                    );
                }
                $this->productos->update_producto_resta($data5);

                /*
                $asiento = 'Por Cobrar';
                $data6 = array(
                    'id_nde' => $id_nde,
                    'id_cliente' => $id_cliente,
                    'id_orden' => $id_orden,
                    'id_cotizacion' => $id_cotizacion,
                    'asiento' => $asiento,
                    'categoria' => $categoria,
                    'total_d' => $data1['total_d'],
                );
                $this->caja->insert($data6);
                */                

                $data = array('data' => $data1);
                $success = array('success' => 'add_ok');
                $mensaje = array('mensaje' => 'Datos almacenados en Base Datos');
                $response = array_merge($mensaje, $success, $data);
            }

            /*$mensaje = array('mensaje' => 'Cliente almacendado en la base de datos');
            $success = array('success' => 'add_ok');
            //$data = array ('data' => $data);

            $response = array_merge($data, $mensaje, $success);*/
        }
        echo json_encode($response);
    }

    public function cotizaciones_nde_add($id = null)
    {
        $data['dataConfig'] = $this->epsconfig_lib->getData();
        $data['iva'] = $this->configs->select('id, iva')->get()->getResult();

        $data['html_documento'] = 'Nota de Entrega';
        $data['form_doc'] = 'form_add_nde';

        $data['cotizacion'] = $this->cotizaciones->find($id);
        $data['cliente'] = $this->clientes->find($data['cotizacion']['id_cliente']);
        if($data['cotizacion']['id_orden'] != null) { $data['post'] = $this->ordenes->find($data['cotizacion']['id_orden']); }
       
        $data['articulos']  = 'cotizaciones/listacotizaciones_ar/' . $id;
        $data['articulos_totales'] = 'cotizaciones/listatotales_id/' . $id;

        return view('nde/nde_add', $data);
    }

}
