<?php
include $_SERVER['DOCUMENT_ROOT'] . "/WebBuilder/WebApp.class.php";
$WebApp->pageHeading('EDIT TEST');
$db = new DBMain();

$test_id = $_GET['record_id'];

$tests_res = $db->exec_query('tests', ['*'], '', '', '', '', "record_id = $test_id");
$test = $tests_res->fetch_assoc();

?>

<style>
    .sticky_button {
        position: fixed;
        top: 2.5%;
        right: 5%;
        z-index: 10;
        background-color: #aa9104;
        border: none;
        color: white;
        padding: 32px 64px;
        text-decoration: none;
        cursor: pointer;
        border-radius: 15px;
        font-size: 16px;
        transition: background-color 0.2s ease;

    }

    .sticky_2 {
        position: fixed;
        top: 2.5%;
        left: 5%;
        z-index: 10;
        background-color: #aa9104;
        border: none;
        color: white;
        padding: 32px 64px;
        text-decoration: none;
        cursor: pointer;
        border-radius: 15px;
        font-size: 16px;
        transition: background-color 0.2s ease;

    }
</style>

<form action='save_test.php' method='POST'>
    <div class='form_container' style='width:95%'>
        <input type='text' name='test_name' required class='input' style='width:100%;' placeholder="TEST NAME"
            value='<?php echo $test['test_name']; ?>' /><br>
        <input type='text' name='test_description' required class='input' style='width:100%;'
            placeholder="TEST DESCRIPTION" value='<?php echo $test['test_description']; ?>' /><br>
        <div style='display:flex;'>
            <input type='text' name='nqf_level' required class='input' style='width:48%;' placeholder="NQF LEVEL"
                value='<?php echo $test['nqf_level']; ?>' />
            <input type='text' name='credits' required class='input' style='width:48%;' placeholder="Credits"
                value='<?php echo $test['credits']; ?>' /><br>
            <select name='passmark' required class='input' style='width:48%;'>
                <option value='1'>100%</option>
                <option value='0.95'>95%</option>
                <option value='0.9'>90%</option>
                <option value='0.85'>85%</option>
                <option value='0.8'>80%</option>
                <option value='0.75'>75%</option>
            </select><br>
            <script>
                document.getElementById('passmark').value = '<?php echo $test['passmark']; ?>';
            </script>
        </div>

        <?php
        // get all sections of the test
        $sections_res = $db->exec_query('test_sections', ['*'], '', '', '', '', "test_id = $test_id", "ORDER BY record_id ASC");

        ?>
        <input type='text' id='sections_total' hidden name='sections_total' class='input'
            value='<?php echo $sections_res->num_rows + 1; ?>' />
        <input type='text' id='test_id' name='test_id' class='input' value='<?php echo $test_id; ?>' />
        <input type='submit' id='save' name='save' value='SAVE' class='sticky_2' />
        <hr>
    </div>
    <br>
    <?php $WebApp->pageHeading('TEST QUESTIONS'); ?>
    <br>
    <div onclick="add_section()" class='sticky_button'>ADD SECTION</div>

    <?php
    $index = 0;

    while ($section = $sections_res->fetch_assoc()) {
        $question_res = $db->exec_query('test_questions', ['*'], '', '', '', '', "test_section_id = {$section['record_id']}", "ORDER BY record_id ASC");

        $answer_res = $db->exec_query('test_answers', ['*'], '', '', '', '', "test_question_id = {$section['record_id']}", "ORDER BY record_id ASC");
        ?>
        <div class="form_container" id="form_container_<?php echo $index; ?>" style="width: 99%; margin-bottom: 5vw;">
            <input type="number" id="row_count_<?php echo $index; ?>" hidden name="row_count_<?php echo $index; ?>"
                value='<?php echo $question_res->num_rows; ?>'>
            <input type="text" name="section_<?php echo $index; ?>_name" required="" class="input"
                placeholder="SECTION NAME" value='<?php echo $section['section_name']; ?>' style="width: 60%;">
            <input type="text" name="section_<?php echo $index; ?>_id" required="" class="input"
                value='<?php echo $section['record_id']; ?>' style="width: 60%;">
            <table id="table_<?php echo $index; ?>" style="width: 100%; text-align: center;">
                <tr>
                    <td style="width: 5%;"></td>
                    <td style="width: 90%;">QUESTION</td>
                </tr>
                <?php
                $q_index = 0;
                while ($question = $question_res->fetch_assoc()) { ?>
                    <tr>
                        <td style="width: 5%;">
                            <div onclick='remove_(<?php echo $q_index; ?>,<?php echo $index; ?>)' class='button'
                                id='<?php echo $index; ?>_hide_<?php echo $q_index; ?>' style='background-color:red;'>X</div>
                        </td>
                        <td style="width: 90%;">
                            <textarea name="<?php echo $index; ?>_question_<?php echo $q_index; ?>"
                                id="<?php echo $index; ?>_question_<?php echo $q_index; ?>" class="input"
                                style="width: 90%; margin-left: 2vw;"><?php echo $question['question']; ?>
                                            </textarea>
                        </td>
                    </tr>
                    <?php
                    $q_index++;
                } ?>
                <tr>
                    <td style="width: 5%;"></td>
                    <td style="width: 90%;">ANSWER</td>
                </tr>
                <?php $a_index = 0;
                while ($answer = $answer_res->fetch_assoc()) { ?>
                    <tr>
                        <td style="width: 5%;">
                            <div onclick='remove_(<?php echo $a_index; ?>,<?php echo $index; ?>)' class='button'
                                id='<?php echo $index; ?>_hide_<?php echo $a_index; ?>' style='background-color:red;'>X</div>
                        </td>
                        <td style="width: 90%;">
                            <textarea name="<?php echo $index; ?>_answer_<?php echo $a_index; ?>"
                                id="<?php echo $index; ?>_answer_<?php echo $a_index; ?>" class="input"
                                style="width: 90%; margin-left: 2vw;"><?php echo $answer['answer']; ?>
                                            </textarea>
                        </td>
                        <td style="width: 5%;">
                            <div onclick='change_(<?php echo $a_index; ?>,<?php echo $index; ?>)' class='button'
                                id='<?php echo $index; ?>_change_<?php echo $a_index; ?>' <?php if ($answer['option'] == 1) {
                                          echo 'style="background-color:green; width: 40%; margin-right: 2vw;"';
                                      } else {
                                          echo 'style="background-color:red; width: 40%; margin-right: 2vw;"';
                                      } ?>>X</div>
                        </td>
                        <td style="width: 5%;">
                            <div class='button' id='<?php echo $index; ?>_hide_<?php echo $a_index; ?>' hidden>X</div>
                        </td>
                    </tr>
                    <?php
                    $a_index++;
                } ?>
            </table>
            <hr>
        </div>

        <?php $index++;
    } ?>

    <div id='added_content'></div>
    <div onclick="add_section()" class='sticky_button'>ADD SECTION</div>

    <script>
        var section_number = document.getElementById('sections_total').value;
        var table_no = document.getElementById('sections_total').value;
        // var form = document.getElementsByTagName('form')[0];

        var newDiv = document.createElement("div");
        newDiv.className = "form_container";
        newDiv.id = "form_container_" + section_number;
        newDiv.style.width = '95%';
        newDiv.style.marginBottom = '5vw';

        function add_section() {
            var form = document.getElementsByTagName('form')[0];
            let sectionCounter = 0;
            var section_number = document.getElementById('sections_total').value;

            var newDiv = document.createElement("div");
            newDiv.className = "form_container";
            newDiv.id = "form_container_" + section_number;
            newDiv.style.width = '95%';
            newDiv.style.marginBottom = '5vw';

            // Create row count input
            const rowCountInput = document.createElement('input');
            rowCountInput.type = 'number';
            rowCountInput.id = `row_count_${section_number}`;
            rowCountInput.name = `row_count_${section_number}`;
            rowCountInput.value = '2';
            newDiv.appendChild(rowCountInput);

            // Create section name input
            const sectionNameInput = document.createElement('input');
            sectionNameInput.type = 'text';
            sectionNameInput.name = `section_${section_number}_name`;
            sectionNameInput.required = true;
            sectionNameInput.className = 'input';
            sectionNameInput.style.width = '60%';
            sectionNameInput.placeholder = 'SECTION NAME';
            newDiv.appendChild(sectionNameInput);

            //create a table
            var table = document.createElement('table');
            table.id = `table_${section_number}`;
            table.style.width = '100%';
            table.style.textAlign = 'center';

            // Create rows
            function createRow(label, inputName, removable = "0") {
                const row1 = document.createElement('tr');
                const labelCell = document.createElement('td');
                labelCell.style.width = '5%';
                const contentCell = document.createElement('td');
                contentCell.style.width = '90%';

                if (label) {
                    contentCell.textContent = label;
                } else {
                    const textarea = document.createElement('textarea');
                    textarea.name = `${section_number}_${inputName}`;
                    textarea.className = 'input';
                    textarea.style.width = '90%';
                    textarea.style.marginLeft = '2vw';
                    contentCell.appendChild(textarea);
                    // Add a button to remove the row
                }
                if (removable == "1") {
                    const removeButton = document.createElement('div');
                    removeButton.textContent = 'X';
                    removeButton.className = 'button';
                    removeButton.style.width = '5%';
                    removeButton.style.backgroundColor = 'red';
                    removeButton.style.marginRight = '2vw';
                    removeButton.onclick = () => {
                        table.deleteRow(row1.rowIndex);
                        rowCountInput.value = parseInt(rowCountInput.value) - 1;
                    };
                    contentCell.appendChild(removeButton);
                }

                row1.appendChild(labelCell);
                row1.appendChild(contentCell);
                return row1;
            }

            // Add rows to table
            table.appendChild(createRow('QUESTION', null, "0"));
            table.appendChild(createRow(null, 'question_0', "0"));
            table.appendChild(createRow('ANSWER', null, "0"));
            table.appendChild(createRow(null, 'answer_0', "0"));

            // Create buttons
            function createButton(text, onClick, width = "25%") {
                const button = document.createElement('div');
                button.textContent = text;
                button.id = 'button_' + section_number;
                button.className = 'button';
                button.style.width = width;
                button.style.marginLeft = "auto";
                button.style.marginRight = "auto";
                button.onclick = onClick;
                return button;
            }

            // Add all elements to the div
            newDiv.appendChild(table);
            newDiv.appendChild(createButton('ADD ANSWER', () => add_multi_answer(section_number)));
            // newDiv.appendChild(document.createElement('hr'));
            // newDiv.appendChild(createButton('ADD QUESTION', () => add_question(section_number)));
            newDiv.appendChild(document.createElement('hr'));
            newDiv.appendChild(createButton('DELETE SECTION', () => delete_section(section_number)));

            form.appendChild(newDiv);

            document.getElementById('sections_total').value = document.getElementById('sections_total').value * 1 + 1 * 1;
        }

        //answer buttons
        function add_multi_answer(table_id) {
            var table = document.getElementById("table_" + table_id);
            if (!table) {
                console.error(`Table with id table_${table_id} does not exist.`);
                return;
            }
            var row_count_element = document.getElementById('row_count_' + table_id);
            var row_count = parseInt(row_count_element.value);
            var row = table.insertRow(-1); // Insert a new row at the end of the table
            row_count++; // Increment row count for each new row

            // Insert new cells (<td> elements) at the 1st and 2nd position of the "new" <tr> element:
            var cell1 = row.insertCell(0);
            var cell2 = row.insertCell(1);
            var cell3 = row.insertCell(2);
            var cell4 = row.insertCell(3);

            // Add some text to the new cells:
            cell1.innerHTML = "<div onclick='multi_remove_(" + row_count + "," + table_id + ")' class='button' id='" + table_id + "_hide_" + row_count + "' style='background-color:red;width:40%;'>X</div>";
            cell2.innerHTML = " <textarea type='text' id='" + table_id + "_answer_" + row_count + "' name='" + table_id + "_answer_" + row_count + "' class='input' style='width:90%;margin-left: 2vw;'></textarea>";
            cell3.innerHTML = "<div onclick='change_(" + row_count + "," + table_id + ")' class='button' id='" + table_id + "_change_" + row_count + "' style='background-color:red;width:40%;margin-right:2vw;'>X</div>";
            cell4.innerHTML = "<input type='text' id='" + table_id + "_change_value_" + row_count + "' name='" + table_id + "_change_value_" + row_count + "' value='0' class='button' hidden>";

            row_count_element.value = row_count;
        }

        function add_single_question(section_number, table_id) {
            //create a new table with 4 rows in the same div
            var table = document.getElementById(section_number + "table_" + table_id);
            var section_number = document.getElementById('sections_total').value;

            // Create row count input
            const rowCountInput = document.createElement('input');
            rowCountInput.type = 'number';
            rowCountInput.id = `row_count_${section_number}`;
            rowCountInput.name = `row_count_${section_number}`;
            rowCountInput.value = '2';
            newDiv.appendChild(rowCountInput);

            // Create section name input
            const sectionNameInput = document.createElement('input');
            sectionNameInput.type = 'text';
            sectionNameInput.name = `section_${section_number}_name`;
            sectionNameInput.required = true;
            sectionNameInput.className = 'input';
            sectionNameInput.style.width = '60%';
            sectionNameInput.placeholder = 'SECTION NAME';
            newDiv.appendChild(sectionNameInput);

            var table = document.createElement('table');
            table.id = 'table_' + section_number;
            table.style.width = '100%';
            table.style.textAlign = 'center';

            // Create rows
            function createRow(label, inputName) {
                const row1 = document.createElement('tr');
                const labelCell = document.createElement('td');
                labelCell.style.width = '5%';
                const contentCell = document.createElement('td');
                contentCell.style.width = '90%';

                if (label) {
                    contentCell.textContent = label;
                } else {
                    const textarea = document.createElement('textarea');
                    textarea.name = `${section_number}_${inputName}`;
                    textarea.className = 'input';
                    textarea.style.width = '90%';
                    textarea.style.marginLeft = '2vw';
                    contentCell.appendChild(textarea);
                }

                row1.appendChild(labelCell);
                row1.appendChild(contentCell);
                return row1;
            }

            // Add rows to table.
            table.appendChild(createRow('QUESTION', null));
            table.appendChild(createRow(null, 'question_0'));
            table.appendChild(createRow('ANSWER', null));
            table.appendChild(createRow(null, 'answer_0'));

            // Create buttons
            function createButton(text, onClick, width = "25%") {
                const button = document.createElement('div');
                button.textContent = text;
                button.className = 'button';
                button.style.width = width;
                button.style.marginLeft = "auto";
                button.style.marginRight = "auto";
                button.onclick = onClick;
                return button;
            }

            // Add all elements to the div
            newDiv.appendChild(table);
            newDiv.appendChild(document.createElement('hr'));
            newDiv.appendChild(createButton('ADD ANSWER', () => add_multi_answer(table_id)));
            newDiv.appendChild(document.createElement('hr'));
            newDiv.appendChild(createButton('ADD QUESTION', () => add_question(section_number)));
            newDiv.appendChild(document.createElement('hr'));
            newDiv.appendChild(createButton('DELETE QUESTION', () => delete_question(table_id)));

            form.appendChild(newDiv);

            document.getElementById('sections_total').value = document.getElementById('sections_total').value * 1 + 1 * 1;
        }

        function add_question(table_id) {
            //create a new table with 4 rows in the same div
            var table = document.getElementById("table_" + table_id);
            var section_number = document.getElementById('sections_total').value;

            // Create row count input
            const rowCountInput = document.createElement('input');
            rowCountInput.type = 'number';
            rowCountInput.id = `row_count_${section_number}`;
            rowCountInput.name = `row_count_${section_number}`;
            rowCountInput.value = '2';
            newDiv.appendChild(rowCountInput);

            // Create section name input
            const sectionNameInput = document.createElement('input');
            sectionNameInput.type = 'text';
            sectionNameInput.name = `section_${section_number}_name`;
            sectionNameInput.required = true;
            sectionNameInput.className = 'input';
            sectionNameInput.style.width = '60%';
            sectionNameInput.placeholder = 'SECTION NAME';
            newDiv.appendChild(sectionNameInput);

            var table = document.createElement('table');
            table.id = `table_${section_number}`;
            table.style.width = '100%';
            table.style.textAlign = 'center';

            // Create rows
            function createRow(label, inputName) {
                const row1 = document.createElement('tr');
                const labelCell = document.createElement('td');
                labelCell.style.width = '5%';
                const contentCell = document.createElement('td');
                contentCell.style.width = '90%';

                if (label) {
                    contentCell.textContent = label;
                } else {
                    const textarea = document.createElement('textarea');
                    textarea.name = `${section_number}_${inputName}`;
                    textarea.className = 'input';
                    textarea.style.width = '90%';
                    textarea.style.marginLeft = '2vw';
                    contentCell.appendChild(textarea);
                }

                row1.appendChild(labelCell);
                row1.appendChild(contentCell);
                return row1;
            }

            // Add rows to table.
            table.appendChild(createRow('QUESTION', null));
            table.appendChild(createRow(null, 'question_0'));
            table.appendChild(createRow('ANSWER', null));
            table.appendChild(createRow(null, 'answer_0'));

            // Create buttons
            function createButton(text, onClick, width = "25%") {
                const button = document.createElement('div');
                button.textContent = text;
                button.id = 'button_' + section_number;
                button.className = 'button';
                button.style.width = width;
                button.style.marginLeft = "auto";
                button.style.marginRight = "auto";
                button.onclick = onClick;
                return button;
            }
            form = document.getElementsByTagName('form')[0];
            // Add all elements to the div
            newDiv.appendChild(table);
            newDiv.appendChild(document.createElement('hr'));
            newDiv.appendChild(createButton('ADD ANSWER', () => add_multi_answer(table_id)));
            newDiv.appendChild(document.createElement('hr'));
            newDiv.appendChild(createButton('ADD QUESTION', () => add_question(section_number)));
            newDiv.appendChild(document.createElement('hr'));
            newDiv.appendChild(createButton('DELETE SECTION', () => delete_section(table_id)));

            form.appendChild(newDiv);

            document.getElementById('sections_total').value = document.getElementById('sections_total').value * 1 + 1 * 1;

        }

        function delete_question(table_id) {
            const table = document.getElementById("table_" + table_id);
            const rowCountElement = document.getElementById('row_count_' + table_id);

            if (table && table.rows.length > 1) {
                table.deleteRow(table.rows.length - 1);

                if (rowCountElement) {
                    rowCountElement.value = parseInt(rowCountElement.value) - 1;
                }
            } else {
                console.error(`Cannot delete the last question in table ${table_id}`);
            }
        }

        function change_(row_count, table_id) {
            var element = document.getElementById(table_id + "_change_" + row_count);
            var element2 = document.getElementById(table_id + '_change_value_' + row_count);
            // console.log(table_id + '_change_value_' + row_count);
            if (element) {
                if (element.style.backgroundColor === 'red') {
                    element.style.backgroundColor = 'green';
                    element.innerHTML = 'Y';
                    element2.setAttribute("value", "1");
                } else {
                    element.style.backgroundColor = 'red';
                    element.innerHTML = 'X';
                    element2.setAttribute("value", "0");
                }
            } else {
                console.error(`Element with id ${element} does not exist.`);
            }
        }

        //Remove buttons
        function multi_remove_(ind, table_id) {
            document.getElementById(table_id + "_hide_" + ind).hidden = true;
            document.getElementById(table_id + "_change_" + ind).hidden = true;
            document.getElementById(table_id + "_answer_" + ind).hidden = true;
            document.getElementById(table_id + "_answer_" + ind).value = "";
            document.getElementById('row_count_' + table_id).value = (document.getElementById('row_count_' + table_id).value * 1) - 1 * 1;
        }

        function remove_(ind, table_id) {
            document.getElementById(table_id + "_hide_" + ind).hidden = true;
            document.getElementById(table_id + "_answer_" + ind).hidden = true;
            document.getElementById(table_id + "_answer_" + ind).value = "";
            document.getElementById('row_count_' + table_id).value = (document.getElementById('row_count_' + table_id).value * 1) - 1 * 1;
        }

        function delete_section(section_number) {
            var form = document.getElementsByTagName('form')[0];
            var form_id = document.getElementById('form_container_' + section_number);

            //If either form_id or form_id2 exists, remove them
            if (form_id) {
                form.removeChild(form_id);

            } else {
                console.error(`Element with id form_container_${section_number} does not exist.`);
            }
        }

    </script>