<?php
// $id = "c093nhfid83";
// $file = "/var/www/html/";
// $file2 = ".csv";
// $file3 = $file + $id;
// // echo $id;
// // echo $file;
// // echo $file2;
// $file3 = "/var/www/html/$id.csv";

// $date = new DateTime();
// $timestamp = $date->getTimestamp();

// $file = "/var/www/html/$id.csv?$timestamp";
// echo $file;


    $id = $_POST["id"];  // get internal sensor id from js
    // echo('run');
    require '../php/database.php';
// Check connection

    $sql_query = "SELECT timestamp, temp FROM $id";

    // Gets the data from the database
    $result = $mysqli->query($sql_query);
    $f = fopen('php://temp', 'wt');
    $first = true;
    while ($row = $result->fetch_assoc()) {
        if ($first) {
            fputcsv($f, array_keys($row));
            $first = false;
        }
        fputcsv($f, $row, ",", " ");  // write row to csv file and remove double quotes
    } // end while

    // echo('run2');
    $mysqli->close();

    $size = ftell($f);
    rewind($f);
    // echo $size;
    
    // $date = new DateTime();
    // $timestamp = $date->getTimestamp();
    // echo $timestamp;

    $file = "/var/www/html/$id.csv";
    // header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    // header("Content-Length: $size");
    // Output to browser with appropriate mime type, you choose ;)
    // header("Content-type: text/x-csv");
    // header("Content-type: text/csv");
    // header("Content-type: application/csv");
    header("Cache-Control: max-age=0, no-cache, no-store, must-revalidate"); // HTTP/1.1
    // header("Expires: Wed, 11 Jan 1984 05:00:00 GMT"); // Date in the past
    clearstatcache();
    file_put_contents($file, $f);
    // fpassthru($f);
    // exit;

