<?php

namespace App\Models\Facturas;

use CodeIgniter\Database\BaseBuilder;

class FacturaModel extends \App\Models\BaseModel
{

    protected $table = 'facturas';

    protected $useAutoIncrement = true;

    const SORTABLE = [
        0 => "t1.id",
        1 => "t1.numero",
        2 => "t1.fecha_factura_at",
        3 => "t2.nombre",
        4 => "t1.base",
        5 => "t1.total",
        6 => "t1.pendiente",
        7 => "t1.creditoAsegurado",
        8 => "t1.estado",
        9 => "t1.estado_pago",
        10 => "t4.nombre",
        11 => "DAFEDIFF(days, NOW(), t3.fecha_vencimiento_at)",
    ];

    const SORTABLE_PEDIDOS = [
        1 => "t1.numero",
        2 => "t2.nombre",
        3 => "t4.cantidad",
        4 => "t2.nombre",
        5 => "t1.estado",
        6 => "t1.fecha_factura_at",
        7 => "t1.total",
    ];

    // Lista de columnas basada en los campos de la tabla, para asignación masiva
    protected $allowedFields = [
        'pedido_id',
        'factura_rectificada_id',
        'factura_rectificativa_id',
        'cliente_id',
        'serie_id',
        'numero',
        'estado',
        'estado_pago',
        'fecha_factura_at',
        'notas',
        'base',
        'total',
        'pendiente',
        'total_pagos',
        'creditoAsegurado',
        'cliente_nombre',
        'cliente_address',
        'cliente_cif',
        'cliente_pais',
        'cliente_cp',
        'cliente_ciudad',
        'cliente_provincia',
        'created_at',
        'updated_at',
        'deleted_at',
        'user_created_id',
        'user_updated_id'
    ];

    protected $returnType = "App\Entities\Facturas\FacturaEntity";

    protected $useTimestamps = true;
    protected $useSoftDeletes = true;

    protected $createdField = "created_at";
    protected $updatedField = "updated_at";

    public static $labelField = "id";

    public function getResource(string $search = "", $cliente_id = -1)
    {
        $builder = $this->db
            ->table($this->table . " t1")
            ->select(
                "t1.id AS id, t1.numero AS numero, DATE_FORMAT(t1.fecha_factura_at, '%d/%m/%Y') AS fecha_factura_at, 
                t2.nombre AS cliente, t1.base AS base, t1.total AS total, t1.pendiente AS pendiente,
                t1.creditoAsegurado AS creditoAsegurado, t1.estado AS estado, t1.estado_pago AS estado_pago,
                GROUP_CONCAT(DISTINCT t4.nombre ORDER BY t4.nombre ASC SEPARATOR ', ') AS forma_pago, 
                DATE_FORMAT(MIN(CASE WHEN t3.fecha_vencimiento_at != '0000-00-00 00:00:00' THEN t3.fecha_vencimiento_at ELSE NULL END), '%d/%m/%Y') AS vencimiento, 
                t2.vencimiento AS dias_vencimiento"
            );

        $builder->join("clientes t2", "t2.id = t1.cliente_id", "left");
        $builder->join("facturas_pagos t3", "t3.factura_id = t1.id", "left");
        $builder->join("formas_pago t4", "t3.forma_pago_id = t4.id", "left");

        $builder->where("t1.deleted_at IS NULL");
        if (auth()->user()->inGroup("cliente-admin") || auth()->user()->inGroup("cliente-editor")) {
            $builder->where("t1.estado", "validada");
        }

        if ($cliente_id != -1) {
            $builder->where("t1.cliente_id", $cliente_id);
        }

        $builder->groupBy("t1.id"); // Agrupa por id de la factura

        return empty($search)
            ? $builder
            : $builder
                ->groupStart()
                ->like("t1.id", $search)
                ->orLike("t1.id", $search)
                ->groupEnd();
    }

    public function getDatatableQuery($cliente_id): BaseBuilder
    {
        $builder = $this->db
            ->table($this->table . " t1")
            ->select(
                "t1.id AS id, t1.numero AS numero, DATE_FORMAT(t1.fecha_factura_at, '%d/%m/%Y') AS fecha_factura_at, 
                t2.nombre AS cliente, t1.base AS base, t1.total AS total, t1.pendiente AS pendiente,
                t1.creditoAsegurado AS creditoAsegurado, t1.estado AS estado, t1.estado_pago AS estado_pago,
                GROUP_CONCAT(DISTINCT t4.nombre ORDER BY t4.nombre ASC SEPARATOR ', ') AS forma_pago, 
                DATE_FORMAT(MIN(CASE WHEN t3.fecha_vencimiento_at != '0000-00-00 00:00:00' THEN t3.fecha_vencimiento_at ELSE NULL END), '%d/%m/%Y') AS vencimiento, 
                t2.vencimiento AS dias_vencimiento"
            );
        $builder->join("clientes t2", "t2.id = t1.cliente_id", "left");
        $builder->join("facturas_pagos t3", "t3.factura_id = t1.id", "left");
        $builder->join("formas_pago t4", "t3.forma_pago_id = t4.id", "left");
        
        $builder->where("t1.deleted_at", null);

        if (auth()->user()->inGroup("cliente-admin") || auth()->user()->inGroup("cliente-editor")) {
            $builder->where("t1.estado", "validada");
        }

        if ($cliente_id != -1) {
            $builder->where("t1.cliente_id", $cliente_id);
        }

        $builder->groupBy("t1.id"); 
        //$query = $builder->getCompiledSelect();
        return $builder;
    }


