<?php
/**
 * PHPExcel
 *
 * Copyright (c) 2006 - 2015 PHPExcel
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * @category   PHPExcel
 * @package    PHPExcel
 * @copyright  Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
 * @license    http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt	LGPL
 * @version    ##VERSION##, ##DATE##
 */

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"]);

$selGrupo=$_GET["selGrupo"];
$dtDel=$_GET["dtDel"];
$dtAl=$_GET["dtAl"];
$selBodegapro=$_GET['selBodegapro'];
$crTrepo=$_GET['crTrepo'];

# QUERYS
if ($selGrupo=="000") {
    if ($selBodegapro=="000") {
        $sNomper = "SELECT np.*,  mae.mae_gru, mae.mae_dep, mae.mae_tpue,mae.mae_bodega,TRIM(mae.mae_nom) AS mae_nom, TRIM(mae.mae_ape) AS mae_ape, mae_igsssn,mae.mae_fpago
                    FROM nomper np
                    LEFT JOIN maestro mae ON np.np_emp=mae.mae_emp AND np.np_cod = mae.mae_cod 
                    WHERE np_emp='$empCod' AND np_ffin>='$dtDel' and np_ffin<='$dtAl' ORDER BY np.np_gru,np.np_bodega,np_dep,np.np_tpue";
    } else {
        $sNomper = "SELECT np.*,  mae.mae_gru, mae.mae_dep, mae.mae_tpue,mae.mae_bodega,TRIM(mae.mae_nom) AS mae_nom, TRIM(mae.mae_ape) AS mae_ape, mae_igsssn,mae.mae_fpago
                    FROM nomper np
                    LEFT JOIN maestro mae ON np.np_emp=mae.mae_emp AND np.np_cod = mae.mae_cod 
                    WHERE np_emp='$empCod' AND np.np_bodega='$selBodegapro' AND np_ffin>='$dtDel' and np_ffin<='$dtAl' ORDER BY np.np_gru,np.np_bodega,np_dep,np.np_tpue";

    }       
} else {
    if ($selBodegapro=="000") {
        $sNomper = "SELECT np.*,  mae.mae_gru, mae.mae_dep, mae.mae_tpue,mae.mae_bodega,TRIM(mae.mae_nom) AS mae_nom, TRIM(mae.mae_ape) AS mae_ape, mae_igsssn,mae.mae_fpago
                    FROM nomper np
                    LEFT JOIN maestro mae ON np.np_emp=mae.mae_emp AND np.np_cod = mae.mae_cod 
                    WHERE np_emp='$empCod' AND np.np_gru='$selGrupo' AND np_ffin>='$dtDel' and np_ffin<='$dtAl' ORDER BY np.np_gru,np.np_bodega,np_dep,np.np_tpue";
    } else {
        $sNomper = "SELECT np.*,  mae.mae_gru, mae.mae_dep, mae.mae_tpue,mae.mae_bodega,TRIM(mae.mae_nom) AS mae_nom, TRIM(mae.mae_ape) AS mae_ape, mae_igsssn,mae.mae_fpago
                    FROM nomper np
                    LEFT JOIN maestro mae ON np.np_emp=mae.mae_emp AND np.np_cod = mae.mae_cod 
                    WHERE np_emp='$empCod' AND np.np_gru='$selGrupo' AND np.np_bodega='$selBodegapro' AND np_ffin>='$dtDel' and np_ffin<='$dtAl' ORDER BY np.np_gru,np.np_bodega,np_dep,np.np_tpue";
    }       
}       

$dResumenpla = "DELETE FROM resumenpla";

$sResumen = "SELECT *, TRIM(bod.bp_nom) AS bp_nom, TRIM(gru.gru_nom) AS gru_nom, TRIM(dep.dep_nom) AS dep_nom, TRIM(tpu.tpu_nom) AS tpu_nom,
            SUM(rp_liqrec) AS rp_sumliqrec, SUM(rp_ch) AS rp_sumch, SUM(rp_depo) AS rp_sumdepo, SUM(rp_efec) AS rp_sumefec
            FROM resumenpla rp
            LEFT JOIN bodegapro bod ON bod.bp_cod=rp.rp_bodega
            LEFT JOIN grupo gru ON gru.gru_emp=rp.rp_emp AND gru.gru_cod=rp.rp_grupo
            LEFT JOIN dep dep ON dep.dep_emp=rp.rp_emp AND dep.dep_cod=rp.rp_dep
            LEFT JOIN tpuesto tpu ON  tpu.tpu_cod=rp.rp_tpue 
            GROUP BY rp_bodega,rp_grupo,rp_dep,rp_tpue ORDER BY rp_bodega,rp_grupo,rp_dep,rp_tpue";

