<?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"];
$selNiv=$_GET["selNiv"];
$numHoja=$_GET["numHoja"];
$crMoneda=$_GET["crMoneda"];
$textoMoneda=$_GET["textoMoneda"];
$cbFecsn=$_GET["cbFecsn"];
$cbNoFol=$_GET["cbNoFol"];
$txtLeyenda=$_GET["txtLeyenda"];

$tipoCierre="099";

$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(.7);
            $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("","",8);
        $this->SetWidths(array(9.2,2.2,2.2,2.2,2.2,2.2));
        $this->SetAligns(array("L","R","R","R","R"));
    }
    
    function Footer() {
        global $cbFecsn;
        // Posición: a 1,5 cm del final
        $func = new functions();
        $this->SetY(-2);
        $this->SetFont("Arial","I",8);
        if ($func->stringToBool($cbFecsn)) {
            $this->Cell(0,1,strftime("%d/%m/%Y %T"),0,0,"C");
        }
    }
}

# 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 AND LEFT(c.cie_cta, 1)>3
            GROUP BY c.cie_cta, cie_mes=$selMes";

$sPoliDet = "SELECT 
                TRIM(p.pold_cta) AS pold_cta,
                pold_debe,
                pold_haber
            FROM poli_det p
            INNER JOIN cuentas cta ON p.pold_emp=cta.cta_emp AND p.pold_cta=cta.cta
            WHERE pold_emp='$empCod' AND YEAR(pold_fec)=$numAno AND pold_tipo='$tipoCierre' AND LEFT(p.pold_cta, 1)>3
            GROUP BY p.pold_cta";

function sCuentas($cta) { 
    global $empCod;
    return "SELECT TRIM(cta_acta) AS cta_acta FROM cuentas WHERE cta_emp='$empCod' AND cta='$cta'";
}

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

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

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

$func = new functions();
// RESTAR POLIZA DE CIERRE
if ($selMes==12) {
    while ($rec = $db->fetchAssoc($select['poli_det'])) {
        $cta = $rec["pold_cta"];
        while (!empty($cta)) {
            $fetchAssoc["cuentas"] = $db->sFetchAssoc(sCuentas($cta));
            $ctaActa = trim($fetchAssoc["cuentas"]["cta_acta"]);
            
            $i = $func->multiSearch($arrayCie, array('cie_cta' => $cta, 'cie_mes' => $selMes));
            $arrayCie[$i]["cie_mdebe"]-=$rec["pold_debe"];
            $arrayCie[$i]["cie_mhaber"]-=$rec["pold_haber"];
            $arrayCie[$i]["salMes"]=$arrayCie[$i]["cie_mdebe"]-$arrayCie[$i]["cie_mhaber"];

            $cta = $ctaActa;
        }
    }
}

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

$totSalIniMov = 0;
$totDebeMov = 0;
$totHaberMov = 0;
$totSalMesMov = 0;
$totSalActMov = 0;

$totBloque=0;

