<?php

ini_set('memory_limit', '1024M');
include("conexion/conexion.php");
$conexionObj2 = new conexion();
$conexionObj2->conectarse();
$fecha_actual = date("Y-m-d");
$csvName = 'ConsultaZonasEstados' . $fecha_actual . '.csv';
if (file_exists($csvName)) {
    unlink($csvName);
}

$consOds = $_GET['orden'];

$StrZonas = "select distinct(cod_zona) as cod_zona from guias_proceso where orden='" . $consOds . "'";
$ResZonas = $conexionObj2->consultar($StrZonas);
$cntz = mysql_num_rows($ResZonas);
$cadena = "ESTADOS;";
if ($cntz > 0) {
    while ($CurZonas = mysql_fetch_array($ResZonas)) {
        $ArrZona[] = $CurZonas['cod_zona'];
        $cadena .= trim($CurZonas['cod_zona']) . ';';
    }
    $cadena = substr($cadena, 0, -1);
    $cadena .=chr(13) . chr(10);



    $StrDev = "select id_devolucion,nombre from devoluciones";
    $ResDev = $conexionObj2->consultar($StrDev);
    $cadena .= "ENTREGADAS;";


/////////Entregadas
    foreach ($ArrZona as $valor) {
        $strmysql = "select count(*) as total from guias_proceso where cod_zona='" . $valor . "' and id_estado in(14,15) and orden='" . $consOds . "'";
        $ResCta = $conexionObj2->consultar($strmysql);
        $CurCta = mysql_fetch_array($ResCta);
        $cadena .= trim($CurCta["total"]) . ';';
    }
    $cadena = substr($cadena, 0, -1);
    $cadena .=chr(13) . chr(10);



//    /////////Pendientes
    $cadena .= "PENDIENTES;";
    foreach ($ArrZona as $valor) {
        $strmysql = "select count(*) as total from guias_proceso where cod_zona='" . $valor . "' and id_estado=13 and orden='" . $consOds . "'";
        $ResCta = $conexionObj2->consultar($strmysql);
        $CurCta = mysql_fetch_array($ResCta);
        $cadena .= trim($CurCta["total"]) . ';';
    }
    $cadena = substr($cadena, 0, -1);
    $cadena .=chr(13) . chr(10);

    while ($CurDev = mysql_fetch_array($ResDev)) {
        $coddevo = $CurDev['id_devolucion'];
        $cadena .= trim($CurDev['nombre']) . ';';


        foreach ($ArrZona as $valor) {
            $strmysql = "select count(*) as total from guias_proceso where cod_zona='" . $valor . "' and id_devolucion='" . $coddevo . "' and orden='" . $consOds . "'";
            $ResCta = $conexionObj2->consultar($strmysql);
            $CurCta = mysql_fetch_array($ResCta);
            $cadena .= trim($CurCta["total"]) . ';';
        }
        $cadena = substr($cadena, 0, -1);
        $cadena .=chr(13) . chr(10);
    }

    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 $cadena;
}
?>