<?php
include_once("../../../php/sessionStart.php"); 
include_once("../../../php/db/dbExec.php");
include_once('../../../php/maxExecTime.php');
include_once('../../../php/functions.php');
include_once("../../../php/fpdf/functions.php");

$empCod=utf8_decode($_SESSION["empCod"]);
$empNom=utf8_decode($_SESSION["empNom"]);
$empMoneda=utf8_decode($_SESSION["empMoneda"]);
$empTcam=utf8_decode($_SESSION["pTcam"]);

$txtCodp=$_GET["txtCodp"];
$dtFeci=$_GET["dtFeci"];
$dtFecf=$_GET["dtFecf"];
$crTmone=$_GET["crTmone"];
if ($crTmone == 'L') {
    $tipomon=$empMoneda;
} else {
    $tipomon='DOLARES';
}   

//$func = new functions();


$lineWidth=17;
$lineHeight=0.5;

class generatePDF extends PDF_MC_Table {
    function Header() {
        global $empNom, $lineHeight, $lineWidth, $dtFeci, $dtFecf, $tipomon;
        $this->SetMargins(1.5, 1, 2);
        $this->Cell(0, 0, "", 0, 1);

        $this->SetFont("Arial","B",12);
        $this->Cell($lineWidth,.7,$empNom,0,0,"L");

        $this->SetFont("Arial","I",8);
        $this->SetY(.7);
        $this->Cell(0,1,utf8_decode("PÁGINA ").$this->PageNo(),0,1,"R");

        $this->SetFont("","",9);
        $this->MultiAlignCell($lineWidth, $lineHeight, utf8_decode("ESTADO DE CUENTA DETALLADO CUENTAS POR COBRAR DEL ".strftime("%d/%m/%Y", strtotime($dtFeci))." AL ".strftime("%d/%m/%Y", strtotime($dtFecf))),0,1,"L");
        $this->SetFont("","B",8);        
        $this->SetFont("","",7);        

        $this->MultiAlignCell($lineWidth, $lineHeight, utf8_decode("CIFRAS EXPRESADAS EN ").$tipomon,0,1,"L");
        $this->SetFont("");
        $this->SetAligns(array("L","L","C","C","C","R","R","R","R","R"));
    }
    
    function Footer() {
        // Posición: a 1,5 cm del final
        //$this->SetY(-2.5);
        //$this->SetFont("Arial","I",8);
        //$this->Cell(0,1,"PAGINA ".$this->PageNo(),0,0,"C");
    }
}


