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

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

$selDepto=$_GET["selDepto"];
$selsubDepto=$_GET["selSubDepto"];
$selBodega=$_GET["selBodega"];
$BodegaNom=$_GET["BodegaNom"];
$dtFec=$_GET["dtFec"];
$crTse=$_GET["crTse"];
if ($crTse=="T") {
   $crTsenom="Todos los articulos";
} else {
   $crTsenom="Solo articulos con Existencia";
}   
$lineWidth=17;
$lineHeight=0.4;

class generatePDF extends PDF_MC_Table {
    function Header() {
        global $empNom, $lineHeight, $lineWidth, $dtFec, $BodegaNom, $crTsenom;
        $this->SetMargins(1.2, 1, 2);
        $this->Cell(0, 0, "", 0, 1);

        $this->SetFont("Arial","B",14);
        $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("Reporte Costeado de Inventario al ".strftime("%d/%m/%Y", strtotime($dtFec))),0,1,"L");
        //$this->Ln();
        $this->MultiAlignCell($lineWidth, $lineHeight, utf8_decode("Bodega ".$BodegaNom),0,1,"L");
        $this->MultiAlignCell($lineWidth, $lineHeight, utf8_decode($crTsenom),0,1,"L");
        $this->SetFont("","",8);
        $header = array("Codigo","Descripcion","Existencia","Costo/Promedio","Costo Total","Precio/Unitario","Precio Total");
        $this->SetFont("","B");
        $this->SetWidths(array(3.3,8.8,2.2,2.5,2.7,2.5,2.7));
        $this->SetAligns(array("C","C","C","C","C","C","C"));
        $this->Row($header, $lineHeight);
        $this->SetFont("");
        $this->SetAligns(array("L","L","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 ($selDepto=='0000') {
    if ($selsubDepto=='0000') {
        $sArtic = "SELECT *, TRIM(art_cod) AS art_cod,
                    TRIM(art_desc) AS art_desc,
                    TRIM(art_desd) AS art_desd,
                    TRIM(art_marca) AS art_marca,
                    TRIM(art_prov) AS art_prov,
                    TRIM(art_codf) AS art_codf,
                    TRIM(art_codbarr) AS art_codbarr
                    FROM artic art LEFT JOIN deptosi di ON art.art_dep=di.dep_cod 
                    LEFT JOIN subdeptosi sdi ON art.art_dep=sdi.sdep_dep AND art.art_subdep=sdi.sdep_cod
                    LEFT JOIN unimed um ON art.art_medi=um.um_cod
                    WHERE art_emp='$empCod' AND art_bienser='B' ORDER BY art_emp,art_dep,art_subdep,art_desc";
    } else {
        $sArtic = "SELECT *, TRIM(art_cod) AS art_cod,
                    TRIM(art_desc) AS art_desc,
                    TRIM(art_desd) AS art_desd,
                    TRIM(art_marca) AS art_marca,
                    TRIM(art_prov) AS art_prov,
                    TRIM(art_codf) AS art_codf,
                    TRIM(art_codbarr) AS art_codbarr
                    FROM artic art LEFT JOIN deptosi di ON art.art_dep=di.dep_cod 
                    LEFT JOIN  subdeptosi sdi ON art.art_dep=sdi.sdep_dep AND art.art_subdep=sdi.sdep_cod
                    LEFT JOIN unimed um ON art.art_medi=um.um_cod
                    WHERE art_emp='$empCod' AND art_subdep='$selsubDepto' AND art_bienser='B' ORDER BY art_emp,art_dep,art_subdep,art_desc";
    }
} else {
    if ($selsubDepto=='0000') {
        $sArtic = "SELECT *, TRIM(art_cod) AS art_cod,
                    TRIM(art_desc) AS art_desc,
                    TRIM(art_desd) AS art_desd,
                    TRIM(art_marca) AS art_marca,
                    TRIM(art_prov) AS art_prov,
                    TRIM(art_codf) AS art_codf,
                    TRIM(art_codbarr) AS art_codbarr
                    FROM artic art LEFT JOIN deptosi di ON art.art_dep=di.dep_cod 
                    LEFT JOIN  subdeptosi sdi ON art.art_dep=sdi.sdep_dep AND art.art_subdep=sdi.sdep_cod
                    LEFT JOIN unimed um ON art.art_medi=um.um_cod
                    WHERE art_emp='$empCod' AND art_dep='$selDepto' AND art_bienser='B' ORDER BY art_emp,art_dep,art_subdep,CAST(art_cod AS UNSIGNED)";
    } else {
        $sArtic = "SELECT *, TRIM(art_cod) AS art_cod,
                    TRIM(art_desc) AS art_desc,
                    TRIM(art_desd) AS art_desd,
                    TRIM(art_marca) AS art_marca,
                    TRIM(art_prov) AS art_prov,
                    TRIM(art_codf) AS art_codf,
                    TRIM(art_codbarr) AS art_codbarr
                    FROM artic art LEFT JOIN deptosi di ON art.art_dep=di.dep_cod 
                    LEFT JOIN  subdeptosi sdi ON art.art_dep=sdi.sdep_dep AND art.art_subdep=sdi.sdep_cod
                    LEFT JOIN unimed um ON art.art_medi=um.um_cod
                    WHERE art_emp='$empCod' AND art_dep='$selDepto' AND art_subdep='$selsubDepto' AND art_bienser='B' ORDER BY art_emp,art_dep,art_subdep,art_desc";
    }
}
function sExiart($codd) { 
    global $empCod, $usuNom, $selBodega;
    return "SELECT * FROM exiart WHERE ea_emp='$empCod' AND ea_cod='$codd' AND ea_bod='$selBodega'";
}

function sExiartTodas($codd) { 
    global $empCod, $usuNom, $selBodega;
    return "SELECT *, SUM(ea_exist) AS ea_existtot FROM exiart WHERE ea_emp='$empCod' AND ea_cod='$codd' GROUP BY '$empCod','$codd'";
}

function sMoviie0($codd) { 
    global $empCod, $usuNom, $selBodega, $dtFec;
    return "SELECT mov_emp,mov_cod,mov_bodent,mov_bodsal,
            SUM(mov_entra) AS mov_sentra
            FROM movii WHERE mov_emp='$empCod' AND mov_cod='$codd' AND mov_bodent='$selBodega' AND mov_fec>'$dtFec' GROUP BY '$empCod','$codd'";
}
function sMoviis0($codd) { 
    global $empCod, $usuNom, $selBodega, $dtFec;
    return "SELECT mov_emp,mov_cod,mov_bodent,mov_bodsal,
            SUM(mov_sale) AS mov_ssale
            FROM movii WHERE mov_emp='$empCod' AND mov_cod='$codd' AND mov_bodsal='$selBodega' AND mov_fec>'$dtFec' GROUP BY '$empCod','$codd'";
}

function sMoviie0Todas($codd) { 
    global $empCod, $usuNom, $selBodega, $dtFec;
    return "SELECT mov_emp,mov_cod,mov_bodent,mov_bodsal,
            SUM(mov_entra) AS mov_sentra
            FROM movii WHERE mov_emp='$empCod' AND mov_cod='$codd' AND mov_fec>'$dtFec' GROUP BY '$empCod','$codd'";
}
function sMoviis0Todas($codd) { 
    global $empCod, $usuNom, $selBodega, $dtFec;
    return "SELECT mov_emp,mov_cod,mov_bodent,mov_bodsal,
            SUM(mov_sale) AS mov_ssale
            FROM movii WHERE mov_emp='$empCod' AND mov_cod='$codd' AND mov_fec>'$dtFec' GROUP BY '$empCod','$codd'";
}

function sCierrei($codd) { 
    global $empCod, $usuNom, $selBodega, $dtFec ;
    return "SELECT * FROM cierresi WHERE ci_emp='$empCod' AND ci_cod='$codd' AND ci_fec='$dtFec'";
}

function sCierreiTodas($codd) { 
    global $empCod, $usuNom, $selBodega, $dtFec;
    return "SELECT * FROM cierresi WHERE ci_emp='$empCod' AND ci_cod='$codd' AND ci_fec='$dtFec'";
}

# EJECUCION DE QUERYS
$db = new dbExec();
$func = new functions();

$select["artic"] = $db->query($sArtic);

# GENERAR PDF
$pdf = new generatePDF("L","cm", "Letter");
$pdf->AddPage();
$ti_Depto="XXXX";
$ti_sDepto="XXXX";
$sumcos=0;
while ($rec = $db->fetchAssoc($select["artic"])) {
    if ($ti_Depto.$ti_sDepto!=$rec["art_dep"].$rec["art_subdep"]) {
       $pdf->SetFont("","B");
       $pdf->Cell($lineWidth,.7,trim($rec["dep_nom"]).", ".rtrim($rec["sdep_nom"]),0,0,"L");
       $ti_Depto=$rec["art_dep"];
       $ti_sDepto=$rec["art_subdep"];
       $pdf->SetFont("","");
       $pdf->ln();
    }
    $codd=$rec["art_cod"];
    $cosp=$rec["art_cosp"];
    $pre1=$rec["art_pre1"];

    if ($selBodega=='0000') {
        $select["exiart"] = $db->query(sExiartTodas($codd));
        $fetchAssoc["exiart"] = $db->fetchAssoc($select["exiart"]);
        $Exist = $fetchAssoc["exiart"]["ea_existtot"];

        $select["cierresi"] = $db->query(sCierreiTodas($codd));
        $fetchAssoc["cierresi"] = $db->fetchAssoc($select["cierresi"]);
        if ($db->numRows($select["cierresi"]) > 0) {
            $cosp = $fetchAssoc["cierresi"]["ci_cosp"];
        }
        $select["movii"] = $db->query(sMoviie0Todas($codd));
        $recme0 = $db->fetchAssoc($select['movii']);
        $sEntramov=$recme0["mov_sentra"];

        $select["movii"] = $db->query(sMoviis0Todas($codd));
        $recms0 = $db->fetchAssoc($select['movii']);
        $sSalemov=$recms0["mov_ssale"];

        $Exipas=($Exist-$sEntramov)+$sSalemov;
    } else {
        $select["exiart"] = $db->query(sExiart($codd));
        $fetchAssoc["exiart"] = $db->fetchAssoc($select["exiart"]);
        $Exist = $fetchAssoc["exiart"]["ea_exist"];

        $select["cierresi"] = $db->query(sCierrei($codd));
        $fetchAssoc["cierresi"] = $db->fetchAssoc($select["cierresi"]);
        if ($db->numRows($select["cierresi"]) > 0) {
            $cosp = $fetchAssoc["cierresi"]["ci_cosp"];
        }
        $select["movii"] = $db->query(sMoviie0($codd));
        $recme0 = $db->fetchAssoc($select['movii']);
        $sEntramov=$recme0["mov_sentra"];

        $select["movii"] = $db->query(sMoviis0($codd));
        $recms0 = $db->fetchAssoc($select['movii']);
        $sSalemov=$recms0["mov_ssale"];

        $Exipas=($Exist-$sEntramov)+$sSalemov;
    }
    if ($crTse=='E' && $Exipas<=0) {
        continue;
    }        
    $costot=round($Exipas*$cosp,5);
    $pretot=round($Exipas*$pre1,5);
    $sumcos+=$costot;
    $sumpre+=$pretot;
    $body = array(
        $rec["art_cod"],
        trim($rec["art_desc"]),
        number_format($Exipas, 2, '.', ','),
        number_format($cosp, 5, '.', ','),
        number_format($costot, 5, '.', ','),
        number_format($pre1, 2, '.', ','),
        number_format($pretot, 2, '.', ','),
    );
    $pdf->RowBorderHidden($body, $lineHeight);
}
$pdf->line($pdf->GetX()+3.5, $pdf->GetY(), 26, $pdf->GetY());

//$pdf->SetAligns(array("","","C","R","R","R"));
$body = array("","Totales: ","","",
    number_format($sumcos,2, '.', ','),
    "",
    number_format($sumpre,2, '.', ','),
);
$pdf->RowBorderHidden($body, $lineHeight);
$pdf->line($pdf->GetX()+3.5, $pdf->GetY(), 26, $pdf->GetY());
$pdf->line($pdf->GetX()+3.5, $pdf->GetY()+.075, 26, $pdf->GetY()+.075);

$db->close();
$pdf->Output(utf8_decode("RCostPre").".pdf","I");
?>