<?php
/*
********************************************************************************

    filename:    functions.php
    description: functions and constants

********************************************************************************
*/
/*
    ... doneness constants
*/
    define("DONENESSEXTRARARE", "Extra Rare");
    define("DONENESSRARE", "Rare");
    define("DONENESSMEDIUMRARE", "Medium Rare");
    define("DONENESSMEDIUM", "Medium");
    define("DONENESSMEDIUMWELL", "Medium Well");
    define("DONENESSWELLDONE", "Well Done");
    define("DONENESSOVERCOOKED", "Overcooked");
    define("DONENESSES", "doneness ENUM('Extra Rare', 'Rare', 'Medium Rare', 'Medium', 'Medium Well', 'Well Done', 'Overcooked') NULL");
/*
    ... burn state constants
*/
    define("BURNREADY", "Ready");
    define("BURNPREHEATING", "Preheating");
    define("BURNCOOKING", "Cooking");
    define("BURNCHECKING", "Checking");
    define("BURNDONE", "Done");
    define("BURNSTATES", "burnState ENUM('Ready','Preheating','Cooking','Checking','Done') NULL");
/*
    ... cook state constants
*/
    define("COOKOFF", "Off");
    define("COOKPREHEATING", "Preheating");
    define("COOKNEARREADY", "Near Ready");
    define("COOKREADY", "Ready");
    define("COOKLOW", "Cook Low");
    define("COOKOK", "Cook OK");
    define("COOKHIGH", "Cook High");
    define("COOKSTATES", "cookState ENUM('Off','Preheating','Near Ready','Ready','Low','OK','High') NULL");
/*
    ... food state constants
*/
    define("FOODRAW", "Raw");
    define("FOODCOOKING", "Cooking");
    define("FOODNEARDONE", "Near Done");
    define("FOODDONE", "Done");
    define("FOODOVERDONE", "Over Done");
    define("FOODSTATES", "foodState ENUM('Raw','Cooking','Near Done','Done','Over Done') NULL");
/*
    ... temp scale constants
*/
    define("TEMPSCALEF", "F");
    define("TEMPSCALEC", "C");
    define("TEMPSCALE", "tempScale ENUM ('F', 'C') NOT NULL");
/*
    ... burn mode constants
*/
    define("BURNMODEAUTO", "Auto");
    define("BURNMODEMANUAL", "Manual");
    define("BURNMODE", "burnMode ENUM ('Auto', 'Manual') NOT NULL");
/*
   ... convert Fahrenheit to Celsius
*/
    function FtoC($tF) {
        $tC=($tF-32.0) * 5 / 9;
        return $tC;
    }
/*
   ... convert Celsius to Fahrenheit
*/
    function CtoF($tC) {
        $tF = 9 / 5 * $tC + 32.0;
        return $tF;
    }
/*
   ... convert Fahrenheit to Kelvin
*/
    function tK($tF) {
        $tC=($tF-32.0) * 5 / 9;
        $tK = $tC + 273.15;
        return $tK;
    }
/*
   ... convert Kelvin to Fahrenheit
*/
    function tF($tK) {
        $tC = $tK - 273.15;
        $tF = 9 / 5 * $tC + 32.0;
        return $tF;
    }
/*
   ... convert Celsius to Kelvin
*/
    function CtoK($tC) {
        $tK = $tC + 273.15;
        return $tK;
    }
/*
   ... convert Kelvin to Celsius
*/
    function KtoC($tK) {
        $tC = $tK - 273.15;
        return $tC;
    }

    function initCurrentProbes() {
        $conn = connectToDB();
        for ($i = 1; $i <= 8; $i++) {
            $sql = "UPDATE currentprobes SET probeTemp = 0, targetTemp = 0, highTemp = 0, lowTemp = 0 WHERE probePosition = $i";
            if (!mysqli_query($conn, $sql)) {
                echo "Error: " . $sql . "<br>" . mysqli_error($conn);
            }
        }
        mysqli_close($conn);
    }

