<?php

require_once('../../assets/constants/config.php');
session_start();
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname;charset=utf8mb4;collation=utf8_general_ci;prefix=''", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);


$stmt = $conn->prepare("SELECT * FROM tbl_school_info");
$stmt->execute();
$result = $stmt->fetchAll();

foreach($result as $row) {

$currency = $row[6];
date_default_timezone_set($row[5]);

}


$starting_mark = 1;
$mytotal_marks = 0;
$exam_id = $_SESSION['current_examid'];
$student = $_SESSION['id'];
$date_submit = date('Y-m-d G:i:s');
$student_answers = array();
$corrections = $_SESSION['exam_corrections'];

foreach ($_POST as $key => $value) {
array_push($student_answers,$value);
}

$stmt = $conn->prepare("SELECT * FROM tbl_asessment_records WHERE student = ? AND exam = ?");
$stmt->execute([$student, $exam_id]);
$result = $stmt->fetchAll();

foreach($result as $row) {
$marking_scheme = explode(",",$row[8]);
$total_questions = count($marking_scheme);
}

$total_score = 0;
foreach ($student_answers as $key => $student_answer) {
if (strtoupper($student_answer) == strtoupper($marking_scheme[$key])) {
$total_score++;
}
}

$percent_score = ($total_score / $total_questions) * 100;
$percent_score = floor($percent_score);

try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname;charset=utf8mb4;collation=utf8_general_ci;prefix=''", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);


$answers = implode(",",$student_answers);

$stmt = $conn->prepare("UPDATE tbl_asessment_records SET 	answers = :answ, submission = '1', score = :score, submission_time = :subtime WHERE exam = :exam AND student = :student");
$stmt->bindParam(':answ', $answers);
$stmt->bindParam(':score', $percent_score);
$stmt->bindParam(':subtime', $date_submit);
$stmt->bindParam(':exam', $exam_id);
$stmt->bindParam(':student', $student);

$stmt->execute();
if ($corrections == "1") {
header("location:../corrections?node=$exam_id");
}else{
header("location:../view-exam?node=$exam_id");
}


}catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}

}catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}

?>