# QUERYS
if ($txtCodp !='ZZZZ') {
    $sDoctoscc = "SELECT *, TRIM(dc_clien) AS dc_clien, TRIM(dc_codp) AS dc_codp, TRIM(dc_nit) AS dc_nit, (dc_tot-(dc_abo+dc_ret+dc_reti)) AS dc_saldod, TRIM(cl.cli_clas) AS dc_clas, TRIM(cla.cla_nom) AS cla_nom FROM doctoscc dc 
        LEFT JOIN cliencc cl ON dc.dc_emp=cl.cli_emp and dc.dc_codp=cl.cli_cod 
        LEFT JOIN clasic cla ON cl.cli_clas=cla.cla_cod
        WHERE dc_emp='$empCod' and dc_fec>='$dtFeci' and dc_fec<='$dtFecf' and dc_codp='$txtCodp' ORDER BY cli_clas,cli_nom,dc_fec";

    function sAbonosc($codp,$tipod,$seried,$numd) { 
        global $empCod, $dtFeci, $dtFecf;
        return "SELECT * FROM movicc mc LEFT JOIN tipoaboc ta ON mc.mov_tipo=ta.ta_cod WHERE mov_emp='$empCod' and mov_fec<='$dtFecf' and mov_codp='$codp' and mov_tipoc='$tipod' and mov_seriec='$seried' and mov_numc='$numd'";
    }    
    function sAnticpc($codp) { 
        global $empCod, $dtFeci, $dtFecf;
        return "SELECT * FROM anticpc WHERE ant_emp='$empCod' and ant_fec>='dtFeci' and ant_fec<='$dtFecf' and ant_codp='$codp' and ant_tot>ant_totapli";
    }    

} else {
    $sDoctoscc = "SELECT *, TRIM(dc_clien) AS dc_clien, TRIM(dc_codp) AS dc_codp, TRIM(dc_nit) AS dc_nit, (dc_tot-(dc_abo+dc_ret+dc_reti)) AS dc_saldod, TRIM(cl.cli_clas) AS dc_clas, TRIM(cla.cla_nom) AS cla_nom FROM doctoscc dc 
        LEFT JOIN cliencc cl ON dc.dc_emp=cl.cli_emp and dc.dc_codp=cl.cli_cod 
        LEFT JOIN clasic cla ON cl.cli_clas=cla.cla_cod
        WHERE dc_emp='$empCod' and dc_fec>='$dtFeci' and dc_fec<='$dtFecf' ORDER BY cli_clas,cli_nom,dc_fec";

    function sAbonosc($codp,$tipod,$seried,$numd) { 
        global $empCod, $dtFeci, $dtFecf;
        return "SELECT * FROM movicc mc LEFT JOIN tipoaboc ta ON mc.mov_tipo=ta.ta_cod WHERE mov_emp='$empCod' and mov_fec<='$dtFecf' and mov_codp='$codp' and mov_tipoc='$tipod' and mov_seriec='$seried' and mov_numc='$numd'";
    }
    function sAnticpc($codp) { 
        global $empCod, $dtFeci, $dtFecf;
        return "SELECT * FROM anticpc WHERE ant_emp='$empCod' and ant_fec>='dtFeci' and ant_fec<='$dtFecf' and ant_codp='$codp' and ant_tot>ant_totapli";
    }    
}    
# EJECUCION DE QUERYS
$db = new dbExec();
$lineHeight=0.35;
$select["doctoscc"] = $db->query($sDoctoscc);

# GENERAR PDF
$pdf = new generatePDF("P","cm", array(22, 28));
$pdf->AddPage();

$func = new functions();

$ti_clasi="XXXZZZ999";
$totcargos=0;
$totret=0;
$totreti=0;
$totabonos=0;
$t_lini=1;
$codp="";
$ti_codp="XXZZZ999";
$nomp="";
$clas="";
$clasnom="";
$saldoact=0;

$arrayProv = array();

