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

$dtFecI=$_SESSION["print"]["dtFecI"];
$dtFecF=$_SESSION["print"]["dtFecF"];
$selBodega=$_SESSION["print"]["selBodega"];
$BodegaNom=$_SESSION["print"]["BodegaNom"];
$txtCodd=$_SESSION["print"]["txtCodd"];
$txtDescd=$_SESSION["print"]["txtDescd"];

# QUERYS
$sMoviie0 = "SELECT mov_emp,mov_cod,mov_bodent,mov_bodsal,
            SUM(mov_entra) AS mov_sentra
            FROM movii WHERE mov_emp='$empCod' AND mov_cod='$txtCodd' AND mov_bodent='$selBodega' AND mov_fec>='$dtFecI' GROUP BY '$empCod','$txtCodd'";

$sMoviis0 = "SELECT mov_emp,mov_cod,mov_bodent,mov_bodsal,
            SUM(mov_sale) AS mov_ssale
            FROM movii WHERE mov_emp='$empCod' AND mov_cod='$txtCodd' AND mov_bodsal='$selBodega' AND mov_fec>='$dtFecI' GROUP BY '$empCod','$txtCodd'";

$sMovii = "SELECT *,
            TRIM(mov_cod) AS mov_cod
            FROM movii LEFT JOIN tipodoci ON movii.mov_tipo=tipodoci.td_cod WHERE mov_emp='$empCod' AND mov_cod='$txtCodd' AND (mov_bodent='$selBodega' OR mov_bodsal='$selBodega') AND mov_fec>='$dtFecI' AND mov_fec<='$dtFecF' ORDER BY mov_fec,td_eos,mov_tipo,mov_num";
    
$sExiart = "SELECT * FROM exiart WHERE ea_emp='$empCod' AND ea_cod='$txtCodd' AND ea_bod=$selBodega";

$sArtic = "SELECT *,
            TRIM(art_cod) AS art_cod,
            TRIM(art_desc) AS art_desc 
            FROM artic LEFT JOIN unimed ON artic.art_medi=unimed.um_cod WHERE art_emp='$empCod' AND art_cod='$txtCodd'";

# EJECUCION DE QUERYS
$db = new dbExec();
$select["movii"] = $db->query($sMoviie0);
$recme0 = $db->fetchAssoc($select['movii']);
$sEntramov=$recme0["mov_sentra"];

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

$select["artic"]=$db->query($sArtic);
$recart = $db->fetchAssoc($select['artic']);
$artNom=trim($recart["art_desc"]);
$artmedida=rtrim($recart["um_nom"]);

$select["exiart"]=$db->query($sExiart);
$recea = $db->fetchAssoc($select['exiart']);
$Saldo=$recea["ea_exist"];

$salIni=($Saldo-$sEntramov)+$sSalemov;
$Saldo=0;

