<?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/functions.php');
include_once("../../../php/fpdf/functions.php");
include_once('../../../php/maxExecTime.php');

$empCod = $_SESSION['empCod'];
$empNom = $_SESSION['empNom'];

$selBodega=$_GET["selBodega"];
$BodegaNom=$_GET["BodegaNom"];
$dtFeci=$_GET["dtFeci"];
$dtFecf=$_GET["dtFecf"];

# QUERYS
if ($selBodega=='0000') {
    $sArtic = "SELECT fd.*, TRIM(fac.fact_nom) AS fact_nom, TRIM(cli.cli_nom) AS cli_nom, 
                SUM(factd_cant) AS factd_scant, SUM(factd_tot) AS factd_stot,
                TRIM(fd.factd_desc) AS art_desc,
                TRIM(fd.factd_nit) AS factd_nit
                FROM fact_det fd 
                LEFT JOIN facturas fac ON fd.factd_emp=fac.fact_emp AND fd.factd_transac=fac.fact_transac
                LEFT JOIN clien cli ON fd.factd_nit=cli.cli_nit 
                WHERE factd_emp='$empCod' AND factd_nit!='CF' AND factd_fec>='$dtFeci' AND factd_fec<='$dtFecf' 
                GROUP BY factd_emp,factd_nit
                ORDER BY factd_emp,SUM(factd_tot) DESC";
} else {
    $sArtic = "SELECT fd.*, TRIM(fac.fact_nom) AS fact_nom, TRIM(cli.cli_nom) AS cli_nom, 
                SUM(factd_cant) AS factd_scant, SUM(factd_tot) AS factd_stot,
                TRIM(fd.factd_desc) AS art_desc,
                TRIM(fd.factd_nit) AS factd_nit
                FROM fact_det fd 
                LEFT JOIN facturas fac ON fd.factd_emp=fac.fact_emp AND fd.factd_transac=fac.fact_transac
                LEFT JOIN clien cli ON fd.factd_nit=cli.cli_nit 
                WHERE factd_emp='$empCod' AND factd_nit!='CF' AND factd_fec>='$dtFeci' AND factd_fec<='$dtFecf' AND factd_bodsal='$selBodega' 
                GROUP BY factd_emp,factd_nit
                ORDER BY factd_emp,SUM(factd_tot) DESC";
}

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

$func = new functions();

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

/** 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['Movimientos']=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=6;
$objPHPExcel->setActiveSheetIndex($sheet['Movimientos'])
			->setCellValueByColumnAndRow($i, 1, $empNom)
			->setCellValueByColumnAndRow($i, 2, "Reporte de Movimientos Segun Cliente y producto ".strftime("%d/%m/%Y", strtotime($dtFeci))." al ".strftime("%d/%m/%Y", strtotime($dtFecf)))
            ->setCellValueByColumnAndRow($i, 3, "Bodega:  ".$BodegaNom)
			->setCellValueByColumnAndRow($i++, $j, 'Nit')
			->setCellValueByColumnAndRow($i++, $j, 'Cliente')
			->setCellValueByColumnAndRow($i++, $j, 'Valor');
# ESTILO ENCABEZADO PRIMERA HOJA
$styEmp = array(
    'font' => array(
        'bold' => true,
        'size' => 17,
    ),
    'alignment' => array(
        'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
    )
);

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

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

$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
        )
    )
);


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

$objPHPExcel->getActiveSheet()->mergeCells('A1:C1')->getStyle('A1')->applyFromArray($styEmp);
$objPHPExcel->getActiveSheet()->mergeCells('A2:C2')->getStyle('A2')->applyFromArray($styFec);
$objPHPExcel->getActiveSheet()->mergeCells('A3:C3')->getStyle('A3')->applyFromArray($styFec);
$objPHPExcel->getActiveSheet()->mergeCells('A4:C4')->getStyle('A4')->applyFromArray($styFec);
$objPHPExcel->getActiveSheet()->getStyle('A6:C6')->applyFromArray($styEncabezado);

# VALORES PRIMER HOJA
$i=$iIni;
for ($j=7; $rec = $db->fetchAssoc($select['fact_det']); $j++) {
    if ($rec["factd_stot"]<=0) {
        continue;
    }

	$objPHPExcel->getActiveSheet()
				->setCellValueByColumnAndRow($i++, $j, $rec['factd_nit'])
				->setCellValueByColumnAndRow($i++, $j, utf8_encode(trim($rec['cli_nom'])))
                ->setCellValueByColumnAndRow($i++, $j, $rec['factd_stot']);
            $objPHPExcel->getActiveSheet()->setCellValueExplicit('A'.$j, $rec["factd_nit"], PHPExcel_Cell_DataType::TYPE_STRING);
	$i=$iIni;
}

// TOTALES DEL MOVIMIENTO

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

$objPHPExcel->getActiveSheet()->getStyle('C5'.':C'.$j)->getNumberFormat()->setFormatCode('###,###,##0.00');
$objPHPExcel->getActiveSheet()->getStyle('A5'.':B'.$j)->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_TEXT);

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

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

$db->close();

// Redirect output to a client’s web browser (Excel2007)
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="ResuMovCli.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;

?>