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

$dtFeci=$_GET["dtFeci"];
$dtFecf=$_GET["dtFecf"];
$crStat=$_GET["crStat"];

if ($crStat == "T") {
  $textostat="TODAS LAS ORDENES REGISTRADAS";
}
if ($crStat == "A") {
  $textostat="ORDENES QUE ESTAN ABIERTAS";
}
if ($crStat == "C") {
  $textostat="ORDENES QUE ESTAN CERRADAS";
}

# QUERYS
if ($crStat=='T') {
    $sOrdenes = "SELECT *, 
       TRIM(od.od_codp) AS od_codp,
       TRIM(od.od_prov) AS od_prov,
       TRIM(od.od_dirp) AS od_dirp,
       TRIM(od.od_telp) AS od_telp,
       TRIM(od.od_facnom) AS od_facnom,
       TRIM(od.od_facdir) AS od_facdir,
       TRIM(od.od_dirent) AS od_dirent,
       TRIM(od.od_soli) AS od_soli,
       TRIM(od.od_autorizo) AS od_autorizo,
       TRIM(od.od_obs) AS od_obs
       FROM ordendc odd LEFT JOIN ordenc od ON odd.odd_emp=od.od_emp and odd.odd_serie=od.od_serie and odd.odd_num=od.od_num 
       WHERE odd_emp='$empCod' and odd_fec>='$dtFeci' and odd_fec<='$dtFecf' ORDER BY odd_serie,odd_num";
}
if ($crStat=='A') {
    $sOrdenes = "SELECT *, 
       TRIM(od.od_codp) AS od_codp,
       TRIM(od.od_prov) AS od_prov,
       TRIM(od.od_dirp) AS od_dirp,
       TRIM(od.od_telp) AS od_telp,
       TRIM(od.od_facnom) AS od_facnom,
       TRIM(od.od_facdir) AS od_facdir,
       TRIM(od.od_dirent) AS od_dirent,
       TRIM(od.od_soli) AS od_soli,
       TRIM(od.od_autorizo) AS od_autorizo,
       TRIM(od.od_obs) AS od_obs
       FROM ordendc odd LEFT JOIN ordenc od ON odd.odd_emp=od.od_emp and odd.odd_serie=od.od_serie and odd.odd_num=od.od_num 
       WHERE odd_emp='$empCod' and odd_fec>='$dtFeci' and odd_fec<='$dtFecf' and od_stat!='C' ORDER BY odd_serie,odd_num";
}

if ($crStat=='C') {
    $sOrdenes = "SELECT *, 
       TRIM(od.od_codp) AS od_codp,
       TRIM(od.od_prov) AS od_prov,
       TRIM(od.od_dirp) AS od_dirp,
       TRIM(od.od_telp) AS od_telp,
       TRIM(od.od_facnom) AS od_facnom,
       TRIM(od.od_facdir) AS od_facdir,
       TRIM(od.od_dirent) AS od_dirent,
       TRIM(od.od_soli) AS od_soli,
       TRIM(od.od_autorizo) AS od_autorizo,
       TRIM(od.od_obs) AS od_obs
       FROM ordendc odd LEFT JOIN ordenc od ON odd.odd_emp=od.od_emp and odd.odd_serie=od.od_serie and odd.odd_num=od.od_num 
       WHERE odd_emp='$empCod' and odd_fec>='$dtFeci' and odd_fec<='$dtFecf' and od_stat='C' ORDER BY odd_serie,odd_num";
}
# EJECUCION DE QUERYS
$db = new dbExec();
$select["ordendc"] = $db->query($sOrdenes);

$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['ordenes']=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=5;
$objPHPExcel->setActiveSheetIndex($sheet['ordenes'])
            ->setCellValueByColumnAndRow($i, 1, $empNom)
            ->setCellValueByColumnAndRow($i, 2, "LISTADO DE ORDENES DE COMPRA DEL ".strftime("%d/%m/%Y", strtotime($dtFeci))." AL ".strftime("%d/%m/%Y", strtotime($dtFecf)))
            ->setCellValueByColumnAndRow($i, 3, utf8_decode($textostat));

