<?php
include('config.php');
if($_SERVER["REQUEST_METHOD"] == "POST")
{
    $eval_ID = $_POST["eval_id"];
    $user_email = $_POST["email"];
    $eval_stat = $_POST["eval_stat"];

    if(isset($_POST['update_eval_btn'])){   

        $sql_evaluation = mysqli_query($db, "SELECT * FROM evaluations WHERE ID='$eval_ID'");
        while($DB_ROW = mysqli_fetch_array($sql_evaluation)) {
            $turn_in = $DB_ROW['Turned_in'];
            $total = $turn_in + 1;
        }

        $sql2 = "UPDATE submitted_evaluation SET `Eval_Stat`='1' WHERE `Eval_ID`='$eval_ID'";
            if (mysqli_query($db, $sql2)){
                $sql3 = "UPDATE evaluations SET `Turned_in`='$total' WHERE `ID`='$eval_ID'";
                if (mysqli_query($db, $sql3)){
                    echo '<script>alert("Submitted successfully!");</script>';
                    echo '<script>document.location = "view_evaluation.php?ID='.$eval_ID.'"</script>';
                }
            }
        
    }
    else{
        $sql_evaluation = mysqli_query($db, "SELECT * FROM evaluations WHERE ID='$eval_ID'");
        while($DB_ROW = mysqli_fetch_array($sql_evaluation)) {
            $turn_in = $DB_ROW['Turned_in'];
            $total = $turn_in + 1;
        }

        // Get the current time adn date
        date_default_timezone_set('Asia/Manila');
        $date = date("m-d-Y");
        
        $sql = "INSERT INTO submitted_evaluation (`Eval_ID`, `Email`, `Eval_Stat`, `Date_Submitted`) VALUES ('$eval_ID', '$user_email', '$eval_stat' , '$date')";
        if (mysqli_query($db, $sql)){
            $sql1 = "UPDATE evaluations SET `Turned_in`='$total' WHERE `ID`='$eval_ID'";
            if (mysqli_query($db, $sql1)){
                echo '<script>alert("Submitted successfully!");</script>';
                echo '<script>document.location = "view_evaluation.php?ID='.$eval_ID.'"</script>';
            }
            else{
                echo mysqli_error($db);
            } 
        }
    }
}
?>