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

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

$selMes=$_GET["selMes"];
$numAno=$_GET["numAno"];
$txtFecl=$_GET["txtFecl"];
$txtTitulo=$_GET["txtTitulo"];
$numHoja=$_GET["numHoja"];
$crMoneda=$_GET["crMoneda"];
$textoMoneda=$_GET["textoMoneda"];
$cbFecsn=$_GET["cbFecsn"];
$cbNoFol=$_GET["cbNoFol"];
$ultimoDia=$_GET["ultimoDia"];


$lineWidth=18;
$lineHeight=0.35;

class generatePDF extends PDF_MC_Table {
    function Header() {
        global $empNom, $empNomc, $txtTitulo, $txtFecl, $textoMoneda, $cbNoFol, $numHoja, $lineWidth, $lineHeight;
        $this->SetMargins(2, 1, 2);

        $func = new functions();
        $this->SetFont("Arial","",9);
        $this->Cell(0, 0, "", 0, 1);
        $this->MultiAlignCell($lineWidth, $lineHeight, $empNom,0,1,"C");
        $this->MultiAlignCell($lineWidth, $lineHeight, $empNomc,0,1,"C");
        if ($func->stringToBool($cbNoFol)) {
            $this->SetFont("Arial","I",8);
            $this->SetY(.9);
            $this->Cell(0,1, utf8_decode("Folio: ".((string)($this->PageNo())+$numHoja)),0,1,"R");
        }
        $this->MultiAlignCell($lineWidth, $lineHeight, utf8_decode($txtTitulo),0,1,"C");
        $this->MultiAlignCell($lineWidth, $lineHeight, utf8_decode("Al ".$txtFecl),0,1,"C");
        $this->MultiAlignCell($lineWidth, $lineHeight, utf8_decode("Cifras Expresadas en ".$textoMoneda),0,1,"C");

        $this->Ln($lineHeight);

        $this->SetFont("","B",8);
        $header = array("Cuenta","Nombre de Cuenta","Saldo Inicial","Debe Mes", "Haber Mes", "Saldo Mes", "Saldo Actual");
        $this->SetWidths(array(2,5,2.2,2.2,2.2,2.2,2.2));
        $this->SetAligns(array("C","C","C","C","C","C","C"));
        $this->Row($header, $lineHeight);

        $this->SetFont("","B",8);        
        $header = array("No.Docto","Tipo","Fecha","Concepto","Debe","Haber","Saldo");
        $this->SetFont("","B");
        $this->SetWidths(array(2,1,1.5,7.3,2,2,2));
        $this->SetAligns(array("C","C","C","C","C","C","C"));
        $this->Row($header, $lineHeight);
    }
    
    function Footer() {
        global $cbFecsn;
        // Posición: a 1,5 cm del final
        $func = new functions();
        $this->SetY(-2);
        $this->SetFont("Arial","I",7);
        if ($func->stringToBool($cbFecsn)) {
            $this->Cell(0,1,strftime("%d/%m/%Y %T"),0,0,"L");
        }
    }
}
# QUERYS
$sCierres = "SELECT
                c.cie_mes,
                cta.cta_niv,
                cta.cta_con,
                TRIM(c.cie_cta) AS cie_cta,
                TRIM(cta.cta_nom) AS cta_nom,
                TRIM(cta.cta_acta) AS cta_acta,
                (0) AS salIni,
                c.cie_mdebe,
                c.cie_mhaber,
                (SUM(cie_mdebe)-SUM(cie_mhaber)) AS salMes
            FROM cierres c 
            INNER JOIN cuentas cta ON c.cie_emp=cta.cta_emp AND c.cie_cta=cta.cta
            WHERE c.cie_emp='$empCod' AND c.cie_ano=$numAno AND c.cie_mes<=$selMes
            GROUP BY c.cie_cta, cie_mes=$selMes";

function sPoliDet($cta) { 
    global $empCod,$selMes,$numAno;
    return "SELECT *,
            TRIM(pd.pold_cta) AS pold_cta,
            TRIM(pd.pold_ctan) AS pold_ctan,
            TRIM(p.pol_con) AS pol_con,
            SUM(pold_debe) AS pold_debe,
            SUM(pold_haber) AS pold_haber
            FROM poli_det pd LEFT JOIN polizas p ON pd.pold_emp=p.pol_emp AND pd.pold_ban=p.pol_ban AND pd.pold_tipo=p.pol_tipo AND pd.pold_fec=p.pol_fec AND pd.pold_num=p.pol_num AND pd.pold_tipoi=p.pol_tipoi AND pd.pold_nit=p.pol_nit WHERE pd.pold_emp='$empCod' AND pd.pold_cta='$cta' AND YEAR(pd.pold_fec)='$numAno' AND MONTH(pd.pold_fec)='$selMes' GROUP BY pd.pold_tipo, pd.pold_cta";
}


# EJECUCION DE QUERYS
$db = new dbExec();
$select["cierres"] = $db->query($sCierres);

$arrayCie=$db->fetchAll($select["cierres"]);

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

$func = new functions();

$totCta = "";
$totSalIni = 0;
$totDebe = 0;
$totHaber = 0;
$totSalMes = 0;
$totSalAct = 0;

$totDebeMov = 0;
$totHaberMov = 0;

$ctaPrinAnt=1;
$ctaNivAnt=1;