/** 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;
$jIni=0;
$objPHPExcel = new PHPExcel();

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

$bordersThin = array(
    'borders' => array(
        'allborders' => array(
            'style' => PHPExcel_Style_Border::BORDER_THIN
        )
    )
);

$borderBottomDouble = array(
    'borders' => array(
        'bottom' => array(
            'style' => PHPExcel_Style_Border::BORDER_DOUBLE
        )
    )
);

$borderTopThin = array(
    'borders' => array(
        'top' => array(
            'style' => PHPExcel_Style_Border::BORDER_THIN
        )
    )
);

$bold17 = array(
    'font' => array(
        'bold' => true,
        'size' => 13,
    ),
);

# HOJAS
$sheet['saldos']=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=$jIni+1;
$objPHPExcel->setActiveSheetIndex($sheet['saldos'])
	->setCellValueByColumnAndRow($i,	$j++, utf8_encode($empNom))
    ->setCellValueByColumnAndRow($i, $j++, utf8_encode("KARDEX DEL ".strftime("%d/%m/%Y", strtotime($dtFecI))." AL ".strftime("%d/%m/%Y", strtotime($dtFecF))))
	->setCellValueByColumnAndRow($i,   $j++, utf8_encode("ARTICULO: ".$txtCodd." - ".$artNom))
    ->setCellValueByColumnAndRow($i,   $j++, utf8_encode("UNIDAD MEDIDA: ".$artmedida))
    ->setCellValueByColumnAndRow($i,   $j++, utf8_encode("BODEGA: ".$BodegaNom))
        ->setCellValueByColumnAndRow(4, 6, "Saldo Inicial: ")
        ->setCellValueByColumnAndRow(5, 6, $salIni);
    $objPHPExcel->getActiveSheet()->getStyle('A6:I7')->applyFromArray($bold17);

$j++;

$i=$iIni;
$objPHPExcel->getActiveSheet()->getStyle('A'.$j.':F'.$j)->applyFromArray($bordersThin);
$objPHPExcel->getActiveSheet()
    ->setCellValueByColumnAndRow($i++,  $j, 'Tipo Documento')
    ->setCellValueByColumnAndRow($i++,  $j, 'Numero')
    ->setCellValueByColumnAndRow($i++,  $j, 'Fecha')
    ->setCellValueByColumnAndRow($i++,  $j, '     Entradas')
    ->setCellValueByColumnAndRow($i++,  $j, '     Salidas')
    ->setCellValueByColumnAndRow($i++,  $j, '     Saldo');


# VALORES PRIMER HOJA
$sentra = 0;
$ssale = 0;
$Saldo = $salIni;

$j++;

# CREA EL CICLO PARA EL LISTADO DE MOVIMIENTOS

$select["movii"] = $db->query($sMovii);
while ($rec = $db->fetchAssoc($select['movii'])) {
    $entra = $rec["mov_entra"];
    $sale = $rec["mov_sale"];
    if (TRIM($rec["mov_bodent"])!=TRIM($selBodega)) {
        $entra=0;
    }
    if (TRIM($rec["mov_bodsal"])!=TRIM($selBodega)) {
        $sale=0;
    }
    $sentra += $entra;
    $ssale += $sale;

    $Saldo = ($Saldo+$entra)-$sale;

    $i=$iIni;

    $objPHPExcel->getActiveSheet()
    ->setCellValueByColumnAndRow($i++,  $j, $rec["td_nom"])
    ->setCellValueByColumnAndRow($i++,  $j, $rec["mov_num"])
    ->setCellValueByColumnAndRow($i++,  $j, strftime("%d/%m/%Y", strtotime($rec["mov_fec"])))
    ->setCellValueByColumnAndRow($i++,  $j, (round($entra,2) != 0) ? $entra : "")
    ->setCellValueByColumnAndRow($i++,  $j, (round($sale,2) != 0) ? $sale : "")
    ->setCellValueByColumnAndRow($i++,  $j, $Saldo);

    $j++;

    $linea=2;
}


$j++;

// TOTALES DEL MOVIMIENTO
$objPHPExcel->getActiveSheet()->getStyle('D'.$j.':F'.$j)->applyFromArray($borderTopThin);
$objPHPExcel->getActiveSheet()->getStyle('D'.$j.':F'.$j)->applyFromArray($borderBottomDouble);

$objPHPExcel->getActiveSheet()
    ->setCellValueByColumnAndRow(2, $j, 'Totales')
    ->setCellValueByColumnAndRow(3, $j, '=SUM(D7:D'.($j-1).')')
    ->setCellValueByColumnAndRow(4, $j, '=SUM(E7:E'.($j-1).')'); 

# ESTILO HOJA
$xCenter = array(
    'font' => array(
        'bold' => true,
    ),
	'alignment' => array(
        'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
    )
);

for ($q=1; $q < 6; $q++) { 
	$objPHPExcel->getActiveSheet()->mergeCells('A'.$q.':F'.$q)->getStyle('A'.$q)->applyFromArray($xCenter);
}

$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(35);
$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(15);
$objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(14);
$objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(17);
$objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(17);
$objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(17);

# FORMATOS
$objPHPExcel->getActiveSheet()->getStyle('D6'.':F'.$j)->getNumberFormat()->setFormatCode('#,##0.00');
$objPHPExcel->getActiveSheet()->getStyle('A6'.':B'.$j)->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_TEXT);

/*foreach(range('A','G') as $colID) { 
	$objPHPExcel->getActiveSheet()->getColumnDimension($colID)->setAutoSize(true); 
} */

# ESTABLECER TITULOS
$objPHPExcel->setActiveSheetIndex($sheet['saldos'])->setTitle('Saldo');

# 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="Kardex.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;
?>