function sResumenpla($grupo,$bodega,$dep,$tpue,$igsssn){
    global $empCod;
    return "SELECT * FROM resumenpla WHERE rp_emp='$empCod' AND rp_grupo='$grupo' AND rp_bodega='$bodega' AND rp_dep='$dep' AND rp_tpue='$tpue' AND rp_igsssn='$igsssn'";
}

function iResumenpla($grupo,$bodega,$dep,$tpue,$igsssn,$liqrec,$ch,$depo,$efec){
    global $empCod;
    return "INSERT INTO resumenpla(rp_emp,rp_grupo,rp_bodega,rp_dep,rp_tpue,rp_igsssn,rp_liqrec,rp_ch,rp_depo,rp_efec) VALUES ('$empCod','$grupo','$bodega','$dep','$tpue','$igsssn','$liqrec','$ch','$depo','$efec')";
}
function uResumenpla($grupo,$bodega,$dep,$tpue,$igsssn,$liqrec,$ch,$depo,$efec){
    global $empCod;
    return "UPDATE resumenpla SET rp_liqrec='$liqrec',rp_ch='$ch',rp_depo='$depo',rp_efec='$efec' WHERE rp_emp='$empCod' AND rp_grupo='$grupo' AND rp_bodega='$bodega' AND rp_dep='$dep' AND rp_tpue='$tpue' AND rp_igsssn='$igsssn'";
}

function sNomper_prod($del,$al,$cod){
    global $empCod;
    return "SELECT *, SUM(npp_cant) AS npp_uniprod, SUM(npp_tot) AS npp_valprod FROM nomper_prod WHERE npp_emp='$empCod' AND npp_codemple='$cod' AND npp_fec>='$del' AND npp_fec<='$al' GROUP BY npp_emp,npp_codemple";
}

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

$func = new functions();

/** Error reporting */
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
date_default_timezone_set('Europe/London');

if (PHP_SAPI == 'cli')
    die('This example should only be run from a Web Browser');

require_once dirname(__FILE__) . '/../../../php/PHPExcel/Classes/PHPExcel.php';

$iIni=0;
$objPHPExcel = new PHPExcel();

# CREAR HOJAS
for ($i=0; $i < 1; $i++) { 
    $objPHPExcel->createSheet();
}

# HOJAS
$sheet['planilla']=0;

# ESTABLECER PROPIEDADES DEL DOCUMENTO
$objPHPExcel->getProperties()->setCreator("Asesoría en Sistemas, S.A.")
                        ->setLastModifiedBy("Asesoría en Sistemas, S.A.")
                        ->setTitle("Office 2007 XLSX Test Document")
                        ->setSubject("Office 2007 XLSX Test Document")
                        ->setDescription("")
                        ->setKeywords("office 2007 openxml php")
                        ->setCategory("Contabilidad General");

# ENCABEZADO PRIMER HOJA
$i=$iIni;
$j=7;
$objPHPExcel->setActiveSheetIndex($sheet['planilla'])
            ->setCellValueByColumnAndRow($i, 2, TRIM($empNom))
            ->setCellValueByColumnAndRow($i, 3, "RESUMEN DE PLANILLA DEL : ".strftime("%d/%m/%Y", strtotime($dtDel))." al ".strftime("%d/%m/%Y", strtotime($dtAl)))
            ->setCellValueByColumnAndRow($i++, $j, 'DEPARTAMENTO')
            ->setCellValueByColumnAndRow($i++, $j, 'AREA/PUESTO')
            ->setCellValueByColumnAndRow($i++, $j, 'LIQUIDO')
            ->setCellValueByColumnAndRow($i++, $j, 'CHEQUE')
            ->setCellValueByColumnAndRow($i++, $j, 'DEPOSITO')
            ->setCellValueByColumnAndRow($i++, $j, 'EFECTIVO')
            ->setCellValueByColumnAndRow($i++, $j, 'TOTAL');