$salIni=0;
$k=0;
foreach ($arrayCie as $rec) {
    $rec["salIni"]=$salIni;
    $k++;
    if ($rec["cie_mes"]!=$selMes) {
        $salIni=$rec["salMes"];

        if ($k<sizeof($arrayCie)) {
            if ($arrayCie[$k]["cie_cta"]==$rec["cie_cta"]){
                continue;
            }
        }
        $rec["salIni"]=$salIni;
    }

    $cta=$rec["cie_cta"];
    if ($rec["salIni"]!=0 || $rec["cie_mdebe"]!=0 || $rec["cie_mhaber"]!=0) {

        // MES NO TRABAJADO
        if ($rec["cie_mes"]!=$selMes) {
            $rec["cie_mdebe"]=0;
            $rec["cie_mhaber"]=0;
            $rec["salMes"]=0;
        }

        $salAct=($rec["salIni"]+$rec["cie_mdebe"])-$rec["cie_mhaber"];

        // PARA INVERTIR SIGNOS
        //if ($rec["cie_cta"][0] == "2" || $rec["cie_cta"][0] == "3" || $rec["cie_cta"][0] == "4") {
        //    $rec["salIni"]*=(-1);
        //    $rec["salMes"]*=(-1);
        //    $salAct*=(-1);
        //}

        // TASA DE CAMBIO
        if ($crMoneda != "L") {
            $rec["salIni"]/=$pTcam;
            $rec["cie_mdebe"]/=$pTcam;
            $rec["cie_mhaber"]/=$pTcam;
            $rec["salMes"]/=$pTcam;
            $salAct/=$pTcam;
        }
        

        $pdf->SetFont("","B",8);
        $pdf->SetWidths(array(2,5,2.2,2.2,2.2,2.2,2.2));
        $pdf->SetFont("");
        $pdf->SetAligns(array("L","L","R","R","R","R","R"));

        // AGREGA FILA CUENTAS
        if ($rec["cta_niv"]!=$ctaNivAnt) {
            $pdf->Ln();
        }
        $body = array(
            $rec["cie_cta"],
            $rec["cta_nom"],
            (round($rec["salIni"], 2) != 0) ? number_format($rec["salIni"], 2, '.', ',') : "",
            (round($rec["cie_mdebe"], 2) != 0) ? number_format($rec["cie_mdebe"], 2, '.', ',') : "",
            (round($rec["cie_mhaber"], 2) != 0) ? number_format($rec["cie_mhaber"], 2, '.', ',') : "",
            (round($rec["salMes"], 2) != 0) ? number_format($rec["salMes"], 2, '.', ',') : "",
            (round($salAct, 2) != 0) ? number_format($salAct, 2, '.', ',') : ""
        );
        $pdf->RowBorderHidden($body, $lineHeight);
        

        if ($rec["cta_con"]=="N") {
            //$pdf->Ln();
            $pdf->line($pdf->GetX()+0, $pdf->GetY(), 20, $pdf->GetY());
          } else {
            $pdf->Ln();
        }


        $ctaPrinAnt=$rec["cie_cta"][0];
        $ctaNivAnt=$rec["cta_niv"];


        $debe = 0;
        $haber = 0;
        $Saldo = $salIni;
        if ($crMoneda != "L") {
            $Saldo/=$pTcam;
        }
        $linea=1;

        # CREA EL CICLO PARA EL LISTADO DE MOVIMIENTOS DE LA CUENTA

        $select["poli_det"] = $db->query(sPoliDet($cta));


        while ($recPd = $db->fetchAssoc($select['poli_det'])) {
            // TASA DE CAMBIO
            if ($crMoneda != "L") {
                $recPd["pold_debe"]/=$pTcam;
                $recPd["pold_haber"]/=$pTcam;
            }
            $debe += $recPd["pold_debe"];
            $haber += $recPd["pold_haber"];
            $totDebe += $recPd["pold_debe"];
            $totHaber += $recPd["pold_haber"];
            $Saldo = ($Saldo+$recPd["pold_debe"])-$recPd["pold_haber"];
            $body = array(
                "999999",
                $recPd["pold_tipo"],
                strftime("%d/%m/%Y", strtotime($ultimoDia)),
                "MOVIMIENTO DEL MES",
                (round($recPd["pold_debe"],2) != 0) ? number_format($recPd["pold_debe"], 2, '.', ',') : "",
                (round($recPd["pold_haber"],2) != 0) ? number_format($recPd["pold_haber"], 2, '.', ',') : "",
                number_format($Saldo, 2, '.', ','),
            );
            $pdf->SetFont("", "", 7);
            $pdf->SetWidths(array(2,1,1.5,7.3,2,2,2));
            $pdf->SetAligns(array("L","L","L","L","R","R","R")); 
            $pdf->RowBorderHidden($body, $lineHeight);

            $linea=2;
            if (($pdf->GetY()+$lineHeight) > 25) {
                $pdf->AddPage();
            }
        }

        if ($linea!=1) {
            $pdf->Ln();
        }

        $salIni=0;

        if (($pdf->GetY()+$lineHeight) > 25) {
            $pdf->AddPage();
        }
    }
}


// TOTALES DEL MOVIMIENTO
$pdf->Ln();
$pdf->line($pdf->GetX()+7, $pdf->GetY(), 20, $pdf->GetY());
$body = array(
    "",
    "",
    "",
    "SUMA DEL MOVIMIENTO",
    ($totDebe != 0) ? number_format($totDebe, 2, '.', ',') : "",
    ($totHaber != 0) ? number_format($totHaber, 2, '.', ',') : "",
    "",
    ""
);
$pdf->RowBorderHidden($body, $lineHeight);


$db->close();
ob_end_clean();
ob_start();
$pdf->Output(utf8_decode("Diario Mayor General Resumido").".pdf","I"); 
//echo sPoliDet("1110102");
?>