/*
    ... connect to database
*/
    function connectToDB() {
        $servername = "localhost";
        $burnbotPasswordFile = fopen("burnbotpassword.txt", "r");
        $password = fgets($burnbotPasswordFile);
        fclose($burnbotPasswordFile);
/*
        ... HostMonster
*/
        $username = "polycent_jmyort";
        $dbname = "polycent_burnbot";
        $conn = mysqli_connect($servername, $username, $password, $dbname);
        if (!$conn) {
/*
            ... RPi
*/
            $username = "root";
            $dbname = "burnbot";
            $conn = mysqli_connect($servername, $username, $password, $dbname);
            if (!$conn) {
                die("Connection failed: " . mysqli_connect_error());
            }
        }
        return $conn;
    }
/*
    ... get doneness order
*/
    function getDonenessIndex($doneness) {
        switch ($doneness) {
        case "Extra Rare":
            $donenessIndex = 1;
            break;
        case "Rare":
            $donenessIndex = 2;
            break;
        case "Medium Rare":
            $donenessIndex = 3;
            break;
        case "Medium":
            $donenessIndex = 4;
            break;
        case "Medium Well":
            $donenessIndex = 5;
            break;
        case "Well Done":
            $donenessIndex = 6;
            break;
        case "Overcooked":
            $donenessIndex = 7;
            break;
        default:
            $donenessIndex = 0;
        }
        return $donenessIndex;        
    }
/*
    ... get current burn
*/
    function getCurrentBurn() {
//        $conn = connectToDB();
        $sql = "SELECT burnId, burnState, numberProbes, startDateTime, endDateTime,
            blowerSpeed, ventPosition,
            foodId, food, doneness, comments, pitId, pitManufacturer, pitModel,
            blowerP, blowerI, blowerD, ventP, ventI, ventD
            FROM currentburn WHERE currentBurnId=1";
//        $result = mysqli_query($conn, $sql);            
//        $row = mysqli_fetch_assoc($result);
//        mysql_close($conn);
        $row = getRow($sql);
        return $row;
    }
/*
    ... get current probes
*/
    function getCurrentProbes() {
//        $rows = array();
//        $conn = connectToDB();
        $sql = "SELECT probeId, probePosition, probeTemp, targetTemp, highTemp, lowTemp,
            manufacturer, model, a, b, c FROM currentprobes";
//        $result = mysqli_query($conn, $sql);
//        if (mysqli_num_rows($result) > 0) {
//            while($row = mysqli_fetch_assoc($result)) {
//                array_push($rows, $row);
//            }
//        }
//        mysql_close($conn);
        $rows = getRows($sql);
        return ($rows);
    }
/*
   ... get burns
*/
    function getBurns() {
        $sql = "SELECT burnId, startDateTime, endDateTime,
            foodId, food, doneness, comments,
            pitId, pitManufacturer, pitModel,
            blowerP, blowerI, blowerD, ventP, ventI, ventD
            FROM burns";
        $rows = getRows($sql);
        return ($rows);
    }
/*
   ... get burn
*/
    function getBurn($burnId) {
        $sql = "SELECT burnId, startDateTime, endDateTime,
            foodId, food, doneness, comments,
            pitId, pitManufacturer, pitModel,
            blowerP, blowerI, blowerD, ventP, ventI, ventD
            FROM burns WHERE burnId=$burnId";
        $row = getRow($sql);
        return ($row);
    }
/*
    ... delete burn
*/
    function deleteBurn($burnId) {
        if ($burnId != "") {
            $sql = "DELETE FROM burns WHERE burnId = $burnId";
            if (!mysqli_query($conn, $sql)) {
                error_log("Error deleting burn: " . $sql . " " . mysqli_error($conn));
            }
            $sql = "DELETE FROM statuses WHERE burnId = $burnId";
            if (!mysqli_query($conn, $sql)) {
                error_log("Error deleting burn: " . $sql . " " . mysqli_error($conn));
            }
        } else {
            error_log("Error deleting burn: blank burnId");
        }
    }
/*
   ... get statuses
*/
    function getStatuses($burnId) {
                if ($burnId == 0) {
                    $sql = "SELECT statusId, burnId, burnState, probeId, probePosition,
                        statusDateTime, probeTemp, targetTemp, highTemp, lowTemp, blowerSpeed, ventPosition
                        FROM statuses";
                } else {
                    $sql = "SELECT statusId, burnId, burnState, probeId, probePosition,
                        statusDateTime, probeTemp, targetTemp, highTemp, lowTemp, blowerSpeed, ventPosition
                        FROM statuses WHERE burnId = $burnId";
                }
        $rows = getRows($sql);
        return ($rows);
    }
