<?php
include "../../root.class.php";
$db = new db_safeguard();

$date = date("Y-m-d H:i", strtotime("+2 Hours"));

echo "<br>name: " . $_POST['name'];
echo "<br>info: " . $_POST['test_description'];
echo "<br>ngl: " . $_POST['passmark'];
echo "<br>Sections total: " . $_POST['question_total'];


var_dump($_POST);

$record = $db->query("tests","INSERT INTO `tests` (`name`,`test_description`,`passmark`,`date_created`) VALUES ('{$_POST['name']}','{$_POST['test_description']}','{$_POST['passmark']}','{$date}')");
$index = 0;

$test_id_res = $db->query('tests',"SELECT * FROM tests WHERE name = '{$_POST['name']}'");
$test_id = $test_id_res->fetch_assoc();

while ($index <= $_POST['question_total']) {
    echo "<br> I: " . $index;
    echo "<br>question_name: " . $_POST["question_" .$index . "_name"];
    if (strlen($_POST["question_" . $index . "_name"]) != 0) {
        $question_id = $db->query("test_questions","INSERT INTO `test_questions` (`test_id`,`question_name`) VALUES ({$test_id['record_id']},'{$_POST["question_" .$index . "_name"]}')");
        echo "INSERT INTO `test_questions` (`test_id`,`question_name`) VALUES ({$test_id['record_id']},'{$_POST["question_" .$index . "_name"]}')";
        echo "<br>test_question_id: " . $question_id;
        echo "<br>rows: " . $_POST['row_count_' . $index];
        $a_index = 0;
        while ($a_index <= $_POST['row_count_' . $index]) {
            echo "<br> QI " . $a_index;
            if (strlen($_POST[$index . "_answer_$a_index"]) != 0) {
                echo "<br><br>answer: " . $_POST[$index . "_answer_$a_index"];

                $db->query("test_answers","INSERT INTO `test_answers` (`test_question_id`,`answer`,`options`) VALUES ($question_id,'{$_POST[$index . "_answer_$a_index"]}','{$_POST[$index . "_answer_option_$a_index"]}')");
                echo "<br>options: " . $_POST[$index . "_answer_option_$a_index"];

                echo "<br><br> " . "INSERT INTO `test_answers` (`test_question_id`,`answer`,`option`) VALUES ($question_id,'{$_POST[$index . "_answer_$a_index"]}','{$_POST[$index . "_answer_option_$a_index"]}')";
            }
            $a_index++;
        }
    }
    $index++;
}

echo "<script> window.location.href = '../training/tests.php';</script>";
