<?php
include $_SERVER['DOCUMENT_ROOT'] . "/WebApp/assesor/html.class.php";
$db = new DBMain();
?>

<?php
$attempt = $_GET['attempt'];
$booking_id = $_GET['booking_id'];
$client_id = $_GET['client_id'];
$client_employees_id = $_GET['client_employees_id'];
$assesments_id = $_GET['assesments_id'];

$assesment_res = $db->exec_query('assesments', ['*'], '', '', '', '', "record_id = $assesments_id");
$assesment = $assesment_res->fetch_assoc();
if ($attempt > 0) {
    $prev_ass_res = $db->exec_query('asseses', ['*'], '', '', '', '', "booking = $booking_id AND assesments_id = $assesments_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 asseses_timeline (`datetime_start`,`datetime_stop`,`t_delta`) VALUES ('$date_now','none','0')");
?>

<form action='save_assesment_v1.php' method="POST" enctype="multipart/form-data">
    <?php
    // get assesment secitons
    $section_index = 0;
    $sections_res = $db->exec_query('assesment_sections', ['*'], '', '', '', '', "assesment_id = {$assesment['record_id']}", "ORDER BY record_id ASC");
    while ($sections = $sections_res->fetch_assoc()) {
        if ($attempt > 0) {
            $old_ass_res = $db->exec_query('asseses_sections', ['*'], '', '', '', '', "asseses_id = {$prev_ass['record_id']} AND section_name = '{$sections['section_name']}'", "ORDER BY record_id ASC");
            if ($old_ass_res->num_rows > 0) {
                $old_ass = $old_ass_res->fetch_assoc();
                $subtotal = explode('-', $old_ass['subtotal']);
                echo $results_sub = $subtotal[1] / $subtotal[0];
            }
        }
    ?>

        <div class='form_container' style='width:90%; margin-bottom:5vw; <?php if ($attempt > 0) {
                                                                                if ($results_sub >= $assesment['passmark']) { ?>background-color:lightgreen;<?php } else { ?>background-color:RGB(255,200,200);<?php }
                                                                                                                                    } ?>'>
            <h1><?php echo $sections['section_name']. " / ".$sections['record_id']; ?></h1>
            <input type="text" name='<?php echo $section_index; ?>_section_name' hidden value='<?php echo $sections['section_name']; ?>' />
            <input type="text" name='client_id' hidden value='<?php echo $client_id; ?>' />
            <input type="text" id='client_employees_id' name='client_employees_id' hidden 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' id='passmark' hidden value='<?php echo $assesment['passmark']; ?>' />
            <input type="text" name='assesments_id' hidden value='<?php echo $assesments_id; ?>' />
            <input type="text" name='assesments_name' hidden value='<?php echo $assesment['assesments_name']; ?>' />
            <input type="text" name='assesments_info' hidden value='<?php echo $assesment['assesment_info']; ?>' />
            <input type="text" name='nqf_level' hidden value='<?php echo $assesment['nqf_level']; ?>' />
            <input type="text" name='credits' hidden value='<?php echo $assesment['credits']; ?>' />
            <table style='width:99%'>
                <tr>
                    <th style='width:70%'>
                        <h2> QUESTION </h2>
                    </th>
                    <th colspan="2" style='width:20%'>
                        <h2> COMPETENT</h2>
                    </th>
                    <th style='width:10%'>
                        <h2> COMMENT</h2>
                    </th>
                </tr>
                <br>
                <?php
                $questions_res = $db->exec_query('assesment_questions', ['*'], '', '', '', '', "assesment_section_id = {$sections['record_id']}", "ORDER BY record_id ASC");
                $question_index = 0;
                while ($questions = $questions_res->fetch_assoc()) {
                    if ($attempt > 0) {
                        $questions_old_res = $db->exec_query('asseses_section_questions', ['*'], '', '', '', '', "asseses_section_id = {$old_ass['record_id']} AND question = '{$questions['question']}'");
                        if ($questions_old_res->num_rows > 0) {
                            $old_question = $questions_old_res->fetch_assoc();
                        }
                    }
                ?>
                    <tr>
                        <td style='padding:50px'>
                            <label class='label'><b><?php echo $questions['question']; ?></b></label>
                        </td>
                        <td>
                            <input type='text' name='<?php echo $section_index; ?>_competent_<?php echo $question_index; ?>' hidden id='<?php echo $section_index; ?>_competent_<?php echo $question_index; ?>' class='input' <?php if ($attempt > 0) { ?>value='<?php echo $old_question['answer']; ?>' <?php } else { ?>value='0' <?php } ?> value='0' />
                            <input type='text' name='<?php echo $section_index; ?>_question_<?php echo $question_index; ?>' hidden id='<?php echo $section_index; ?>_question_<?php echo $question_index; ?>' class='input' value='<?php echo $questions['question']; ?>' />
                            <!-- onclick make value of competent 1 and grey out the no button -->
                            <div class='button' style='background-color:grey' id='<?php echo $section_index; ?>_c_<?php echo $question_index; ?>' onclick="yes_<?php echo $section_index; ?>_<?php echo $question_index; ?>()">YES</div>
                        </td>
                        <td>
                            <div class='button' style='background-color:grey' id='<?php echo $section_index; ?>_nyc_<?php echo $question_index; ?>' onclick="no_<?php echo $section_index; ?>_<?php echo $question_index; ?>()">NO</div>
                        </td>
                        <td style='padding:10px'>
                            <textarea id='<?php echo $question_index; ?>_comment_<?php echo $question_index; ?>' name='<?php echo $question_index; ?>_comment_<?php echo $question_index; ?>' class='input'><?php if ($attempt > 0) {
                                                                                                                                                                                                                echo $old_question['comment'];
                                                                                                                                                                                                            } ?></textarea>
                        </td>
                    </tr>
                    <script>
                        <?php if ($attempt > 0) {

                            if ($old_question['answer'] == 1) {
                        ?>yes_<?php echo $section_index; ?>_<?php echo $question_index; ?>() <?php
                                                                                            } else {
                                                                                                ?>no_<?php echo $section_index; ?>_<?php echo $question_index; ?>() <?php
                                                                                                                                                                }
                                                                                                                                                            } ?>

                        function yes_<?php echo $section_index; ?>_<?php echo $question_index; ?>() {
                            document.getElementById('<?php echo $section_index; ?>_competent_<?php echo $question_index; ?>').value = '1';
                            document.getElementById('<?php echo $section_index; ?>_nyc_<?php echo $question_index; ?>').style.backgroundColor = 'grey';
                            document.getElementById('<?php echo $section_index; ?>_c_<?php echo $question_index; ?>').style.backgroundColor = '#aa9104';
                        }

                        function no_<?php echo $section_index; ?>_<?php echo $question_index; ?>() {
                            document.getElementById('<?php echo $section_index; ?>_competent_<?php echo $question_index; ?>').value = '0';
                            document.getElementById('<?php echo $section_index; ?>_c_<?php echo $question_index; ?>').style.backgroundColor = 'grey';
                            document.getElementById('<?php echo $section_index; ?>_nyc_<?php echo $question_index; ?>').style.backgroundColor = '#aa9104';
                        }
                    </script>

                <?php
                    $question_index++;
                } ?>
                <input type='number' hidden id='<?php echo $section_index; ?>_question_count' name='<?php echo $section_index; ?>_question_count' value='<?php echo $question_index; ?>' />
            </table>

        </div>

    <?php
        $section_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;'>

        <label class='label'>PICTURE OF ATTENDANT:</label><br>
        <label for="fileToUpload">Select File</label><br>
        <input type="file" required name="fileToUpload" class='input' id="fileToUpload" />

    </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 $section_index; ?>' />
    <input type='number' hidden id='timeline_id' name='timeline_id' value='<?php echo $timeline_id; ?>' />

    <input type='submit' name='save' id='save_btn' hidden class='button' value='COMPLETE' />

</form>