/*
   ... get foods
*/
    function getFoods() {
        $sql = "SELECT foodId, food, doneness, externalTemp, externalHighTemp, externalLowTemp,
            internalTemp, internalHighTemp, internalLowTemp, comments FROM foods";
        $rows = getRows($sql);
        return ($rows);
    }
/*
    ... get food
*/
    function getFood($foodId) {
        $sql = "SELECT foodId, food, doneness, externalTemp, externalHighTemp, externalLowTemp,
            internalTemp, internalHighTemp, internalLowTemp, comments
            FROM foods WHERE foodId=$foodId";
        $row = getRow($sql);
        return ($row);
    }
/*
   ... get pits
*/
    function getPits() {
            $sql = "SELECT pitId, manufacturer, model,
                blowerP, blowerI, blowerD, ventP, ventI, ventD, comments
                FROM pits";
        $rows = getRows($sql);
        return ($rows);
    }
/*
    ... get pit
*/
    function getPit($pitId) {
        $sql = "SELECT manufacturer, model, blowerP, blowerI, blowerD,
            ventP, ventI, ventD, comments FROM pits 
            WHERE pitId = $pitId";
        $row = getRow($sql);
        return ($row);
    }
/*
    ... get probes
*/
    function getProbes() {
        $sql = "SELECT probeId, manufacturer, model, a, b, c,
            lowTemp, lowResistance, mediumTemp, mediumResistance, highTemp, highResistance
            FROM probes";
        $rows = getRows($sql);
        return ($rows);
    }
/*
    ... get probe
*/
    function getProbe($probeId) {
        $sql = "SELECT probeId, manufacturer, model, a, b, c,
            lowTemp, lowResistance, mediumTemp, mediumResistance, highTemp, highResistance
            FROM probes WHERE probeId=$probeId";
        $row = getRow($sql);
        return ($row);
    }
/*
    ... delete probe
*/
    function deleteProbe($probeId) {
        $sql= "DELETE FROM probes WHERE probeId = $probeId";
        deleteRow($sql);
    }
/*
    ... get system settings
*/
    function getSystem() {
        $sql = "SELECT sampleInterval, timeZone, tempScale, mode FROM system where systemId=1";
        $row = getRow($sql);
        return ($row);        
    }    
/*
    ... get mode
*/
    function getMode() {
        $sql = "SELECT mode FROM system WHERE systemId=1";
        $row = getRow($sql);
        $mode = $row[mode];
        return ($mode);
    }
/*
    ... set manual mode
*/
    function setManualMode() {
        $mode = "Manual";
        $sql = "UPDATE system SET mode='$mode' WHERE systemId=1";
        updateRow($sql);
        $sql = "UPDATE currentburn SET mode='$mode' WHERE currentBurnId=1";
        updateRow($sql);
        return;
    }
/*
    ... set auto mode
*/
    function setAutoMode() {
        $mode = "Auto";
        $sql = "UPDATE system SET mode='$mode' WHERE systemId=1";
        updateRow($sql);
        $sql = "UPDATE currentburn SET mode='$mode' WHERE currentBurnId=1";
        updateRow($sql);
        return;
    }
/*
    ... get rows
*/
    function getRows($sql) {
        $rows = array();
        $conn = connectToDB();
        $result = mysqli_query($conn, $sql);        
        if (mysqli_num_rows($result) > 0) {
            while($row = mysqli_fetch_assoc($result)) {
                array_push($rows, $row);
            }
        }
        mysqli_close($conn);
        return ($rows);
    }
/*
    ... get row
*/
    function getRow($sql) {
        $conn = connectToDB();
        $result = mysqli_query($conn, $sql);        
        $row = mysqli_fetch_assoc($result);
        mysqli_close($conn);
        return ($row);
    }
/*
    ... add row
*/
    function addRow($sql) {
        $conn = connectToDB();
        mysqli_query($conn, $sql);
        mysqli_close($conn);
        return ($rows);
    }
/*
    ... update row
*/
    function updateRow($sql) {
        $conn = connectToDB();
        mysqli_query($conn, $sql);
        mysqli_close($conn);
        return ($rows);
    }
/*
    ... delete row
*/
    function deleteRow($sql) {
        $conn = connectToDB();
        mysqli_query($conn, $sql);
        mysqli_close($conn);
        return;
    }
?>