# ESTILO ENCABEZADO PRIMERA HOJA
$styEmp = array(
    'font' => array(
        'name' => 'Arial',
        'bold' => true,
        'size' => 12,
        //'color' => array('rgb' => 'FFFFFF')
        'color' => array('rgb' => '16365C')

    )
/*    'borders' => array(
        'allborders' => array(
            'style' => PHPExcel_Style_Border::BORDER_THIN,
        )
    ),      */
    //'fill' => array('type' => PHPExcel_Style_Fill::FILL_SOLID, 'color' => array('rgb' => '354D73') ),
    //'fill' => array('type' => PHPExcel_Style_Fill::FILL_SOLID, 'color' => array('rgb' => 'c3c3c3') )
/*    'alignment' => array(
        'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
//        'wrap' => true,
        'merge' => true,
        )  */
);
$styEmp1 = array(
    'font' => array(
        'name' => 'Arial',
        'bold' => true,
        'size' => 12,
        //'color' => array('rgb' => 'FFFFFF')
        'color' => array('rgb' => '16365C')

    )
/*    'borders' => array(
        'allborders' => array(
            'style' => PHPExcel_Style_Border::BORDER_THIN,
        )
    ),    */
    //'fill' => array('type' => PHPExcel_Style_Fill::FILL_SOLID, 'color' => array('rgb' => '354D73') ),
    //'fill' => array('type' => PHPExcel_Style_Fill::FILL_SOLID, 'color' => array('rgb' => 'c3c3c3') )
/*    'alignment' => array(
        'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,  
    //    'wrap' => true,
        )    */
);


$styFec = array(
    'alignment' => array(
        'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
    )
);

$styEncabezado = array(
    'font' => array(
        'name' => 'Arial',
        'bold' => true,
        'size' => 12,
        'name' => 'Arial',
        //'color' => array('rgb' => 'FFFFFF')
        'color' => array('rgb' => '16365C')

    ),
    'borders' => array(
        'allborders' => array(
            'style' => PHPExcel_Style_Border::BORDER_THIN,
        )
    ),
    'fill' => array('type' => PHPExcel_Style_Fill::FILL_SOLID, 'color' => array('rgb' => 'E6B8B7') ),
    //'fill' => array('type' => PHPExcel_Style_Fill::FILL_SOLID, 'color' => array('rgb' => 'c3c3c3') )
    'alignment' => array(
        'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
        'wrap' => true,
        )    
);

$styTotales = array(
    'font' => array(
        'bold' => true,
        'size' => 12,
        'color' => array('rgb' => 'FFFFFF')
        //'color' => array('rgb' => '001a57')

    ),
    'borders' => array(
        'allborders' => array(
            'style' => PHPExcel_Style_Border::BORDER_THIN,
        )
    ),
    'fill' => array('type' => PHPExcel_Style_Fill::FILL_SOLID, 'color' => array('rgb' => '354D73') )
    //'fill' => array('type' => PHPExcel_Style_Fill::FILL_SOLID, 'color' => array('rgb' => 'c3c3c3') )
);

$styLineas = array(
    'font' => array(
        'name' => 'Arial',
        'bold' => false,
        'size' => 12,
    ),
    'borders' => array(
        'allborders' => array(
            'style' => PHPExcel_Style_Border::BORDER_THIN
        )
    )
);
//foreach(range('A','I') as $colID) { 
//    $objPHPExcel->getActiveSheet()->getColumnDimension($colID)->setAutoSize(true); 
//}

$objPHPExcel->getActiveSheet()->getStyle('A2:G2')->applyFromArray($styEmp);
$objPHPExcel->getActiveSheet()->getStyle('A3:G3')->applyFromArray($styEmp1);
$objPHPExcel->getActiveSheet()->getStyle('A4:G4')->applyFromArray($styEmp1);
$objPHPExcel->getActiveSheet()->getStyle('A7:G7')->applyFromArray($styEncabezado);

