<?php

$id = $_POST["id"];  // get internal sensor id from js
$temp = $_POST["data"];
$date = date('Y/m/d H:i:s');
$filename = "../chartData/$id.csv";

// first we check if file exists, if not create and add CSV headers
if (is_writable($filename)) {
}
else {
    // create file
    if (!$handle = fopen($filename, 'w')) {
        //  echo "Cannot open file";
         exit;
    }
    $data = "Timestamp, Temperature\n";
    // Write to  file.
    if (fwrite($handle, $data) === FALSE) {
        // echo "Cannot write to file";
        exit;
    }
    fclose($handle);
}

$data = "$date, $temp\n";  // create string of data to save to csv file

if (is_writable($filename)) {  // check if file exists

    // open file
    if (!$handle = fopen($filename, 'a')) {
        //  echo "Cannot open file";
         exit;
    }

    // Write to file.
    if (fwrite($handle, $data) === FALSE) {
        // echo "Cannot write to file";
        exit;
    }
    fclose($handle);

} else {
    // can't write to file
}