<?php
include "../../classes/qr.class.php";
include "../../classes/app.class.php";

$app = new app();
$qr = new qrcode();
$db = new DBMain();
?>

<div class='container flex_container'>
    <h1>BOOK TOOL</h1>

    <input type='text' id='text_qr' hidden style="display: none;">
    <div style='display: flex;'>
        <div class="container flex_container_content" style="border: 1px solid black;padding: 2%; border-radius: 5px; width:50%;display:flex; justify-content:center;">
            <div class='flex_container'>
                <label>SELECT ARTISAN</label>
                <select id="art">
                    <?php echo $db->get_artisans_in_dropdown(); ?>
                </select>
                <!-- <label>TOOL_ID</label> -->
                <input type="text" style='display:none;' name="tool_id" id="tool_id">
            </div>
        </div>
        <div style='width:100%;display:flex;flex-direction: row;flex-wrap: nowrap;align-content: center;justify-content: center;align-items: center;'>
                <?php echo $qr->scanner("text_qr", "find_tool_id()", "SCAN TOOL"); ?>
            </div>
    </div>

    <button onclick="book_tools()" hidden disabled id='check_tool_btn'>BOOK</button>
</div>
<script>

    function find_tool_id() {
        text_qr = document.getElementById('text_qr').value;
        var xhttp = new XMLHttpRequest();
        xhttp.onload = function() {
            console.log(this.responseText);
            if (this.responseText == 0) {
                console.log("FAILED");
            } else {
                array_text = this.responseText;
                document.getElementById('tool_id').value = array_text;
                if (array_text <= 0) {
                    document.getElementById('tool_id').style.backgroundColor = "RED";
                }
                document.getElementById('check_tool_btn').hidden = false;
                document.getElementById('check_tool_btn').disabled = false;
            }
        }
        xhttp.open("GET", '../../ajax/tools/get_tool_id.php?qr_code=' + text_qr);
        xhttp.send();
    }

    function book_tools() {
        qr_code = document.getElementById('text_qr').value;
        artisan_id = document.getElementById('art').value;

        var xhttp = new XMLHttpRequest();
        xhttp.onload = function() {
            console.log(this.responseText);
            if (this.responseText == 0) {
                console.log("FAILED");

            } else if (this.responseText == 1) {
                console.log("PASSED");
                window.location.href = 'search_client.php';
            }
        }
        xhttp.open("GET", '../../ajax/tools/book_tools.php?qr_code=' + qr_code + '&artisan_id=' + artisan_id);
        xhttp.send();
    }
</script>