<?php
include $_SERVER['DOCUMENT_ROOT'] . "/WebApp/assesor/html.class.php";
$db = new DBMain();

// var_dump($_GET);
?>

<?php
$attempt = $_GET['attempt'];
$booking_id = $_GET['booking_id'];
$clients_id = $_GET['clients_id'];
$client_employees_id = $_GET['client_employees_id'];
$test_id = $_GET['test_id'];

$test_res = $db->exec_query('tests', ['*'], '', '', '', '', "record_id = $test_id");
$test_data = $test_res->fetch_assoc();

if ($attempt > 0) {
    $prev_ass_res = $db->exec_query('tests_sec', ['*'], '', '', '', '', "booking = $booking_id AND test_id = $test_id AND client_employees_id = $client_employees_id", "ORDER BY record_id DESC");
    $prev_ass = $prev_ass_res->fetch_assoc();
}
$date_now = date('Y-m-d H:i', strtotime("+ 2 Hours"));
$timeline_id = $db->insert("insert test_timeline (`datetime_start`,`datetime_stop`,`t_delta`) VALUES ('$date_now','none','0')");
?>

<form action='save_test.php' method="POST" enctype="multipart/form-data">
    <?php
    // get test secitons
    $question_index = 0;

    $test_questions_res = $db->exec_query('test_questions', ['*'], '', '', '', '', "test_id = {$test_data['record_id']}", "ORDER BY record_id ASC");

    while ($test_questions = $test_questions_res->fetch_assoc()) {
        if ($attempt > 0) {
            $old_ass_res = $db->exec_query('tests_questions_sec', ['*'], '', '', '', '', "tests_sec_id = {$prev_ass['record_id']} AND questions = '{$test_questions['section_name']}'", "ORDER BY record_id ASC");
            if ($old_ass_res->num_rows > 0) {
                $old_ass = $old_ass_res->fetch_assoc();
                // echo $old_ass['subtotal'];
                $subtotal = explode('-', $old_ass['subtotal']);
                $results_sub = $subtotal[1] / $subtotal[0];
                // echo $test_questions['question'];
            }
        }
        ?>
        <div class='form_container'
            style='width:90%; margin-bottom:5vw; <?php if ($attempt > 0) {
                if ($results_sub >= $test_data['passmark']) { ?>background-color:lightgreen;<?php } else { ?>background-color:RGB(255,200,200);<?php }
            } ?>'>
            <h1><?php echo $test_questions['section_name'] . " / " . $test_questions['record_id']; ?></h1>
            <input type="text" hidden name='<?php echo $question_index; ?>_section_name' 
                value='<?php echo $test_questions['section_name']; ?>' />
            <input type="text" name='clients_id' hidden value='<?php echo $clients_id; ?>' />
            <input type="text" id='client_employees_id' hidden name='client_employees_id' 
                value='<?php echo $client_employees_id; ?>' />
            <input type="text" name='booking_id' id='booking_id' hidden value='<?php echo $booking_id; ?>' />
            <input type="text" name='passmark' hidden id='passmark'  value='<?php echo $test_data['passmark']; ?>' />
            <input type="text" name='test_id' hidden value='<?php echo $test_id; ?>' />
            <input type="text" name='test_name' hidden value='<?php echo $test_data['test_name']; ?>' />
            <input type="text" name='test_info' hidden value='<?php echo $test_data['test_description']; ?>' />
            <input type="text" name='nqf_level' hidden value='<?php echo $test_data['nqf_level']; ?>' />
            <input type="text" name='credits' hidden value='<?php echo $test_data['credits']; ?>' />
            <table style='width:99%'>
                <tr>
                    <th style='width:70%'>
                        <h2> OPTIONS </h2>
                    </th>
                    <th colspan="2" style='width:20%'>
                        <h2> YES  /  NO</h2>
                    </th>
                    <th style='width:10%'>
                        <h2> COMMENT</h2>
                    </th>
                </tr>
                <br>
                <?php
                $answers_res = $db->exec_query('test_answers', ['*'], '', '', '', '', "test_question_id = {$test_questions['record_id']}", "ORDER BY record_id ASC");
                $answer_index = 0;
                while ($answers = $answers_res->fetch_assoc()) {
                    if ($attempt > 0) {
                        $answers_old_res = $db->exec_query('tests_answers_sec', ['*'], '', '', '', '', "tests_questions_sec_id = {$test_questions['record_id']} AND answer = '{$answers['answer']}'");
                        if ($answers_old_res->num_rows > 0) {
                            $old_answers = $answers_old_res->fetch_assoc();
                        }
                    }
                    ?>
                    <tr>
                        <td style='padding:50px'>
                            <label class='label'><b><?php echo $answers['answer']; ?></b></label>
                        </td>
                        <td>
                            <input type='text' name='<?php echo $question_index; ?>_option_<?php echo $answer_index; ?>'
                                hidden id='<?php echo $question_index; ?>_option_<?php echo $answer_index; ?>'
                                class='input' <?php if ($attempt > 0) { ?>value='<?php echo $old_answers['answer']; ?>' <?php } else { ?>value='0' <?php } ?> value='0' />
                            <input type='text' name='<?php echo $question_index; ?>_question_<?php echo $answer_index; ?>'
                                hidden id='<?php echo $question_index; ?>_question_<?php echo $answer_index; ?>' class='input'
                                value='<?php echo $answers['answer']; ?>' />
                            <!-- onclick make value of option 1 and grey out the no button -->
                            <div class='button' style='background-color:grey'
                                id='<?php echo $question_index; ?>_c_<?php echo $answer_index; ?>'
                                onclick="yes_<?php echo $question_index; ?>_<?php echo $answer_index; ?>(<?php echo $answer_index; ?>)">YES</div>
                        </td>
                        <td>
                            <div class='button' style='background-color:grey'
                                id='<?php echo $question_index; ?>_nyc_<?php echo $answer_index; ?>'
                                onclick="no_<?php echo $question_index; ?>_<?php echo $answer_index; ?>(<?php echo $answer_index; ?>)">NO</div>
                                <input type="text" hidden name="<?php echo $question_index; ?>_check_<?php echo $answer_index; ?>" id="<?php echo $question_index; ?>_check_<?php echo $answer_index; ?>"  value='<?php echo $answers['option']; ?>'>
                        </td>
                        <td style='padding:10px'>
                            <textarea id='<?php echo $answer_index; ?>_comment_<?php echo $answer_index; ?>'
                                name='<?php echo $answer_index; ?>_comment_<?php echo $answer_index; ?>'
                                class='input'><?php if ($attempt > 0) {
                                    echo $old_answers['comment'];
                                } ?></textarea>
                                
                        </td>
                    </tr>
                    <script>
                        
                        <?php 
                        if ($attempt > 0) {
                            if ($old_answers['option'] == 1) {
                                ?>yes_<?php echo $question_index; ?>_<?php echo $answer_index; ?>() <?php
                            } else {
                                ?>no_<?php echo $question_index; ?>_<?php echo $answer_index; ?>() <?php
                            }
                        } ?>

                        function yes_<?php echo $question_index; ?>_<?php echo $answer_index; ?>(answer_index) {
                            document.getElementById('<?php echo $question_index; ?>_option_<?php echo $answer_index; ?>').value = '1';
                            document.getElementById('<?php echo $question_index; ?>_nyc_<?php echo $answer_index; ?>').style.backgroundColor = 'grey';
                            document.getElementById('<?php echo $question_index; ?>_c_<?php echo $answer_index; ?>').style.backgroundColor = 'green';
                        }

                        function no_<?php echo $question_index; ?>_<?php echo $answer_index; ?>(answer_index) {
                            document.getElementById('<?php echo $question_index; ?>_option_<?php echo $answer_index; ?>').value = '0';
                            document.getElementById('<?php echo $question_index; ?>_c_<?php echo $answer_index; ?>').style.backgroundColor = 'grey';
                            document.getElementById('<?php echo $question_index; ?>_nyc_<?php echo $answer_index; ?>').style.backgroundColor = 'red';
                        }
                    </script>

                    <?php
                    $answer_index++;
                } ?>
                <input type='number' hidden id='<?php echo $question_index; ?>_question_count'
                    name='<?php echo $question_index; ?>_question_count' value='<?php echo $answer_index; ?>' />
            </table>

        </div>

        <?php
        $question_index++;
    }

    ?>

    <br>
    <div class='form_container' style='width:90%; margin-bottom:5vw;'>
        <?php $employee_res = $db->exec_query('client_employees', ['*'], '', '', '', '', "record_id = $client_employees_id");
        $employee_info = $employee_res->fetch_assoc();
        ?>
        <h1><b><?php echo $employee_info['client_employees_name']; ?>'S SIGNATURE</b></h1>
        <canvas id="signature_pad" class="signature-pad" width=500 height=300
            style='background-color:white;border-radius:20px;'></canvas><br>
        <button type="button" id="save_signature" class="button">SIGN</button>
        <button type="button" id="clear_signature" onclick="signaturePad.clear();" class="button">CLEAR</button>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/signature_pad@2.3.2/dist/signature_pad.min.js"></script>
    <script>
        var canvas = document.getElementById('signature_pad');
        var signaturePad = new SignaturePad(canvas);

        document.getElementById('save_signature').addEventListener('click', function () {
            if (signaturePad.isEmpty()) {
                alert("Please provide signature first.");
            } else {
                var dataURL = signaturePad.toDataURL('image/png');
                var blob = dataURLToBlob(dataURL);
                var formData = new FormData();
                formData.append('file', blob, 'signature.png');
                formData.append('employee_id', document.getElementById('client_employees_id').value);
                formData.append('booking_id', document.getElementById('booking_id').value);

                var xhr = new XMLHttpRequest();
                xhr.open("POST", "upload.php", true);
                xhr.onreadystatechange = function () {
                    if (xhr.readyState === 4 && xhr.status === 200) {
                        // alert(xhr.responseText); // Handle the server response
                        if (xhr.responseText.indexOf("OK") > 1) {
                            // alert("SUCCESSFULLY UPLOADED");\
                            document.getElementById('save_btn').hidden = false;
                            document.getElementById('save_signature').hidden = true;
                        } else {
                            alert(xhr.responseText);
                        }
                    }
                };
                xhr.send(formData);
            }
        });

        function dataURLToBlob(dataURL) {
            var binary = atob(dataURL.split(',')[1]);
            var array = [];
            for (var i = 0; i < binary.length; i++) {
                array.push(binary.charCodeAt(i));
            }
            return new Blob([new Uint8Array(array)], {
                type: dataURL.split(',')[0].split(':')[1].split(';')[0]
            });
        }
    </script>
    <!-- NOTES AREA -->
    <div class='form_container' style='width:90%; margin-bottom:5vw;'>
        <h2>ASSESOR NOTES</h2>
        <textarea id='notes' name='notes' class='input' required style="width: 100%;" placeholder='NOTES'></textarea>
    </div>
    <div class='form_container' style='width:90%; margin-bottom:5vw;'>
        <h2>SPECIAL INSTRUCITONS</h2>
        <textarea id='special_instructions' name='special_instructions' class='input' style="width: 100%;"
            placeholder='NOTES'></textarea>
    </div>
    <div class='form_container' style='width:90%; margin-bottom:5vw;'>
        <h2>VEHICLE MODEL</h2>
        <textarea id='vehicle_model' name='vehicle_model' class='input' required style="width: 100%;"></textarea>
    </div>

    <input type='number' hidden id='section_count' name='section_count' value='<?php echo $question_index; ?>' />
    <input type='number' hidden id='timeline_id' name='timeline_id' value='<?php echo $timeline_id; ?>' />

    <input type='submit' name='save' id='save_btn' class='button' value='COMPLETE' />

</form>