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

    filename:     probecalibrateprocess.php
    description:  calibrate probe
    inputs:       probeId, low/high Temperatures/Resistances
    outputs:      error
    actions:      none
    redirections: probelist.php

********************************************************************************
*/
    include 'functions.php';
    $conn = connectToDB();

    $calibrate = $_POST["calibrate"];
    $cancel = $_POST["cancel"];

    if ($cancel) {
        header('Location: probelist.php');
        exit;
    } 
    $error = "";
    try {   
        $probeId = $_GET["probeId"];
        $t1F = (float) $_POST["lowTemp"];
        $r1 = (float) $_POST["lowResistance"];
        $t2F = (float) $_POST["mediumTemp"];
        $r2 = (float) $_POST["mediumResistance"];
        $t3F = (float) $_POST["highTemp"];
        $r3 = (float) $_POST["highResistance"];

        $t1 = tK($t1F);
        $t2 = tK($t2F);
        $t3 = tK($t3F);

        $l1 = log($r1);
        $l2 = log($r2);
        $l3 = log($r3);

        $y1 = 1 / $t1;
        $y2 = 1 / $t2;
        $y3 = 1 / $t3;

        $g2 = ($y2 - $y1) / ($l2 - $l1);
        $g3 = ($y3 - $y1) / ($l3  - $l1);

        $c = (($g3 - $g2) / ($l3 -$l2)) * (1 / ($l1 + $l2 + $l3));
        $b = $g2 - $c * ($l1 * $l1 + $l1 * $l2 + $l2 * $l2);
        $a = $y1 - ($b + $l1 * $l1 * $c) * $l1;

        $sql = "UPDATE probes SET a=$a, b=$b, c=$c, lowResistance=$r1, lowTemp=$t1F, mediumTemp=$t2F, mediumResistance=$r2, highTemp=$t3F, highResistance=$r3 WHERE probeId=$probeId";
        if (!mysqli_query($conn, $sql)) {
            error_log("Probe NOT calibrated: " . $sql . "<br>" . mysqli_error($conn));
            $error = "Probe NOT calibrated";
        }
    } catch(Exception $e) {
        error_log("Probe NOT calibrated" . $e->getMessage());
        $error = "Probe NOT calibrated";
    }


    mysqli_close($conn);           
    header('Location: probelist.php?error=' . $error);
?>