<?php
include "classes/html.class.php";
$html = new html("service types");
$db = new db();


$res = $db->exec_query('service_types', ['*']);
$list = '<option></option>';
while ($row = $res->fetch_assoc()) {
    $list = $list . "<option value='{$row['record_id']}'>{$row['name']}</option>";
}
?>
<div class='form'>
    <h2 style="font-size:2vw">SELECT SERVICE TYPE:</h2>
    <select class='form_input' id='service_type_id' onchange="get_info()">
        <? echo $list; ?>
    </select>
    <h2 style="font-size:2vw">EDIT SERVICE TYPE:</h2>
    <hr><br>
    <input type='text' placeholder="SERVICE TYPE NAME" id='name' name='name' class='form_input' /><br><br>
    <label style="font-size:1.5vw">ODO TYPE: </label><br>
    <select id='odo_type' class='form_input'>
        <option></option>
        <option>KM</option>
        <option>Hours</option>
        <option>Days</option>
    </select><br><br>
    <input type='text' placeholder="SERVICE INTERVAL" id='interval' class='form_input' /><br><br>


    <input type='submit' value='ADD' class='form_btn' onclick='ajax_func()' />

</div>

<script>
    function get_info() {
        service_type_id = document.getElementById('service_type_id').value;

        // Create an XMLHttpRequest object
        const xhttp = new XMLHttpRequest();
        // Define a callback function
        xhttp.onload = function() {
            // Here you can use the Data
            if (this.responseText == 1) {

                alert(this.responseText);

            } else {

                array_1 = this.responseText.split(',');
                document.getElementById('name').value = array_1[0];
                document.getElementById('odo_type').value = array_1[1];
                document.getElementById('interval').value = array_1[2];
            }

        }

        xhttp.open("GET", "ajax/get_service_type.ajax.php?service_type_id=" + service_type_id);
        xhttp.send();

    }

    function ajax_func() {
        // alert("Test");
        service_type_id = document.getElementById('service_type_id').value;
        name = document.getElementById('name').value;
        odo_type = document.getElementById('odo_type').value;
        interval = document.getElementById('interval').value;

        // Create an XMLHttpRequest object
        const xhttp = new XMLHttpRequest();
        // Define a callback function
        xhttp.onload = function() {
            // Here you can use the Data
            if (this.responseText != 1) {

                alert(this.responseText);

            } else {
                alert("SAVED");
            }
        }

        xhttp.open("GET", "ajax/edit_service_type.ajax.php?name=" + name + "&odo_type=" + odo_type + "&interval=" + interval + "&service_type_id=" + service_type_id);
        xhttp.send();

    }
</script>


</body>

</html>