# ESTILO ENCABEZADO PRIMERA HOJA
$styEmp = array(
    'font' => array(
        'bold' => true,
        'size' => 12,
    ),
    'alignment' => array(
        'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
    )
);

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

$styEncabezado = array(
    'font' => array(
        'bold' => true,
        'size' => 9,
        //'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' => 'c3c3c3') )
);

$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()->mergeCells('A1:I1')->getStyle('A1')->applyFromArray($styEmp);
$objPHPExcel->getActiveSheet()->mergeCells('A2:I2')->getStyle('A2')->applyFromArray($styEmp);
$objPHPExcel->getActiveSheet()->mergeCells('A3:I3')->getStyle('A3')->applyFromArray($styEmp);
//$objPHPExcel->getActiveSheet()->getStyle('A5:H5')->applyFromArray($styEncabezado);

$ti_serie="XXXZZZ999";
$ti_num=9999;
$subtot=0;
$tottot=0;
$t_lini=1;
$codp="";
$nomp="";
$clas="";
$clasnom="";

$j=6;
$inidoc=6;
$iniprov=6;
while ($rec = $db->fetchAssoc($select["ordendc"])) {
    if ($t_lini == 1) {
        if ($rec["od_tmone"] == "L") {
           $moneda="LOCAL";
        } else {
           $moneda="DOLARES";
        }   
        $objPHPExcel->getActiveSheet()
            ->setCellValueByColumnAndRow(0, $j, "NUMERO:  ".$rec["od_num"]."         FECHA:  ".strftime("%d/%m/%Y", strtotime($rec["od_fec"])));
        $j+=1;
        $objPHPExcel->getActiveSheet()
            ->setCellValueByColumnAndRow(0, $j, utf8_encode("PROVEEDOR:   ".$rec["od_prov"]));
        $j+=1;
        $objPHPExcel->getActiveSheet()
            ->setCellValueByColumnAndRow(0, $j, utf8_encode("SOLICITADO POR:   ".$rec["od_soli"])."    DIAS CREDITO:  ".$rec["od_cred"]);
        $j+=1;
        $objPHPExcel->getActiveSheet()
            ->setCellValueByColumnAndRow(0, $j, "TASA DE CAMBIO : ".$rec["od_tcam"]."  VALIDAD HASTA:  ".strftime("%d/%m/%Y", strtotime($rec["od_valida"]))."  MONEDA: ".$moneda);
        $j+=1;
        $objPHPExcel->getActiveSheet()
            ->setCellValueByColumnAndRow(0, $j, utf8_encode("OBSERVCIONES: ".$rec["od_obs"]));
        $j+=1;

        $i=$iIni;
        $objPHPExcel->getActiveSheet()
                    ->setCellValueByColumnAndRow($i++, $j, 'CODIGO')
                    ->setCellValueByColumnAndRow($i++, $j, 'DESCRIPCION')
                    ->setCellValueByColumnAndRow($i++, $j, 'MEDIDA')
                    ->setCellValueByColumnAndRow($i++, $j, 'CANTIDAD')
                    ->setCellValueByColumnAndRow($i++, $j, 'COST/UNITARIO')
                    ->setCellValueByColumnAndRow($i++, $j, 'SUBTOTAL')
                    ->setCellValueByColumnAndRow($i++, $j, '%DESCU')
                    ->setCellValueByColumnAndRow($i++, $j, 'VALOR/DESCU.')
                    ->setCellValueByColumnAndRow($i++, $j, '    TOTAL');
        $objPHPExcel->getActiveSheet()->getStyle('A'.$j.':I'.$j)->applyFromArray($styEncabezado); 
        $j+=1;
        $inidoc=6;
    }
    if ($ti_serie!=$rec["odd_serie"]  || $ti_num!=$rec["odd_num"]) {
        if ($t_lini > 1) {
            $i=$iIni;
            $objPHPExcel->getActiveSheet()
                ->setCellValueByColumnAndRow($i++, $j, "")
                ->setCellValueByColumnAndRow($i++, $j, "    TOTAL ESTE DOCUMENTO")
                ->setCellValueByColumnAndRow($i++, $j, "")
                ->setCellValueByColumnAndRow($i++, $j, "")
                ->setCellValueByColumnAndRow($i++, $j, "")
                ->setCellValueByColumnAndRow($i++, $j, "")
                ->setCellValueByColumnAndRow($i++, $j, "")
                ->setCellValueByColumnAndRow($i++, $j, "")
                ->setCellValueByColumnAndRow($i++, $j, '=SUM(I'.$inidoc.':I'.($j-1).')');
            $objPHPExcel->getActiveSheet()->getStyle('I'.$j.':I'.$j)->applyFromArray($styEncabezado); 
            $j+=2;
            if ($rec["od_tmone"] == "L") {
               $moneda="LOCAL";
            } else {
               $moneda="DOLARES";
            }   
            $objPHPExcel->getActiveSheet()
                ->setCellValueByColumnAndRow(0, $j, "NUMERO:  ".$rec["od_num"]."         FECHA:  ".strftime("%d/%m/%Y", strtotime($rec["od_fec"])));
            $j+=1;
            $objPHPExcel->getActiveSheet()
                ->setCellValueByColumnAndRow(0, $j, utf8_encode("PROVEEDOR:   ".$rec["od_prov"]));
            $j+=1;
            $objPHPExcel->getActiveSheet()
                ->setCellValueByColumnAndRow(0, $j, utf8_encode("SOLICITADO POR:   ".$rec["od_soli"])."    DIAS CREDITO:  ".$rec["od_cred"]);
            $j+=1;
            $objPHPExcel->getActiveSheet()
                ->setCellValueByColumnAndRow(0, $j, "TASA DE CAMBIO : ".$rec["od_tcam"]."  VALIDAD HASTA:  ".strftime("%d/%m/%Y", strtotime($rec["od_valida"]))."  MONEDA: ".$moneda);
            $j+=1;
            $objPHPExcel->getActiveSheet()
                ->setCellValueByColumnAndRow(0, $j, utf8_encode("OBSERVCIONES: ".$rec["od_obs"]));
            $j+=1;

            $i=$iIni;
            $objPHPExcel->getActiveSheet()
                        ->setCellValueByColumnAndRow($i++, $j, 'CODIGO')
                        ->setCellValueByColumnAndRow($i++, $j, 'DESCRIPCION')
                        ->setCellValueByColumnAndRow($i++, $j, 'MEDIDA')
                        ->setCellValueByColumnAndRow($i++, $j, 'CANTIDAD')
                        ->setCellValueByColumnAndRow($i++, $j, 'COST/UNITARIO')
                        ->setCellValueByColumnAndRow($i++, $j, 'SUBTOTAL')
                        ->setCellValueByColumnAndRow($i++, $j, '%DESCU')
                        ->setCellValueByColumnAndRow($i++, $j, 'VALOR/DESCU.')
                        ->setCellValueByColumnAndRow($i++, $j, '    TOTAL');
            $objPHPExcel->getActiveSheet()->getStyle('A'.$j.':I'.$j)->applyFromArray($styEncabezado); 
            $j+=1;
            $inidoc=$j;
        }             
        $subtot=0;
        $ti_serie=$rec["od_serie"];
        $ti_num=$rec["od_num"];
        $t_lini=2;
    } 
    $subtot += $rec["odd_tot"];
    $tottot += $rec["odd_tot"];

    $i=$iIni;
    $objPHPExcel->getActiveSheet()
                ->setCellValueByColumnAndRow($i++, $j, $rec["odd_cod"])
                ->setCellValueByColumnAndRow($i++, $j, trim($rec["odd_desc"]))
                ->setCellValueByColumnAndRow($i++, $j, trim($rec["odd_unimed"]))
                ->setCellValueByColumnAndRow($i++, $j, $rec["odd_cant"])
                ->setCellValueByColumnAndRow($i++, $j, $rec["odd_cosu"])
                ->setCellValueByColumnAndRow($i++, $j, $rec["odd_sub"])
                ->setCellValueByColumnAndRow($i++, $j, $rec["odd_pdesc"])
                ->setCellValueByColumnAndRow($i++, $j, $rec["odd_descu"])
                ->setCellValueByColumnAndRow($i++, $j, $rec["odd_tot"]);
    $objPHPExcel->getActiveSheet()->getStyle('A'.$j.':I'.$j)->applyFromArray($styLineas);
    $j+=1;
}
$i=$iIni;
$objPHPExcel->getActiveSheet()
                ->setCellValueByColumnAndRow($i++, $j, "")
                ->setCellValueByColumnAndRow($i++, $j, "    TOTAL ESTE DOCUMENTO")
                ->setCellValueByColumnAndRow($i++, $j, "")
                ->setCellValueByColumnAndRow($i++, $j, "")
                ->setCellValueByColumnAndRow($i++, $j, "")
                ->setCellValueByColumnAndRow($i++, $j, "")
                ->setCellValueByColumnAndRow($i++, $j, "")
                ->setCellValueByColumnAndRow($i++, $j, "")
                ->setCellValueByColumnAndRow($i++, $j, '=SUM(I'.$inidoc.':I'.($j-1).')');
$objPHPExcel->getActiveSheet()->getStyle('I'.$j.':I'.$j)->applyFromArray($styEncabezado); 
$j+=2;
$i=$iIni;
$objPHPExcel->getActiveSheet()
	->setCellValueByColumnAndRow($i++, $j, "")
    ->setCellValueByColumnAndRow($i++, $j, "    TOTAL GENERAL") 
                ->setCellValueByColumnAndRow($i++, $j, "")
                ->setCellValueByColumnAndRow($i++, $j, "")
                ->setCellValueByColumnAndRow($i++, $j, "")
                ->setCellValueByColumnAndRow($i++, $j, "")
                ->setCellValueByColumnAndRow($i++, $j, "")
                ->setCellValueByColumnAndRow($i++, $j, "")
    ->setCellValueByColumnAndRow($i++, $j, '=SUMIF(B6:B'.($j-1).',"    TOTAL ESTE DOCUMENTO",I6:I'.($j-1).')');
$objPHPExcel->getActiveSheet()->getStyle('I'.$j.':I'.$j)->applyFromArray($styEncabezado);


$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(20);
$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(45);
$objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(15);
$objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(15);
$objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(15);
$objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(15);
$objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(15);
$objPHPExcel->getActiveSheet()->getColumnDimension('H')->setWidth(15);
$objPHPExcel->getActiveSheet()->getColumnDimension('I')->setWidth(15);
$objPHPExcel->getActiveSheet()->getColumnDimension('J')->setWidth(15);

$objPHPExcel->getActiveSheet()->getStyle('D6'.':D'.$j)->getNumberFormat()->setFormatCode('###,###,##0.00');
$objPHPExcel->getActiveSheet()->getStyle('E6'.':E'.$j)->getNumberFormat()->setFormatCode('###,###,##0.00000');
$objPHPExcel->getActiveSheet()->getStyle('F6'.':F'.$j)->getNumberFormat()->setFormatCode('###,###,##0.00000');
$objPHPExcel->getActiveSheet()->getStyle('G6'.':G'.$j)->getNumberFormat()->setFormatCode('###,###,##0.00');
$objPHPExcel->getActiveSheet()->getStyle('H6'.':H'.$j)->getNumberFormat()->setFormatCode('###,###,##0.00');
$objPHPExcel->getActiveSheet()->getStyle('I6'.':I'.$j)->getNumberFormat()->setFormatCode('###,###,##0.00000');

$objPHPExcel->getActiveSheet()->getStyle('A6'.':C'.$j)->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_TEXT);

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

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