<?php

class Facturacion_model extends Databases {

    private $db = DB_NAME_HEAD;
    protected $token = false;

    public function obtenerRemitosSinFacturar($idEmpresaSolicitante, $idCliente) {
        $whereCliente = ($idCliente > -1) ? "AND C.COD = {$idCliente}" : '';

        $sql = "
                SELECT MF.EMP, MF.TIP, MF.SUC, MF.NCO, MF.FEC, C.NOM, MF.TOT, V.NOM AS NOMVEN, MFP.BOE, MFP.COLA, 0 AS RES
                FROM {$this->db}.dbo.AMAEFACT MF
                LEFT JOIN {$this->db}.dbo.CLIENTES C ON C.COD = MF.CLI
                LEFT JOIN {$this->db}.dbo.VENDEDORES V ON V.COD = MF.VEN AND V.EMP = MF.EMP
                LEFT JOIN {$this->db}.dbo.AMAEFACT_PRESU MFP
                    ON      MFP.SUC = MF.SUC
                        AND MFP.NCO = MF.NCO
                        AND MFP.TIP = MF.TIP COLLATE SQL_Latin1_General_CP1_CI_AS
                        AND MFP.TCO = MF.TCO COLLATE SQL_Latin1_General_CP1_CI_AS
                WHERE   MF.TCO = 'RE'
                    AND (
                        SELECT COUNT(1) FROM {$this->db}.dbo.AFACTRE
                        WHERE   TIP = MF.TIP COLLATE SQL_Latin1_General_CP1_CI_AS
                            AND TCO = MF.TCO COLLATE SQL_Latin1_General_CP1_CI_AS
                            AND SUC = MF.SUC
                            AND NCO = MF.NCO
                    ) = 0
                    AND MF.EMP <> {$idEmpresaSolicitante}
                    {$whereCliente}
            ";
        $data = parent::query($sql);
        return ($data && count($data) > 0) ? $data : FALSE;
    }
    
    public function getFacturasPendientes($idCliente) {
        //solo hasta 20 registros
        $sql = "
            SELECT TOP 20 A.TIP, A.TCO, A.SUC, A.NCO, A.TOT, A.FEC FROM {$this->db}.dbo.AMAEFACT A
            INNER JOIN {$this->db}.dbo.TICOMP T ON (A.TCO=T.COD AND T.TIP=1)
            LEFT JOIN {$this->db}.dbo.ACOBYPAG P ON (A.EMP=P.EMP AND A.TIP=P.TIP AND A.TCO=P.TCO AND A.SUC=P.SUC AND A.NCO=P.NCO)
            WHERE A.CLI={$idCliente} AND  A.TOT-ISNULL(P.IPA, 0)-(ISNULL((SELECT TOT+PER FROM {$this->db}.dbo.A_DET_DESCUENTO D WHERE A.EMP=D.EMP AND A.TIP=D.TIP COLLATE Modern_Spanish_CI_AS AND A.TCO=D.TCO COLLATE Modern_Spanish_CI_AS AND A.SUC=D.SUC AND A.NCO=D.NCO), 0)) > 1
            ORDER BY FEC ASC
            ";
        $data = parent::query($sql);
        return ($data && count($data) > 0) ? $data : FALSE;
    }

}
