<?php
/*
 * This file is part of facturacion_base
 * Copyright (C) 2013-2017  Carlos Garcia Gomez  neorazorx@gmail.com
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

require_once 'plugins/facturacion_base/model/core/factura_cliente.php';

/**
 * Factura de un cliente.
 * 
 * @author Carlos García Gómez <neorazorx@gmail.com>
 */
class factura_cliente extends FacturaScripts\model\factura_cliente
{
    public function new_codigo() {
        /// buscamos el número inicial para la serie
        $num = 1;
        $serie0 = new \serie();
        $serie = $serie0->get($this->codserie);
        /// ¿Se ha definido un nº de factura inicial para esta serie y ejercicio? 
        if ($serie && $this->codejercicio == $serie->codejercicio) {
            $num = $serie->numfactura;
        }

        /// buscamos un hueco o el siguiente número disponible
        $encontrado = FALSE;
        
        $fecha = date("y-m-d", strtotime($this->fecha)); //$this->fecha;
        $hora = $this->hora;
        $sql = "SELECT " . $this->db->sql_to_int('numero') . " as numero,fecha,hora FROM " . $this->table_name;
        if ( $fecha > date("y-m-d",strtotime('2018-12-31'))) {
            $sql .= " where fecha > date('2018-12-31')";
            $ws = 1;
            
        }

        if (FS_NEW_CODIGO != 'NUM' && FS_NEW_CODIGO != '0-NUM') {
            if ( $ws==1) {
                $sql .= " AND ";
            } else {
                $sql .= " WHERE ";
            }   
            $sql .= " codejercicio = " . $this->var2str($this->codejercicio)
                 . " AND codserie = " . $this->var2str($this->codserie);
        }
        
        $sql .= " ORDER BY numero ASC;";
        
        $data = $this->db->select($sql);
        //$this->new_message("sql john : ".$sql." fecha ".$fecha."  fec-a  ".date('d-m-y',strtotime('31-12-2018'))."  fec-t ".$this->fecha);
        if ($data) {
            foreach ($data as $d) {
                if (intval($d['numero']) < $num) {
                    /**
                     * El número de la factura es menor que el inicial.
                     * El usuario ha cambiado el número inicial después de hacer
                     * facturas.
                     */
                } else if (intval($d['numero']) == $num) {
                    /// el número es correcto, avanzamos
                    $num++;
                } else {
                    /// Hemos encontrado un hueco y debemos usar el número y la fecha.
                    $encontrado = TRUE;
                    $fecha = Date('d-m-Y', \strtotime($d['fecha']));
                    $hora = Date('H:i:s', \strtotime($d['hora']));
                    break;
                }
            }
        }

        $this->numero = $num;

        if ($encontrado) {
            $this->fecha = $fecha;
            $this->hora = $hora;
        } else {
            /// nos guardamos la secuencia para abanq/eneboo
            $sec0 = new \secuencia();
            $sec = $sec0->get_by_params2($this->codejercicio, $this->codserie, 'nfacturacli');
            if ($sec && $sec->valorout <= $this->numero) {
                $sec->valorout = 1 + $this->numero;
                $sec->save();
            }
        }

        //$this->codigo = fs_documento_new_codigo(FS_FACTURA, "2019", $this->codserie, $this->numero);
        $this->codigo = fs_documento_new_codigo(FS_FACTURA, $this->codejercicio, $this->codserie, $this->numero);
    }

    private function clean_cache()
    {
        $this->cache->delete('factura_cliente_huecos');
    }