$ctaPrinAnt=4;
$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;
    }
    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"];

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

        // ACUMULAR VALORES PARA TOTALES
        if ($rec["cta_niv"]==1) {
            $totSalIniMov += $rec["salIni"];
            $totDebeMov += $rec["cie_mdebe"];
            $totHaberMov += $rec["cie_mhaber"];
            $totSalMesMov += $rec["salMes"];
            $totSalActMov += $salAct;
        }

        // 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);
        }

        if ($rec["cta_con"]=="S") {
            $pdf->SetFont("","B",8);
            $pdf->SetY($pdf->GetY()-.35);         
            $body = array(
                "",
                "",
                (round($totBloque, 2) != 0) ? number_format($totBloque, 2, '.', ',') : "",
                "",
                ""
            );
            $pdf->RowBorderHidden($body, $lineHeight);
            $totBloque=0;
            $pdf->SetFont("","",8);
        }

        // AGREGA FILA TOTALES
        if ($rec["cie_cta"][0]!=$ctaPrinAnt && $rec["cta_niv"]==1) {
            $pdf->SetFont("","B",8);
            $pdf->Ln(.5);
            $pdf->line($pdf->GetX()+15.8, $pdf->GetY(), 20, $pdf->GetY());
            $body = array(
                "TOTAL DE ".$totCta,
                "",
                "",
                "",
                (round($totSalAct, 2) != 0) ? number_format($totSalAct, 2, '.', ',') : ""
            );
            $pdf->RowBorderHidden($body, $lineHeight);
            $pdf->line($pdf->GetX()+15.8, $pdf->GetY(), 20, $pdf->GetY());
            $pdf->Ln();
            $pdf->SetFont("","",8);
        }

        // AGREGA FILA CUENTAS
        if ($rec["cta_niv"]<=$selNiv) {
            if ($rec["cta_niv"]!=$ctaNivAnt) {
                $pdf->Ln();
            }

            if ($rec["cta_con"]=="N") {
                $body = array(
                    $rec["cta_nom"],
                    (round($salAct, 2) != 0) ? number_format($salAct, 2, '.', ',') : "",
                    "",
                    "",
                    ""
                );
                $pdf->RowBorderHidden($body, $lineHeight);
                $totBloque+=$salAct;
            } elseif ($rec["cta_con"]=="S" && $rec["cta_niv"]>2) {
                $body = array(
                    $rec["cta_nom"],
                    "",
                    "",  //(round($salAct, 2) != 0) ? number_format($salAct, 2, '.', ',') : 
                    "",
                    ""
                );
                $pdf->RowBorderHidden($body, $lineHeight);
            } elseif ($rec["cta_con"]=="S" && $rec["cta_niv"]==2) {
                $body = array(
                    $rec["cta_nom"],
                    "",
                    "",
                    "", //(round($salAct, 2) != 0) ? number_format($salAct, 2, '.', ',') : 
                    ""
                );
                $pdf->RowBorderHidden($body, $lineHeight);
            } elseif ($rec["cta_con"]=="S" && $rec["cta_niv"]==1) {
                $body = array(
                    $rec["cta_nom"],
                    "",
                    "",
                    "",
                    ""  //(round($salAct, 2) != 0) ? number_format($salAct, 2, '.', ',') : 
                );
                $pdf->RowBorderHidden1BIU($body, $lineHeight, "BU");
            }
            $salIni=0;
        }

        // VALORES PARA TOTALES
        if ($rec["cta_niv"]==1) {
            $totCta = $rec["cta_nom"];
            $totSalIni = $rec["salIni"];
            $totDebe = $rec["cie_mdebe"];
            $totHaber = $rec["cie_mhaber"];
            $totSalMes = $rec["salMes"];
            $totSalAct = $salAct;
        }

        $ctaPrinAnt=$rec["cie_cta"][0];
        $ctaNivAnt=$rec["cta_niv"];
    }
}
$pdf->SetFont("","B",8);
$pdf->SetY($pdf->GetY()-.35);         
$body = array(
    "",
    "",
    (round($totBloque, 2) != 0) ? number_format($totBloque, 2, '.', ',') : "",
    "",
    ""
);
$pdf->RowBorderHidden($body, $lineHeight);
$totBloque=0;

// AGREGA FILA TOTALES
$pdf->SetFont("","B",8);
$pdf->Ln();
$pdf->line($pdf->GetX()+15.8, $pdf->GetY(), 20, $pdf->GetY());
$body = array(
    "TOTAL DE ".$totCta,
    "",
    "",
    "",
    (round($totSalAct, 2) != 0) ? number_format($totSalAct, 2, '.', ',') : ""
);
$pdf->RowBorderHidden($body, $lineHeight);
$pdf->line($pdf->GetX()+15.8, $pdf->GetY(), 20, $pdf->GetY());

// TOTALES PERDIDA O GANANCIA
if (round($totSalActMov, 2)>=0) {
    $textoPG = "PERDIDA DEL EJERCICIO";
} else {
    $textoPG = "GANACIA DEL EJERCICIO";
    $totSalIniMov*=(-1);
    $totSalMesMov*=(-1);
    $totSalActMov*=(-1);
}

$pdf->Ln();
$pdf->line($pdf->GetX()+15.8, $pdf->GetY(), 20, $pdf->GetY());
$body = array(
    $textoPG,
    "",
    "",
    "",
    (round($totSalActMov,2) != 0) ? number_format($totSalActMov, 2, '.', ',') : ""
);
$pdf->RowBorderHidden1BIU($body, $lineHeight, "B");
$pdf->line($pdf->GetX()+15.8, $pdf->GetY(), 20, $pdf->GetY());
$pdf->line($pdf->GetX()+15.8, $pdf->GetY()+.075, 20, $pdf->GetY()+.075);

$leyenda="";
foreach (explode("|", str_replace("\r", "\n", $txtLeyenda)) as &$textLine) {
    $leyenda.=$textLine."\n";
}
$pdf->ln();
$pdf->MultiAlignCell($lineWidth, $lineHeight, utf8_decode($leyenda),0,1,"J");

$db->close();
ob_end_clean();
ob_start();
$pdf->Output(utf8_decode("Estado de Resultados").".pdf","I");
?>