$totdepo=0;
$totch=0;
$totefec=0;
$bodegap=99999;
$depp=99999;
$t_lini=1;
$j=8;
$inibod=8;
$nocorr=1;
// Se borra lo que se haya grabado antes en el resumen
$db->query($dResumenpla);
// Se lee para agregar al resumen
while ($rec = $db->fetchAssoc($select["nomper"])) {
    if ($crTrepo=='S' && $rec["mae_igsssn"] =='N') {
        continue;
    }
    if ($crTrepo=='N' && $rec["mae_igsssn"] =='S') {
        continue;
    }
    $cod=$rec["np_cod"];
    $del=$rec["np_fini"];
    $al=$rec["np_ffin"];
    $uniprod=0;
    $valprod=0;
    $select["nomper_prod"] = $db->query(sNomper_prod($del,$al,$cod));
    if ($db->numRows($select["nomper_prod"]) > 0) {
       $fetchAssoc["nomper_prod"] = $db->fetchAssoc($select["nomper_prod"]);
       $uniprod=$fetchAssoc["nomper_prod"]["npp_uniprod"];
       $valprod=$fetchAssoc["nomper_prod"]["npp_valprod"]+$rec["np_bonii"];
    }
    $ingrepla=($rec["np_sord"]+$rec["np_sexts"]+$rec["np_sextd"]+$rec["np_ssept"]+$rec["np_bonii"]+$rec["np_bonoe"]+$rec["np_depre"]+$rec["np_viati"]+$rec["np_comi"]+$rec["np_otrp"]+$rec["np_boni"]+$rec["np_sferi"]+$rec["np_bono14"]+$rec["np_agui"]+$rec["np_vaca"]);
    if ($ingrepla>=$valprod) {
        $subtotal=$ingrepla;
        $ajuste=$ingrepla-$valprod;
    } else {
        $subtotal=$valprod;
        $ajuste=0;
    }   
    $descu=($rec["np_igss"]+$rec["np_isr"]+$rec["np_anti"]+$rec["np_unif"]+$rec["np_lent"]+$rec["np_preb"]+$rec["np_pree"]+$rec["np_desj"]+$rec["np_otrd"]);
    $liquido=($subtotal-$descu);
    $totdepo=0;
    $totch=0;
    $totefec=0;
    if ($rec["np_fpago"]<=2) {
        $totdepo=$liquido;
    } 
    if ($rec["np_fpago"]>2 && $rec["np_fpago"]!=5) {
        $totch=$liquido;
    } 
    if ($rec["np_fpago"]==5) {
        $totefec=$liquido;
    } 
    $grupo=$rec["np_gru"];
    $bodega=$rec["np_bodega"];
    $dep=$rec["np_dep"];
    $tpue=$rec["np_tpue"];
    $igsssn=$rec["mae_igsssn"];

    $select["resumenpla"] = $db->query(sResumenpla($grupo,$bodega,$dep,$tpue,$igsssn));
    if ($db->numRows($select["resumenpla"]) > 0) {
       $fetchAssoc["resumenpla"] = $db->fetchAssoc($select["resumenpla"]);
       $liqant=$fetchAssoc["resumenpla"]["rp_liqrec"];
       $chant=$fetchAssoc["resumenpla"]["rp_ch"];       
       $depoant=$fetchAssoc["resumenpla"]["rp_depo"];       
       $efecant=$fetchAssoc["resumenpla"]["rp_efec"];       
       $nuevoliq=$liqant+$liquido;
       $nuevoch=$chant+$totch;
       $nuevodepo=$depoant+$totdepo;
       $nuevoefec=$efecant+$totefec;
       $db->query(uResumenpla($grupo,$bodega,$dep,$tpue,$igsssn,$nuevoliq,$nuevoch,$nuevodepo,$nuevoefec));
    } else {
       $db->query(iResumenpla($grupo,$bodega,$dep,$tpue,$igsssn,$liquido,$totch,$totdepo,$totefec));
    }
}
//
// Para mostrar los datos del resumen
$select["resumen"] = $db->query($sResumen);
while ($rec = $db->fetchAssoc($select["resumen"])) {
    if ($rec["rp_bodega"] != $bodegap) {
        if ($t_lini>1) {
           $i=$iIni;
           $objPHPExcel->getActiveSheet()
                    ->setCellValueByColumnAndRow($i++, $j, "    TOTAL ESTA BODEGA")
                    ->setCellValueByColumnAndRow($i++, $j, "")
                    ->setCellValueByColumnAndRow($i++, $j, '=SUM(C'.$inibod.':C'.($j-1).')')
                    ->setCellValueByColumnAndRow($i++, $j, '=SUM(D'.$inibod.':D'.($j-1).')')
                    ->setCellValueByColumnAndRow($i++, $j, '=SUM(E'.$inibod.':E'.($j-1).')')
                    ->setCellValueByColumnAndRow($i++, $j, '=SUM(F'.$inibod.':F'.($j-1).')')
                    ->setCellValueByColumnAndRow($i++, $j, '=SUM(G'.$inibod.':G'.($j-1).')');
                $objPHPExcel->getActiveSheet()->getStyle('A'.$j.':G'.$j)->applyFromArray($styTotales);
            $j+=1;
            $inibod=$j;
        }

        $i=$iIni;
        $objPHPExcel->getActiveSheet()
                    ->setCellValueByColumnAndRow($i++, $j, $rec["bp_nom"]);
        $objPHPExcel->getActiveSheet()->getStyle('A'.$j.':G'.$j)->applyFromArray($styLineas);

        $bodegap=$rec["rp_bodega"];
        $j+=1;
        $t_lini=2;
    }
    $i=$iIni;
    $objPHPExcel->getActiveSheet()
                ->setCellValueByColumnAndRow($i++, $j, $rec["dep_nom"])
                ->setCellValueByColumnAndRow($i++, $j, $rec["tpu_nom"])
                ->setCellValueByColumnAndRow($i++, $j, $rec["rp_sumliqrec"])
                ->setCellValueByColumnAndRow($i++, $j, $rec["rp_sumch"])
                ->setCellValueByColumnAndRow($i++, $j, $rec["rp_sumdepo"])
                ->setCellValueByColumnAndRow($i++, $j, $rec["rp_sumefec"])
                ->setCellValueByColumnAndRow($i++, $j, ($rec["rp_sumch"]+$rec["rp_sumdepo"]+$rec["rp_sumefec"]));
    $objPHPExcel->getActiveSheet()->getStyle('A'.$j.':G'.$j)->applyFromArray($styLineas);
    $j+=1;
}
$i=$iIni;
$objPHPExcel->getActiveSheet()
        ->setCellValueByColumnAndRow($i++, $j, "    TOTAL ESTA BODEGA")
        ->setCellValueByColumnAndRow($i++, $j, "")
        ->setCellValueByColumnAndRow($i++, $j, '=SUM(C'.$inibod.':C'.($j-1).')')
        ->setCellValueByColumnAndRow($i++, $j, '=SUM(D'.$inibod.':D'.($j-1).')')
        ->setCellValueByColumnAndRow($i++, $j, '=SUM(E'.$inibod.':E'.($j-1).')')
        ->setCellValueByColumnAndRow($i++, $j, '=SUM(F'.$inibod.':F'.($j-1).')')
        ->setCellValueByColumnAndRow($i++, $j, '=SUM(G'.$inibod.':G'.($j-1).')');
    $objPHPExcel->getActiveSheet()->getStyle('A'.$j.':G'.$j)->applyFromArray($styTotales);