    public function presupuestoHasFacturaValidada($presupuesto_id = null)
    {
        if ($presupuesto_id == null) {
            return false;
        }

        $result = $this->db->table($this->table . " t1")
            ->select("t1.id")
            ->join("facturas_lineas t2", "t2.factura_id = t1.id", "left")
            ->join("pedidos_linea t3", "t2.pedido_linea_impresion_id = t3.id", "left")
            ->where("t3.presupuesto_id", $presupuesto_id)
            ->where("t1.deleted_at IS NULL")
            ->where("t2.deleted_at IS NULL")
            ->where("t1.estado", "validada")
            ->get()
            ->getResultObject();

        return !empty($result);
    }

    public function getSumatoriosFacturacionCliente($cliente_id = -1){

        if($cliente_id == -1){
            return [
                'total_facturacion' => 0,
                'total_pendiente' => 0
            ];
        }

        $result = [];
        $data = $this->db->table('facturas f')
            ->select('sum(f.total) as total')
            ->where('f.cliente_id', $cliente_id)
            ->where('f.deleted_at IS NULL')
            ->where('f.estado', 'validada')
            ->get()
            ->getResultObject();
        $result['total_facturacion'] = 
            round(floatval(($data && $data[0]->total != null) ? $data[0]->total : 0), 2);

        $data = $this->db->table('facturas f')
            ->select('sum(f.pendiente) as pendiente')
            ->where('f.cliente_id', $cliente_id)
            ->where('f.deleted_at IS NULL')
            ->where('f.estado', 'validada')
            ->where('f.estado_pago', 'pendiente')
            ->get()
            ->getResultObject();
        $result['total_pendiente'] =
            round(floatval(($data && $data[0]->pendiente != null) ? $data[0]->pendiente : 0), 2);

        return $result;
    }


    /**
     * Get resource data for creating PDFs.
     *
     * @param string $search
     *
     * @return \CodeIgniter\Database\BaseBuilder
     */
    public function getResourceForPdf($factura_id = -1)
    {
        $builder = $this->db
            ->table($this->table . " t1")
            ->select(
                "t1.id AS id, t1.numero AS numero, DATE_FORMAT(t1.fecha_factura_at, '%d/%m/%Y') AS fecha_factura_at, 
                t1.base AS base, t1.total AS total, t1.pendiente AS pendiente,
                t1.creditoAsegurado AS creditoAsegurado, t1.estado AS estado, t1.estado_pago AS estado_pago,
                t4.nombre AS forma_pago, 
                DATE_FORMAT(MIN(CASE WHEN t3.fecha_vencimiento_at != '0000-00-00 00:00:00' THEN t3.fecha_vencimiento_at ELSE NULL END), '%d/%m/%Y') AS vencimiento, 
                t2.nombre AS cliente, t2.direccion AS cliente_direccion, t2.ciudad AS cliente_ciudad, 
                t2.cp AS cliente_cp, t2.cif AS cliente_cif, t2.vencimiento AS dias_vencimiento,  t2.ccc AS cliente_ccc,
                t5.nombre AS cliente_pais"
            );

        $builder->join("clientes t2", "t2.id = t1.cliente_id", "left");
        $builder->join("facturas_pagos t3", "t3.factura_id = t1.id", "left");
        $builder->join("formas_pago t4", "t3.forma_pago_id = t4.id", "left");
        $builder->join("lg_paises t5", "t2.pais_id = t5.id", "left");

        $builder->where("t1.id", $factura_id);
        $builder->where("t1.deleted_at IS NULL");
        $builder->groupBy("t1.id"); // Agrupa por id de la factura

        return $builder;
    }


    public function getResourcePedidos($pedido_id)
    {
        $builder = $this->db
            ->table($this->table . " t1")
            ->select(
                "t1.id AS id, t1.numero AS numero, t2.nombre AS serie, t1.estado AS estado, 
                t4.cantidad AS ejemplares,
                DATE_FORMAT(t1.fecha_factura_at, '%d/%m/%Y') AS fecha_factura_at, t1.total AS total"
            );

        $builder->join("series t2", "t2.id = t1.serie_id", "left");
        $builder->join("facturas_lineas t3", "t1.id = t3.factura_id", "left");
        $builder->join("facturas_pedidos_lineas t4", "t1.id = t4.factura_id", "left");
        $builder->join("pedidos_linea t5", "t4.pedido_linea_id = t5.id", "left");
        $builder->join("pedidos t6", "t5.pedido_id = t6.id", "left");

        $builder->where("t1.deleted_at IS NULL");
        $builder->where("t6.id", $pedido_id);

        $builder->groupBy("t1.id"); // Agrupa por id de la factura

        return $builder;
    }

    public function getCantidadLineaPedidoFacturada($linea_pedido_id)
    {
        $builder = $this->db
            ->table("facturas_pedidos_lineas t1")
            ->select("SUM(t1.cantidad) AS cantidad")
            ->where("t1.pedido_linea_id", $linea_pedido_id);

        return $builder->get()->getRow()->cantidad;
    }

    public function deleteFacturasLineasPedido($factura_id, $pedido_linea_id, $cantidad)
    {
        $this->db->table("facturas_pedidos_lineas")
            ->where("factura_id", $factura_id)
            ->where("pedido_linea_id", $pedido_linea_id)
            ->where("cantidad", $cantidad)
            ->delete();
    }

}