<?php
ini_set('memory_limit', '1024M');
include("conexion/conexion.php");
$perfil = $_SESSION['perfil'];
$cliente = $_GET['cliente'];
$est_gestion = $_GET['est_gestion'];
$fini = $_GET['fini'];
$ffin = $_GET['ffin'];
$fprod = $_GET['_prod'];
$nombre_arch = str_replace(' ', '_', trim($_GET['nom_arc'])) . '_' . $fini . '_' . $ffin;
$pregunta = $_GET['pregunta'];
$campos_consulta = $_SESSION['campos_consulta'];

if ($perfil == 5) {
    $_and = " and a.id_cliente='" . $cliente . "'";
} else {
    $_and = " ";
}
if (!empty($fprod)) {
    $preg_prod = " and b.producto='" . $fprod . "'";
}


$condicion = " where a.id_estado in " . $est_gestion . " and a.fecha_cargue between '" . $fini . "' and '" . $ffin . "'" . $_and . $preg_prod;
$campos_consulta = $campos_consulta . "";
$rst = "SELECT " . $campos_consulta . " FROM guias_proceso as a inner join ordenes as b on a.orden=b.orden inner join estados_gestion
as e on a.id_estado=e.id_estado " . $condicion;

class export_txt {

    function crear_csv($nombre_file, $rst) {
        $this->conexionObj2 = new conexion();
        $this->conexionObj2->conectarse();
        unset($add);
        unset($titulos);
        $elCSV = $_SESSION['header'];
        $elCSV .= "\r\n";
        $csvName = $nombre_file . ".csv";
        exec("chmod 777 export_cvs.php");
        $fileHandle = fopen($csvName, 'w') or die('NO SE CREO EL ARCHIVO .CSV, INTENTE MAS TARDE.');
        $campos_consulta = $_SESSION['campos_consulta'];

        $titulos = $_SESSION['titulos'];
        $rst_csv = $this->conexionObj2->consultar($rst);
        while ($row_csv = mysql_fetch_array($rst_csv)) {
            for ($j = 0; $j <= 21; $j++) {
                if ($j == 0) {
                    $elCSV .= $row_csv[0];
                    //fwrite($fileHandle, $elCSV);
                } else {
                    $elCSV .= ";" . $row_csv[$j];                    
                }
            }
            $elCSV .= "\n";
            //fwrite($fileHandle, $elCSV);
        }
        fclose($fileHandle);
        header('Content-Type: application/csv');
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Last-Modified: ' . date('D, d M Y H:i:s'));
        header('Content-Disposition: attachment; filename="' . $csvName . '"');
        echo($elCSV);
        return $csvName;
    }

}

$export_txtObj = new export_txt();
$csvName = $export_txtObj->crear_csv($nombre_arch, $rst);
exec("chmod 777 $csvName");
exec("rm $csvName");
?>