while ($rec = $db->fetchAssoc($select["doctoscc"])) {
    if ($t_lini == 1) {
        //$pdf->SetFont("","B",8);        
        $pdf->MultiAlignCell($lineWidth, $lineHeight, utf8_decode("CLIENTE: ".$rec["dc_codp"]."-".$rec["cli_nom"]),0,1,"L");
        $pdf->MultiAlignCell($lineWidth, $lineHeight, utf8_decode("DIRECCION: ".$rec["cli_dir"]),0,1,"L");
        $pdf->MultiAlignCell($lineWidth, $lineHeight, utf8_decode("NIT: ".$rec["cli_nit"]."         TELEFONO: ".$rec["cli_tel"]),0,1,"L");
        $pdf->SetFont("","",7);        
        $header = array("SERIE","NUMERO","FEC/DOC","FEC/VENCE","D/VENCIDO","CARGOS","ABONOS","RET/ISR","RET/IVA","SALDO");
        $pdf->SetWidths(array(2,2,1.5,1.8,1.8,2,2,1.7,1.7,2));
        $pdf->SetAligns(array("C","C","C","C","C","C","C","C","C","C"));
        $pdf->Row($header, $lineHeight); 
        $pdf->SetFont("");
        $pdf->SetAligns(array("L","L","C","C","C","R","R","R","R","R"));

        $codp=$rec["dc_codp"];
        $nomp=$rec["cli_nom"];
        $clas=$rec["cli_clas"];
        $clasnom=$rec["cla_nom"];
        //$t_lini=2;
    }
    if ($ti_codp!=$rec["dc_codp"]) {
        if ($t_lini > 1) {
            // Para mostrar anticipos
            $select["anticpc"] = $db->query(sAnticpc($codp));
            while ($recanti = $db->fetchAssoc($select["anticpc"])) {
                $vanti=$recanti["ant_tot"]-$recanti["ant_totapli"];
                $fecanti=$recanti["ant_fec"];
                $tcamanti=$recanti["ant_tcam"];
                $diff=$func->dateDiff($dtFecf, $fecanti);
                $dias=($diff->invert == 1) ? '-'.$diff->days : $diff->days;
                if ($vanti>0) {
                    if ($crTmone == 'L' && $tcamanti>1) {
                        $vanti=round($vanti*$tcamanti,2);
                    }
                    if ($crTmone == 'E' && $tcamanti == 1) {
                        $vanti=round($vanti/$empTcam,2);
                    }
                }
                $abono=$vanti;
                $totabonos+=$vanti;
                $saldoact = $saldoact-$abono;
                $body = array(
                    "ANTICIPO",
                    trim($recanti["ant_num"]),
                    strftime("%d/%m/%Y", strtotime($recanti["ant_fec"])),
                    strftime("%d/%m/%Y", strtotime($recanti["ant_fec"])),
                    $dias,        
                    "",        
                    (round($abono, 2) != 0) ? number_format($abono, 2, '.', ',') : "",        
                    "",        
                    "",        
                    (round($saldoact, 2) != 0) ? number_format($saldoact, 2, '.', ',') : "",        
                ); 
                $pdf->RowBorderHidden($body, $lineHeight);
            }
            //$pdf->ln();
            $pdf->line($pdf->GetX()+0, $pdf->GetY(), 20, $pdf->GetY());
            $pdf->Cell(.04,.4,"          TOTAL ESTE CLIENTE",0,0,"L");
            $body = array(
                "",
                "",
                "",
                "",
                "",
                number_format($totcargos, 2, '.', ','),
                number_format($totabonos, 2, '.', ','),
                number_format($totret, 2, '.', ','),
                number_format($totreti, 2, '.', ','),
                number_format($saldoact, 2, '.', ','),
            ); 
            $pdf->RowBorderHidden($body, $lineHeight);
            $pdf->line($pdf->GetX()+0, $pdf->GetY(), 20, $pdf->GetY());
            $pdf->AddPage();
            //$pdf->SetFont("","B",8);        
            $pdf->MultiAlignCell($lineWidth, $lineHeight, utf8_decode("CLIENTE: ".$rec["dc_codp"]."-".$rec["cli_nom"]),0,1,"L");
            $pdf->MultiAlignCell($lineWidth, $lineHeight, utf8_decode("DIRECCION: ".$rec["cli_dir"]),0,1,"L");
            $pdf->MultiAlignCell($lineWidth, $lineHeight, utf8_decode("NIT: ".$rec["cli_nit"]."         TELEFONO: ".$rec["cli_tel"]),0,1,"L");
            $pdf->SetFont("","",7);        
            $header = array("SERIE","NUMERO","FEC/DOC","FEC/VENCE","D/VENCIDO","CARGOS","ABONOS","RET/ISR","RET/IVA","SALDO");
            $pdf->SetWidths(array(2,2,1.5,1.8,1.8,2,2,1.7,1.7,2));
            $pdf->SetAligns(array("C","C","C","C","C","C","C","C","C","C"));
            $pdf->Row($header, $lineHeight); 
            $pdf->SetFont("");
            $pdf->SetAligns(array("L","L","C","C","C","R","R","R","R","R"));
        }             
        $totcargos=0;
        $totabonos=0;
        $totret=0;
        $totreti=0;
        $saldoact=0;
        $codp=$rec["dc_codp"];
        $ti_codp=$rec["dc_codp"];
        $nomp=$rec["cli_nom"];

        /*$pdf->SetFont("Arial","B",8);
        $pdf->Cell($lineWidth,.7,$codp."-".$nomp,0,1,"L");
        $pdf->SetFont("","",7); */
        $t_lini=2;
    } 


    $codp=$rec["dc_codp"];
    $clas=$rec["cli_clas"];
    $tipod=$rec["dc_tipo"];
    $seried=$rec["dc_serie"];
    $numd=$rec["dc_num"];
    $fec=$rec["dc_fec"];
    $fecp=$rec["dc_fecp"];
    $tcam=$rec["dc_tcam"];
    $tot=$rec["dc_tot"];
    $ret=$rec["dc_ret"];
    $reti=$rec["dc_reti"];
    if ($tot>0) {
        if ($crTmone == 'L' && $tcam>1) {
            $tot=round($tot*$tcam,2);
            $ret=round($ret*$tcam,2);
            $reti=round($reti*$tcam,2);
        }
        if ($crTmone == 'E' && $tcam == 1) {
            $tot=round($tot/$empTcam,2);
            $ret=round($ret/$empTcam,2);
            $reti=round($reti/$empTcam,2);
        }
    } else {
        continue;
    }

    // Para saber cuantos dias
    $diff=$func->dateDiff($dtFecf, $fecp);
    $dias=($diff->invert == 1) ? '-'.$diff->days : $diff->days;

    $saldoact = ($saldoact+$tot)-($ret+$reti);

    $totcargos += $tot;
    $totret += $ret;
    $totreti += $reti;

    $body = array(
        $rec["dc_serie"],
        trim($rec["dc_num"]),
        strftime("%d/%m/%Y", strtotime($fec)),
        strftime("%d/%m/%Y", strtotime($fecp)),
        $dias,        
        (round($tot, 2) != 0) ? number_format($tot, 2, '.', ',') : "",        
        "",        
        (round($ret, 2) != 0) ? number_format($ret, 2, '.', ',') : "",        
        (round($reti, 2) != 0) ? number_format($reti, 2, '.', ',') : "",        
        (round($saldoact, 2) != 0) ? number_format($saldoact, 2, '.', ',') : "",        
    ); 
    $pdf->RowBorderHidden($body, $lineHeight);
    if (($pdf->GetY()+$lineHeight) > 25) {
        $pdf->AddPage();
        $pdf->MultiAlignCell($lineWidth, $lineHeight, utf8_decode("CLIENTE: ".$rec["dc_codp"]."-".$rec["cli_nom"]),0,1,"L");
        $pdf->MultiAlignCell($lineWidth, $lineHeight, utf8_decode("DIRECCION: ".$rec["cli_dir"]),0,1,"L");
        $pdf->MultiAlignCell($lineWidth, $lineHeight, utf8_decode("NIT: ".$rec["cli_nit"]."         TELEFONO: ".$rec["cli_tel"]),0,1,"L");
        $pdf->SetFont("","",7);        
        $header = array("SERIE","NUMERO","FEC/DOC","FEC/VENCE","D/VENCIDO","CARGOS","ABONOS","RET/ISR","RET/IVA","SALDO");
        $pdf->SetWidths(array(2,2,1.5,1.8,1.8,2,2,1.7,1.7,2));
        $pdf->SetAligns(array("C","C","C","C","C","C","C","C","C","C"));
        $pdf->Row($header, $lineHeight); 
        $pdf->SetFont("");
        $pdf->SetAligns(array("L","L","C","C","C","R","R","R","R","R"));
    }    

    $sumabo=0;
    $select["movicc"] = $db->query(sAbonosc($codp,$tipod,$seried,$numd));
    //$fetchAssoc["movic"] = $db->sFetchAssoc(sAbonos($codp));
    while ($recabo = $db->fetchAssoc($select["movicc"])) {
        $vabo=$recabo["mov_abo"];
        $tcamabo=$recabo["mov_tcam"];
        if ($vabo>0) {
            if ($crTmone == 'L' && $tcamabo>1) {
                $vabo=round($vabo*$tcamabo,2);
            }
            if ($crTmone == 'E' && $tcamabo == 1) {
                $vabo=round($vabo/$empTcam,2);
            }
            $sumabo += $vabo;
        }
        $totabonos += $vabo;
        $sumabo+= $vabo;
        $saldoact = ($saldoact-$vabo);
        $body = array(
            trim($recabo["ta_nom"]),
            trim($recabo["mov_num"]),
            strftime("%d/%m/%Y", strtotime($recabo["mov_fec"])),
            "",
            "",
            "",
            (round($vabo, 2) != 0) ? number_format($vabo, 2, '.', ',') : "",        
            "",        
            "",        
            (round($saldoact, 2) != 0) ? number_format($saldoact, 2, '.', ',') : "",        
        ); 
        $pdf->RowBorderHidden($body, $lineHeight);
        if (($pdf->GetY()+$lineHeight) > 19) {
            $pdf->AddPage();
            $pdf->MultiAlignCell($lineWidth, $lineHeight, utf8_decode("CLIENTE: ".$rec["dc_codp"]."-".$rec["cli_nom"]),0,1,"L");
            $pdf->MultiAlignCell($lineWidth, $lineHeight, utf8_decode("DIRECCION: ".$rec["cli_dir"]),0,1,"L");
            $pdf->MultiAlignCell($lineWidth, $lineHeight, utf8_decode("NIT: ".$rec["cli_nit"]."         TELEFONO: ".$rec["cli_tel"]),0,1,"L");
            $pdf->SetFont("","",7);        
            $header = array("SERIE","NUMERO","FEC/DOC","FEC/VENCE","D/VENCIDO","CARGOS","ABONOS","RET/ISR","RET/IVA","SALDO");
            $pdf->SetWidths(array(2,2,1.5,1.8,1.8,2,2,1.7,1.7,2));
            $pdf->SetAligns(array("C","C","C","C","C","C","C","C","C","C"));
            $pdf->Row($header, $lineHeight); 
            $pdf->SetFont("");
            $pdf->SetAligns(array("L","L","C","C","C","R","R","R","R","R"));
        }    
    }
    if ($sumabo>0) {
      $pdf->ln(); 
    }
}
// Para mostrar anticipos
$select["anticpc"] = $db->query(sAnticpc($codp));
while ($recanti = $db->fetchAssoc($select["anticpc"])) {
    $vanti=$recanti["ant_tot"]-$recanti["ant_totapli"];
    $fecanti=$recanti["ant_fec"];
    $tcamanti=$recanti["ant_tcam"];
    $diff=$func->dateDiff($dtFecf, $fecanti);
    $dias=($diff->invert == 1) ? '-'.$diff->days : $diff->days;
    if ($vanti>0) {
        if ($crTmone == 'L' && $tcamanti>1) {
            $vanti=round($vanti*$tcamanti,2);
        }
        if ($crTmone == 'E' && $tcamanti == 1) {
            $vanti=round($vanti/$empTcam,2);
        }
    }
    $totabonos+=$vanti;
    $saldoact = $saldoact-$vanti;
    $body = array(
        "ANTICIPO",
        trim($recanti["ant_num"]),
        strftime("%d/%m/%Y", strtotime($recanti["ant_fec"])),
        strftime("%d/%m/%Y", strtotime($recanti["ant_fec"])),
        $dias,        
        "",        
        (round($vanti, 2) != 0) ? number_format($vanti, 2, '.', ',') : "",        
        "",        
        "",        
        (round($saldoact, 2) != 0) ? number_format($saldoact, 2, '.', ',') : "",        
    ); 
    $pdf->RowBorderHidden($body, $lineHeight);
}
//$pdf->ln();
$pdf->line($pdf->GetX()+0, $pdf->GetY(), 20, $pdf->GetY());
$pdf->Cell(.04,.4,"          TOTAL ESTE CLIENTE",0,0,"L");
$body = array(
    "",
    "",
    "",
    "",
    "",
    number_format($totcargos, 2, '.', ','),
    number_format($totabonos, 2, '.', ','),
    number_format($totret, 2, '.', ','),
    number_format($totreti, 2, '.', ','),
    number_format($saldoact, 2, '.', ','),
); 
$pdf->RowBorderHidden($body, $lineHeight);
$pdf->line($pdf->GetX()+0, $pdf->GetY(), 20, $pdf->GetY());


$pdf->Output(utf8_decode("Estado Cuenta CxC" ).".pdf","I");

$db->close();

?>