<?php



$serverName = "(local)\SQLEXPRESS"; //serverName\SQLINSTANCIA
//$serverName = "(local)\SQLINSTANCIA"; //serverName\SQLINSTANCIA
// Since UID and PWD are not specified in the $conn2ectionInfo array,
// The connection will be attempted using Windows Authentication.
$conn2ectionInfo = array( "Database"=>"prefrio","UID"=>"sa","PWD"=>"ats475");
$conn2 = sqlsrv_connect( $serverName, $conn2ectionInfo);
$mensaje="";
$itemSelect=array();

if( $conn2 ) {

$boton=@$_REQUEST["boton"];
$idproceso=@$_REQUEST["idproceso"];


    if ($boton) {
        @ob_start();
        /*
        header("Content-type: text/csv");
        header("Content-Disposition: attachment; filename=proceso{$idproceso}.csv");
        header("Pragma: no-cache");
        header("Expires: 0");
        */

        $sql="select top(1) valor from pf_configuracion where id_configuracion='nombre_planta'";
        $stmt = sqlsrv_query($conn2, $sql);
        $row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC);

        $nomPlanta=$row['valor'];

        @sqlsrv_free_stmt( $stmt);



        $sql = /** @lang text */
            "SELECT '$nomPlanta' planta
                ,pp.id_camara
                , pp.id_proceso
                ,RIGHT('00' + CAST(DATEPART(dd, DATEADD(MINUTE,pp.fecha_inicio,'2005-01-01')) AS varchar(2)), 2) 
                +'/'+RIGHT('00' + CAST(DATEPART(mm, DATEADD(MINUTE,pp.fecha_inicio,'2005-01-01')) AS varchar(2)), 2) 
                +'/'+RIGHT('0000' + CAST(DATEPART(YYYY, DATEADD(MINUTE,pp.fecha_inicio,'2005-01-01')) AS varchar(4)), 4)
                +' '+RIGHT('00' + CAST(DATEPART(HH, DATEADD(MINUTE,pp.fecha_inicio,'2005-01-01')) AS varchar(2)), 2)
                +':'+RIGHT('00' + CAST(DATEPART(MINUTE, DATEADD(MINUTE,pp.fecha_inicio,'2005-01-01')) AS varchar(2)), 2) fechainicio
                ,RIGHT('00' + CAST(DATEPART(dd, DATEADD(MINUTE,pp.fecha_fin,'2005-01-01')) AS varchar(2)), 2) 
                +'/'+RIGHT('00' + CAST(DATEPART(mm, DATEADD(MINUTE,pp.fecha_fin,'2005-01-01')) AS varchar(2)), 2) 
                +'/'+RIGHT('0000' + CAST(DATEPART(YYYY, DATEADD(MINUTE,pp.fecha_fin,'2005-01-01')) AS varchar(4)), 4)+' '
                +RIGHT('00' + CAST(DATEPART(HH, DATEADD(MINUTE,pp.fecha_fin,'2005-01-01')) AS varchar(2)), 2)
				+':'+RIGHT('00' + CAST(DATEPART(MINUTE, DATEADD(MINUTE,pp.fecha_fin,'2005-01-01')) AS varchar(2)), 2) fechafin
                ,'99,99' tempfinal
				,tp.id_tarja
				,tp.con_sensor pinchado
				,RIGHT('00' + CAST(DATEPART(dd, DATEADD(MINUTE,hp.fecha,'2005-01-01')) AS varchar(2)), 2) 
                +'/'+RIGHT('00' + CAST(DATEPART(mm, DATEADD(MINUTE,hp.fecha,'2005-01-01')) AS varchar(2)), 2) 
                +'/'+RIGHT('0000' + CAST(DATEPART(YYYY, DATEADD(MINUTE,hp.fecha,'2005-01-01')) AS varchar(4)), 4)
				+' '+RIGHT('00' + CAST(DATEPART(HH, DATEADD(MINUTE,hp.fecha,'2005-01-01')) AS varchar(2)), 2)
                +':'+RIGHT('00' + CAST(DATEPART(MINUTE, DATEADD(MINUTE,hp.fecha,'2005-01-01')) AS varchar(2)), 2) fechalectura
                ,hp.valor
                ,hp.sensor
                ,hp.sensor_tipo
             FROM pf_proceso pp
                INNER JOIN pf_historico_proceso hp ON pp.id_proceso=hp.proceso
				inner join pf_tarjaxproceso tp on pp.id_proceso=tp.id_proceso
            where pp.id_proceso={$idproceso}
                order by hp.fecha
            ";
        $stmt = sqlsrv_query($conn2, $sql);
        if ($stmt === false) {
            die(print_r(sqlsrv_errors(), true));
        }

        $csvArr = array();
        while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
            if ($row !== null) {
                $csvArr[] = $row;

            }
        }
        $finalRow = end($csvArr);
        $finalTemp = str_replace(',', '.', $finalRow['valor'] / 10);
        $finalContent="";

//$out = fopen('php://output', 'w');
        foreach ($csvArr as $row) {
			$idcamara=$row['id_camara'];
			$fechainicio=str_replace('/','',$row['fechainicio']);
            $row['tempfinal'] = $finalTemp;
            $row['valor'] = str_replace(',', '.', $row['valor'] / 10);
            $txtArr = array();
            foreach ($row as $cell) {
                $txtArr[] = '' . $cell . '';
            }
            $finalContent.= implode(',', $txtArr) . "\n";
        }
        $fechaSolo=explode(' ',$fechainicio);
		$fileName=$fechaSolo[0].' '.$idcamara." ".$idproceso.".csv";
        $fileName=str_replace(' ',"\x20",$fileName);
        $fileName=str_replace(':','_',$fileName);
        var_dump($fileName);

        $f = fopen("c:\\ats\\".$fileName, "w");

        fwrite($f, $finalContent);
        fclose($f);


        die(1);
    } else {
        $sql = /** @lang text */
            "SELECT pp.id_proceso,pp.id_camara
          ,RIGHT('00' + CAST(DATEPART(dd, DATEADD(MINUTE,pp.fecha_inicio,'2005-01-01')) AS varchar(2)), 2) 
          +RIGHT('00' + CAST(DATEPART(mm, DATEADD(MINUTE,pp.fecha_inicio,'2005-01-01')) AS varchar(2)), 2) 
          +RIGHT('0000' + CAST(DATEPART(YYYY, DATEADD(MINUTE,pp.fecha_inicio,'2005-01-01')) AS varchar(4)), 4)+' '
          +RIGHT('00' + CAST(DATEPART(HH, DATEADD(MINUTE,pp.fecha_inicio,'2005-01-01')) AS varchar(2)), 2)
          +RIGHT('00' + CAST(DATEPART(MINUTE, DATEADD(MINUTE,pp.fecha_inicio,'2005-01-01')) AS varchar(2)), 2) fecha_inicio          
             FROM pf_proceso pp
             order by pp.id_proceso
            ";
        $stmt = sqlsrv_query($conn2, $sql);
        if ($stmt === false) {
            die(print_r(sqlsrv_errors(), true));
        }

        while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
            if ($row !== null) {
                $itemSelect[] = $row;
            }
        }
    }


}else{
    $mensaje="No se puede conectar a la base de datos";
}


//fclose($out);


include "gencsview.php";

@sqlsrv_free_stmt( $stmt);
?>


