<?php

ini_set('memory_limit', '1024M');
include("conexion/conexion.php");

class export_txt {

    function crear_csv($nombre_file, $reg, $est, $dev) {
        $this->conexionObj2 = new conexion();
        $this->conexionObj2->conectarse();
        unset($add);
        unset($titulos);
        $elCSV = $_SESSION['header'];
        $elCSV .= "\r\n";
        $csvName = $nombre_file . ".csv";
        //"Reporte_". date('Ymd') .".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'];
        $add = $_SESSION['sadd1'];

        $titulos = $_SESSION['titulos'];
        $rst_csv = $this->conexionObj2->consultar("SELECT $campos_consulta FROM guias_proceso $add");
        while ($row_csv = mysql_fetch_array($rst_csv)) {
            for ($j = 0; $j <= $dev; $j++) {
                if ($j == 0) {
                    $elCSV .= $row_csv[0];
                } 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($_GET['nomcsv'], $_GET['registro'], $_GET['estado'], $_GET['dev']);
exec("chmod 777 $csvName");
exec("rm $csvName");
?>