<?php

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

$consCli = $_GET['cliente'];
$consF1 = $_GET['F1'];
$consF2 = $_GET['F2'];

$archivo = fopen($csvName, "a+");
$cadena = 'ORDEN;PRODUCTO;FECHA;TOTAL;ENTREGADAS;DEVOLUCION;PENDIENTES;NOVEDADINICIAL' . chr(13) . chr(10);
fwrite($archivo, $cadena);
fclose($archivo);

$strconsorden = "select a.orden,a.fecha_creacion,a.producto,b.nombre from ordenes as a inner join clientes as b
                            on a.id_cliente=b.id_cliente where fecha_creacion>='" . $consF1 . "' and
                            fecha_creacion<='" . $consF2 . "' and a.id_cliente='" . $consCli . "' order by fecha_creacion desc";
$resul = $conexionObj2->consultar($strconsorden);

while ($CurOds = mysql_fetch_array($resul)) {
    $StrOds = trim($CurOds['orden']);

    $StrEst = "SELECT id_estado,nombre,space(11) as total  from estados_gestion where id_estado>=12 and id_estado<=18 ORDER BY id_estado ";
    $ResEst = $conexionObj2->consultar($StrEst);

    $TotalOrden = 0;
    $TotalEnt = 0;
    $TotalPend = 0;
    $TotalDev = 0;
    $TotalNov = 0;

    while ($CurEst = mysql_fetch_array($ResEst)) {
        $codigo = $CurEst['id_estado'];
        $strsql = "SELECT count(*) FROM guias_proceso WHERE id_estado = '" . $codigo . "' and orden='" . $StrOds . "'";
        $ResTot = $conexionObj2->consultar($strsql);
        $reg = mysql_fetch_array($ResTot);
        $ArrTotales[] = $reg[0];
        $TotalOrden = $TotalOrden + $reg[0];

        if ($codigo == '12' or $codigo == '13') {
            $TotalPend = $TotalPend + $reg[0];
        }

        if ($codigo == '14' or $codigo == '15') {
            $TotalEnt = $TotalEnt + $reg[0];
        }

        if ($codigo == '16') {
            $TotalDev = $TotalDev + $reg[0];
        }

        if ($codigo == '18') {
            $TotalNov = $TotalNov + $reg[0];
        }
    }



    $cadena .= trim($StrOds) . ';' . trim($CurOds['producto']) . ';' . $CurOds['fecha_creacion'] . ';' . $TotalOrden . ';' .
            $TotalEnt . ';' . $TotalDev . ';' . $TotalPend . ';' . $TotalNov . 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;
    
?>