$j+=1;
$inibod=$j;
$i=$iIni;
$objPHPExcel->getActiveSheet()
    ->setCellValueByColumnAndRow($i++, $j, "      TOTAL GENERAL")
    ->setCellValueByColumnAndRow($i++, $j, "") 
    ->setCellValueByColumnAndRow($i++, $j, '=SUMIF(A8:C'.($j-1).',"    TOTAL ESTA BODEGA",C8:C'.($j-1).')') 
    ->setCellValueByColumnAndRow($i++, $j, '=SUMIF(A8:C'.($j-1).',"    TOTAL ESTA BODEGA",D8:D'.($j-1).')') 
    ->setCellValueByColumnAndRow($i++, $j, '=SUMIF(A8:C'.($j-1).',"    TOTAL ESTA BODEGA",E8:E'.($j-1).')') 
    ->setCellValueByColumnAndRow($i++, $j, '=SUMIF(A8:C'.($j-1).',"    TOTAL ESTA BODEGA",F8:F'.($j-1).')') 
    ->setCellValueByColumnAndRow($i++, $j, '=SUMIF(A8:C'.($j-1).',"    TOTAL ESTA BODEGA",G8:G'.($j-1).')');
$objPHPExcel->getActiveSheet()->getStyle('A'.$j.':G'.$j)->applyFromArray($styTotales);

$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(30);
$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(30);
$objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(20);
$objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(20);
$objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(20);
$objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(20);
$objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(20);

$objPHPExcel->getActiveSheet()->getStyle('C8'.':G'.$j)->getNumberFormat()->setFormatCode('###,##0.00');
$objPHPExcel->getActiveSheet()->getStyle('A8'.':B'.$j)->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_TEXT);

# ESTABLECER TITULOS
$objPHPExcel->setActiveSheetIndex($sheet['planilla'])->setTitle('Resumen Planilla');

# AL ABRIR EL DOCUMENTO ABRIR EN PRIMERA HOJA
$objPHPExcel->setActiveSheetIndex(0);


// Redirect output to a client’s web browser (Excel2007)
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="Resumen Planilla.xlsx"');
header('Cache-Control: max-age=0');
// If you're serving to IE 9, then the following may be needed
header('Cache-Control: max-age=1');

// If you're serving to IE over SSL, then the following may be needed
header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
header ('Pragma: public'); // HTTP/1.0

$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('php://output');
exit;
?>