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

$numNum=$_GET["numNum"];
$dtDel=$_GET["dtDel"];
$dtAl=$_GET["dtAl"];

# QUERYS
$sNomper = "SELECT *, TRIM(mae.mae_nom) AS mae_nom, TRIM(mae.mae_ape) AS mae_ape, TRIM(gru_nom) AS gru_nom, TRIM(dep_nom) AS dep_nom,
                mae.mae_fpago, TRIM(tpu.tpu_nom) AS tpu_nom
                FROM nomper np
                LEFT JOIN maestro mae ON np.np_emp=mae.mae_emp AND np.np_cod = mae.mae_cod 
                LEFT JOIN tpuesto tpu ON mae.mae_tpue = tpu.tpu_cod 
                LEFT JOIN grupo gru ON np.np_emp=gru.gru_emp AND np.np_gru = gru.gru_cod 
                LEFT JOIN dep dep ON np.np_emp=dep.dep_emp AND np.np_dep = dep.dep_cod 
                WHERE np_emp='$empCod' AND np_numpla='$numNum' ORDER BY np_emp,np_gru,np_dep,np_cod";

# 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['descuentos']=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=2;
$objPHPExcel->setActiveSheetIndex($sheet['descuentos'])
            ->setCellValueByColumnAndRow(0, 1, "Empresa")
            ->setCellValueByColumnAndRow(1, 1, $empNom)
            ->setCellValueByColumnAndRow(4, 1, "Cod.Emp")
            ->setCellValueByColumnAndRow(5, 1, $empCod)
            ->setCellValueByColumnAndRow(7, 1, "Del")
            ->setCellValueByColumnAndRow(8, 1, strftime("%d/%m/%Y", strtotime($dtDel)))
            ->setCellValueByColumnAndRow(9, 1, "Al")
            ->setCellValueByColumnAndRow(10, 1, strftime("%d/%m/%Y", strtotime($dtAl)))

            ->setCellValueByColumnAndRow($i++, $j, 'Codigo')
            ->setCellValueByColumnAndRow($i++, $j, 'Nombre')
            ->setCellValueByColumnAndRow($i++, $j, 'Isr')
            ->setCellValueByColumnAndRow($i++, $j, 'Bancarios')
            ->setCellValueByColumnAndRow($i++, $j, 'Libreria')
            ->setCellValueByColumnAndRow($i++, $j, 'Carwash')
            ->setCellValueByColumnAndRow($i++, $j, 'Colegiatura')
            ->setCellValueByColumnAndRow($i++, $j, 'Inscripcion')
            ->setCellValueByColumnAndRow($i++, $j, 'Uniforme')
            ->setCellValueByColumnAndRow($i++, $j, 'U.Galileo')
            ->setCellValueByColumnAndRow($i++, $j, 'Bolsa Libros')
            ->setCellValueByColumnAndRow($i++, $j, 'Ornato')
            ->setCellValueByColumnAndRow($i++, $j, 'Prestamos')
            ->setCellValueByColumnAndRow($i++, $j, 'Anticipo')
            ->setCellValueByColumnAndRow($i++, $j, 'Desc/Judicial')
            ->setCellValueByColumnAndRow($i++, $j, 'Otros/Desc');

# ESTILO ENCABEZADO PRIMERA HOJA
$styEmp = array(
    'font' => array(
        'bold' => true,
        'size' => 9,
        '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' => '000000') ),
    //'fill' => array('type' => PHPExcel_Style_Fill::FILL_SOLID, 'color' => array('rgb' => 'c3c3c3') )
    'alignment' => array(
        'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
        'wrap' => true,
        )    
);

$styEncabezado = array(
    'font' => array(
        'bold' => true,
        'size' => 9,
        'color' => array('rgb' => '000000')
        //'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' => 'AFAFAF') ),
    //'fill' => array('type' => PHPExcel_Style_Fill::FILL_SOLID, 'color' => array('rgb' => 'c3c3c3') )
    'alignment' => array(
        'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
        'wrap' => true,
        )    
);

$styLineas = array(
    'font' => array(
        'bold' => false,
        'size' => 9,
    ),
    '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('A1:P1')->applyFromArray($styEmp);
$objPHPExcel->getActiveSheet()->getStyle('A2:P2')->applyFromArray($styEncabezado);
$t_lini=1;
$j=3;
$inidep=3;
while ($rec = $db->fetchAssoc($select["nomper"])) {
    $i=$iIni;
    $objPHPExcel->getActiveSheet()
                ->setCellValueByColumnAndRow($i++, $j, $rec["np_cod"])
                ->setCellValueByColumnAndRow($i++, $j, utf8_encode($rec["mae_nom"]." ".$rec["mae_ape"]))
                ->setCellValueByColumnAndRow($i++, $j, $rec["np_isr"])
                ->setCellValueByColumnAndRow($i++, $j, $rec["np_preb"])
                ->setCellValueByColumnAndRow($i++, $j, $rec["np_lib"])
                ->setCellValueByColumnAndRow($i++, $j, $rec["np_carw"])
                ->setCellValueByColumnAndRow($i++, $j, $rec["np_colegia"])
                ->setCellValueByColumnAndRow($i++, $j, $rec["np_inscrip"])
                ->setCellValueByColumnAndRow($i++, $j, $rec["np_uni"])
                ->setCellValueByColumnAndRow($i++, $j, $rec["np_galileo"])
                ->setCellValueByColumnAndRow($i++, $j, $rec["np_bolsa"])
                ->setCellValueByColumnAndRow($i++, $j, $rec["np_ornato"])
                ->setCellValueByColumnAndRow($i++, $j, $rec["np_pree"])
                ->setCellValueByColumnAndRow($i++, $j, $rec["np_anti"])
                ->setCellValueByColumnAndRow($i++, $j, $rec["np_desj"])
                ->setCellValueByColumnAndRow($i++, $j, $rec["np_otrd"]);
    $objPHPExcel->getActiveSheet()->getStyle('A'.$j.':P'.$j)->applyFromArray($styLineas);
    $j+=1;
}
$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(7);
$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(27);
$objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(9);
$objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(9);
$objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(9);
$objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(9);
$objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(9);
$objPHPExcel->getActiveSheet()->getColumnDimension('H')->setWidth(9);
$objPHPExcel->getActiveSheet()->getColumnDimension('I')->setWidth(9);
$objPHPExcel->getActiveSheet()->getColumnDimension('J')->setWidth(9);
$objPHPExcel->getActiveSheet()->getColumnDimension('K')->setWidth(12);
$objPHPExcel->getActiveSheet()->getColumnDimension('L')->setWidth(9);
$objPHPExcel->getActiveSheet()->getColumnDimension('M')->setWidth(9);
$objPHPExcel->getActiveSheet()->getColumnDimension('N')->setWidth(9);
$objPHPExcel->getActiveSheet()->getColumnDimension('O')->setWidth(12);
$objPHPExcel->getActiveSheet()->getColumnDimension('P')->setWidth(9);

$objPHPExcel->getActiveSheet()->getStyle('C3'.':P'.$j)->getNumberFormat()->setFormatCode('###,###,##0.00');
$objPHPExcel->getActiveSheet()->getStyle('A3'.':B'.$j)->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_TEXT);

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

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