<?php
include "classes/html.class.php";
$html = new html("farms");
$db = new db();
$user_res = $db->exec_query('farms', ["*"]);
$users_list = '<option></option>';
while ($users = $user_res->fetch_assoc()) {
    $users_list = $users_list . "<option value='{$users['record_id']}'>{$users['farm_name']}</option>";
}


?>


<div class='form'>
    <h2 style="font-size:2vw">SELECT FARM:</h2><br>
    <select onchange="call_ajax_func()" id='farm_id' class='form_input'>
        <?php echo $users_list; ?>
    </select>
    <hr>
    <h2 style="font-size:2vw">EDIT FARM:</h2>
    <hr><br>
    <input type='text' placeholder="FARM NAME" id='farm_name' class='form_input' /><br><br>
    <br><br>
    <input type='submit' value='SAVE' class='form_btn' onclick='ajax_func()' />

</div>

<script>
    function ajax_func() {
        // alert("Test");
        farm_name = document.getElementById('farm_name').value;
        farm_id = document.getElementById('farm_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 {
                // window.location.href = "users.php";
                alert("SAVED");

            }
        }

        xhttp.open("GET", "ajax/edit_farm.ajax.php?farm_id=" + farm_id + "&farm_name=" + farm_name);
        xhttp.send();

    }

    function call_ajax_func() {
        // alert("Test");
        farm_id = document.getElementById('farm_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);
                values = this.responseText;
                document.getElementById('farm_name').value = values;
                



            } else {
                // window.location.href = "users.php";
                alert("Something Went Wrong");

            }
        }

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

    }
</script>


</body>

</html>