<?php

session_start();

date_default_timezone_set('America/Lima');



if (PHP_SAPI == 'cli')

  die('Se visualiza solamente desde un navegador.');



/** Include PHPExcel */

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



require_once ("../../config/Cado.php");

require_once ("cVenta.php");

$oVenta = new cVenta();

require_once ("../venta/cVentapago.php");

$oVentapago = new cVentapago();

require_once ("../ingreso/cIngreso.php");

$oIngreso = new cIngreso();

require_once ("../formatos/formato.php");



$dts1=$oVenta->mostrar_filtro(fecha_mysql($_POST['txt_fil_ven_fec1']),fecha_mysql($_POST['txt_fil_ven_fec2']),$_POST['cmb_fil_ven_doc'],$_POST['hdd_fil_cli_id'],$_POST['cmb_fil_ven_est'],$_POST['cmb_fil_ven_id'],$_POST['cmb_fil_usu_id'],$_POST['cmb_fil_punven_id'],$_SESSION['empresa_id']);

/*while ($dts11 = mysql_fetch_array($dts1)) {

  $nom = $dts11['tb_venta_nom'];

}*/

$num_rows= mysql_num_rows($dts1);



// Create new PHPExcel object

$objPHPExcel = new PHPExcel();



// Set document properties

$objPHPExcel->getProperties()->setCreator("Inticap.com")

->setLastModifiedBy("Inticap.com")

->setTitle("Reporte")

->setSubject("Reporte")

->setDescription("Reporte generado por inticap.com")

->setKeywords("")

->setCategory("reporte excel");



$objPHPExcel->setActiveSheetIndex(0);

$c=1;

$estiloTituloColumnas = array(

  'font' => array(

    'name'  => 'Arial',

    'bold'  => true,

    'size'  =>8,

    'color' => array(

      'rgb' => '000000'

      )

    ),

  'fill' => array(

    'type'  => PHPExcel_Style_Fill::FILL_SOLID,

    'color' => array(

      'rgb' => 'FAFAFA')

    ),

  'borders' => array(

    'outline' => array(

      'style' => PHPExcel_Style_Border::BORDER_THIN ,

      'color' => array(

        'rgb' => '143860'

        )

      )

    ),

  'alignment' =>  array(

    'horizontal'=> PHPExcel_Style_Alignment::HORIZONTAL_CENTER,

    'vertical'  => PHPExcel_Style_Alignment::VERTICAL_CENTER,

    'wrap'      => TRUE

    )

  );

  $titulosColumnas = array(

  'FECHA',

  'DOCUMENTO',

  'CLIENTE',

  'RUC/DNI', 

  'TOTAL',

  'PAGOS',

  'SALDOS',

  'VENDEDOR',

  'ESTADO'

  );



  /*foreach ($nom as $val) {

      array_push($titulosColumnas, $val);

  }*/



  $letras = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z');



  $letracolumn = 0;

  for ($i=0; $i < count($titulosColumnas) ; $i++) { 

    $letracolumn = $i;

    $objPHPExcel->getActiveSheet()->setCellValue($letras[$i].$c, $titulosColumnas[$i]);

  }

  $objPHPExcel->getActiveSheet()->getStyle("A$c:".$letras[$letracolumn]."$c")->applyFromArray($estiloTituloColumnas);



  if($num_rows>0){

    $c=$c+1;

    while($dt1 = mysql_fetch_array($dts1))

    {

     

      $total_valven+=$dt1['tb_venta_valven'];

      $total_igv+=$dt1['tb_venta_igv'];

      $total_ventas +=$dt1['tb_venta_tot'];



      $total_pagar += $dt1['tb_venta_tot'];



      $dts2=$oVentapago->filtrar($dt1['tb_venta_id']);

      while($dt2 = mysql_fetch_array($dts2))

      {

        $monto = $dt2['tb_ventapago_mon']; 

        $abonos=0;



        $mod_id=3;

        $est=1;

        $dts3 = $oIngreso->mostrar_por_modulo($mod_id,$dt2['tb_ventapago_id'],$est);

        while($dt3 = mysql_fetch_array($dts3))

        {

          $abonos+= $dt3['tb_ingreso_imp'];

        } 

        mysql_free_result($dts3);



        $saldo = ($monto - $abonos);



        $total_abono+=$abonos;

        $total_saldo+=$saldo;

      }

    

    $filas=0;

    $rw1=$oVenta->mostrar_venta_detalle($dt1['tb_venta_id']);

    $filas= mysql_num_rows($rw1);

    $detalle="";

    

    if(!$filas>0)

    {

      $detalle="Vacío";

    }



	if($dt1['tb_venta_est']==1){

		$est = "REGISTRADA";

	}else if($dt1['tb_venta_est']==2){

		$est = "ANULADA";

	}

	

    $objPHPExcel->getActiveSheet(0)

    ->setCellValue('A'.$c, mostrarFecha($dt1['tb_venta_fec']))

    ->setCellValue('B'.$c, $dt1['tb_documento_abr'].' '.$dt1['tb_venta_numdoc'])    

    ->setCellValue('C'.$c, $dt1['tb_cliente_nom'])

    ->setCellValue('D'.$c, $dt1['tb_cliente_doc'])

    ->setCellValue('E'.$c, formato_money($dt1['tb_venta_tot']))   

    ->setCellValue('F'.$c, formato_money($abonos))

    ->setCellValue('G'.$c, formato_money($saldo))

    ->setCellValue('H'.$c, $dt1['tb_usuario_nom'])



    ->setCellValue('I'.$c,$est );

    //->setCellValue('J'.$c, $array_stock_almacenes[1])

    //->setCellValue('K'.$c, $array_stock_almacenes[2])

    //->setCellValue('L'.$c, $array_stock_almacenes[3])

    //->setCellValue('M'.$c, $array_stock_almacenes[4]);



    $objPHPExcel->getActiveSheet(0)->getStyle("E$c:I$c")->getNumberFormat()->setFormatCode('0.00');

    $c++;



  }

  mysql_free_result($dts1);

  

}

/*

 if($_SESSION['usuariogrupo_id']==2){



   $objPHPExcel->getActiveSheet()

      ->setCellValue('A'.$c, "TOTAL")   

      ->setCellValue('E'.$c, formato_money($total_pagar))

      ->setCellValue('F'.$c, formato_money($total_abono))

      ->setCellValue('G'.$c, formato_money($total_saldo))

      ->setCellValue('H'.$c, &nbsp;)   

      ->setCellValue('I'.$c, &nbsp;)

      ->setCellValue('J'.$c, &nbsp;)



  $objPHPExcel->getActiveSheet(0)->getStyle("E$c:I$c")->getNumberFormat()->setFormatCode('0.0000');



}

for($z = 'A'; $z <= 'M'; $z++){

  $objPHPExcel->getActiveSheet()->getColumnDimension($z)->setAutoSize(TRUE);

}



$objPHPExcel->getActiveSheet()->freezePane('A2');*/

$objPHPExcel->getActiveSheet()->setTitle('TABLA VENTAS');





$nombre_archivo="Informe ventas ".date('d-m-Y-h:i');



// Redirect output to a client’s web browser (Excel5)

//header('Content-Type: application/vnd.ms-excel');

//header('Content-Disposition: attachment;filename="'.$nombre_archivo.'.xls"');



// Redirect output to a client’s web browser (Excel2007)

header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');

header('Content-Disposition: attachment;filename="'.$nombre_archivo.'.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, 'Excel5');

$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');



$objWriter->save('php://output');

exit;





?>