    /**
     * Guarda los datos en la base de datos
     * @return boolean
     */
    public function save()
    {
        if ($this->test()) {
            $this->clean_cache();

            if ($this->exists()) {
                $sql = "UPDATE " . $this->table_name . " SET idasiento = " . $this->var2str($this->idasiento) .
                    ", idasientop = " . $this->var2str($this->idasientop) .
                    ", idfacturarect = " . $this->var2str($this->idfacturarect) .
                    ", codigo = " . $this->var2str($this->codigo) .
                    ", numero = " . $this->var2str($this->numero) .
                    ", numero2 = " . $this->var2str($this->numero2) .
                    ", codigorect = " . $this->var2str($this->codigorect) .
                    ", codejercicio = " . $this->var2str($this->codejercicio) .
                    ", codserie = " . $this->var2str($this->codserie) .
                    ", codalmacen = " . $this->var2str($this->codalmacen) .
                    ", codpago = " . $this->var2str($this->codpago) .
                    ", coddivisa = " . $this->var2str($this->coddivisa) .
                    ", fecha = " . $this->var2str($this->fecha) .
                    ", codcliente = " . $this->var2str($this->codcliente) .
                    ", nombrecliente = " . $this->var2str($this->nombrecliente) .
                    ", cifnif = " . $this->var2str($this->cifnif) .
                    ", direccion = " . $this->var2str($this->direccion) .
                    ", ciudad = " . $this->var2str($this->ciudad) .
                    ", provincia = " . $this->var2str($this->provincia) .
                    ", apartado = " . $this->var2str($this->apartado) .
                    ", coddir = " . $this->var2str($this->coddir) .
                    ", codpostal = " . $this->var2str($this->codpostal) .
                    ", codpais = " . $this->var2str($this->codpais) .
                    ", codagente = " . $this->var2str($this->codagente) .
                    ", netosindto = " . $this->var2str($this->netosindto) .
                    ", neto = " . $this->var2str($this->neto) .
                    ", dtopor1 = " . $this->var2str($this->dtopor1) .
                    ", dtopor2 = " . $this->var2str($this->dtopor2) .
                    ", dtopor3 = " . $this->var2str($this->dtopor3) .
                    ", dtopor4 = " . $this->var2str($this->dtopor4) .
                    ", dtopor5 = " . $this->var2str($this->dtopor5) .
                    ", totaliva = " . $this->var2str($this->totaliva) .
                    ", total = " . $this->var2str($this->total) .
                    ", totaleuros = " . $this->var2str($this->totaleuros) .
                    ", irpf = " . $this->var2str($this->irpf) .
                    ", totalirpf = " . $this->var2str($this->totalirpf) .
                    ", porcomision = " . $this->var2str($this->porcomision) .
                    ", tasaconv = " . $this->var2str($this->tasaconv) .
                    ", totalrecargo = " . $this->var2str($this->totalrecargo) .
                    ", observaciones = " . $this->var2str($this->observaciones) .
                    ", pagada = " . $this->var2str($this->pagada) .
                    ", anulada = " . $this->var2str($this->anulada) .
                    ", retenida = " . $this->var2str($this->retenida) . 
                    ", hora = " . $this->var2str($this->hora) .
                    ", vencimiento = " . $this->var2str($this->vencimiento) .
                    ", femail = " . $this->var2str($this->femail) .
                    ", codtrans = " . $this->var2str($this->envio_codtrans) .
                    ", codigoenv = " . $this->var2str($this->envio_codigo) .
                    ", nombreenv = " . $this->var2str($this->envio_nombre) .
                    ", apellidosenv = " . $this->var2str($this->envio_apellidos) .
                    ", apartadoenv = " . $this->var2str($this->envio_apartado) .
                    ", direccionenv = " . $this->var2str($this->envio_direccion) .
                    ", codpostalenv = " . $this->var2str($this->envio_codpostal) .
                    ", ciudadenv = " . $this->var2str($this->envio_ciudad) .
                    ", provinciaenv = " . $this->var2str($this->envio_provincia) .
                    ", codpaisenv = " . $this->var2str($this->envio_codpais) .
                    ", idimprenta = " . $this->var2str($this->idimprenta) .
                    ", numdocs = " . $this->var2str($this->numdocs) .
                    ", clavesri = " . $this->var2str($this->clavesri) .   
                    ", estadosri = " . $this->var2str($this->estadosri) .   
                    ", clavesrirt = " . $this->var2str($this->clavesrirt) .   
                    ", estadosrirt = " . $this->var2str($this->estadosrirt) .
                    ", clavesrinc = " . $this->var2str($this->clavesrinc) .   
                    ", estadosrinc = " . $this->var2str($this->estadosrinc) .  
                    ", codvendedor = " . $this->var2str($this->codvendedor) .   
                    ", numnc = " . $this->var2str($this->numnc) .
                    ", numfact = " . $this->var2str($this->numfact) .
                    "  WHERE idfactura = " . $this->var2str($this->idfactura) . ";";
//$this->new_message(" sql actualizacion ".$sql);
                return $this->db->exec($sql);
            }

            $this->new_codigo();
            $sql = "INSERT INTO " . $this->table_name . " (idasiento,idasientop,idfacturarect,codigo,numero,
               codigorect,codejercicio,codserie,codalmacen,codpago,coddivisa,fecha,codcliente,
               nombrecliente,cifnif,direccion,ciudad,provincia,apartado,coddir,codpostal,codpais,
               codagente,netosindto,neto,dtopor1,dtopor2,dtopor3,dtopor4,dtopor5,totaliva,total,totaleuros,
               irpf,totalirpf,porcomision,tasaconv,totalrecargo,pagada,anulada,retenida,observaciones,hora,numero2,
               vencimiento,femail,codtrans,codigoenv,nombreenv,apellidosenv,apartadoenv,direccionenv,
               codpostalenv,ciudadenv,provinciaenv,codpaisenv,idimprenta,numdocs,clavesri,estadosri,clavesrirt,estadosrirt,clavesrinc,estadosrinc, codvendedor) VALUES ("
                . $this->var2str($this->idasiento) .
                "," . $this->var2str($this->idasientop) .
                "," . $this->var2str($this->idfacturarect) .
                "," . $this->var2str($this->codigo) .
                "," . $this->var2str($this->numero) .
                "," . $this->var2str($this->codigorect) .
                "," . $this->var2str($this->codejercicio) .
                "," . $this->var2str($this->codserie) .
                "," . $this->var2str($this->codalmacen) .
                "," . $this->var2str($this->codpago) .
                "," . $this->var2str($this->coddivisa) .
                "," . $this->var2str($this->fecha) .
                "," . $this->var2str($this->codcliente) .
                "," . $this->var2str($this->nombrecliente) .
                "," . $this->var2str($this->cifnif) .
                "," . $this->var2str($this->direccion) .
                "," . $this->var2str($this->ciudad) .
                "," . $this->var2str($this->provincia) .
                "," . $this->var2str($this->apartado) .
                "," . $this->var2str($this->coddir) .
                "," . $this->var2str($this->codpostal) .
                "," . $this->var2str($this->codpais) .
                "," . $this->var2str($this->codagente) .
                "," . $this->var2str($this->netosindto) .
                "," . $this->var2str($this->neto) .
                "," . $this->var2str($this->dtopor1) .
                "," . $this->var2str($this->dtopor2) .
                "," . $this->var2str($this->dtopor3) .
                "," . $this->var2str($this->dtopor4) .
                "," . $this->var2str($this->dtopor5) .
                "," . $this->var2str($this->totaliva) .
                "," . $this->var2str($this->total) .
                "," . $this->var2str($this->totaleuros) .
                "," . $this->var2str($this->irpf) .
                "," . $this->var2str($this->totalirpf) .
                "," . $this->var2str($this->porcomision) .
                "," . $this->var2str($this->tasaconv) .
                "," . $this->var2str($this->totalrecargo) .
                "," . $this->var2str($this->pagada) .
                "," . $this->var2str($this->anulada) .
                "," . $this->var2str($this->retenida) .
                "," . $this->var2str($this->observaciones) .
                "," . $this->var2str($this->hora) .
                "," . $this->var2str($this->numero2) .
                "," . $this->var2str($this->vencimiento) .
                "," . $this->var2str($this->femail) .
                "," . $this->var2str($this->envio_codtrans) .
                "," . $this->var2str($this->envio_codigo) .
                "," . $this->var2str($this->envio_nombre) .
                "," . $this->var2str($this->envio_apellidos) .
                "," . $this->var2str($this->envio_apartado) .
                "," . $this->var2str($this->envio_direccion) .
                "," . $this->var2str($this->envio_codpostal) .
                "," . $this->var2str($this->envio_ciudad) .
                "," . $this->var2str($this->envio_provincia) .
                "," . $this->var2str($this->envio_codpais) .
                "," . $this->var2str($this->idimprenta) .
                "," . $this->var2str($this->numdocs) . 
                "," . $this->var2str($this->clavesri) .
                "," . $this->var2str($this->estadosri) .
                "," . $this->var2str($this->clavesrirt) . 
                "," . $this->var2str($this->estadosrirt) .
                "," . $this->var2str($this->clavesrinc) . 
                "," . $this->var2str($this->estadosrinc) .
                "," . $this->var2str($this->codvendedor) .    ");";
                //$this->new_message(" sql actualizacion john li  ".$sql);
            if ($this->db->exec($sql)) {
                //
                $this->idfactura = $this->db->lastval();
                //$this->genera_xml_fun();
                //$this->new_message("id facturas cli  ".$this->idfactura);
                return TRUE;
            }
        }

        return FALSE;
    }
  



}
