<?php
include "classes/html.class.php";
$html = new html("farms");
$db = new db();
$user_res = $db->exec_query('farm_sections', ["*"]);
$users_list = '<option></option>';
while ($users = $user_res->fetch_assoc()) {
    $farm_res = $db->exec_query('farms', ["*"], '', '', '', '', "record_id = {$users['farm_id']}");
    $farm = $farm_res->fetch_assoc();
    $users_list = $users_list . "<option value='{$users['record_id']}'>{$farm['farm_name']} - > {$users['name']}</option>";
}


?>


<div class='form'>
    <h2 style="font-size:2vw">SELECT FARM SECTION:</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 SECTION 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_section_name = document.getElementById('farm_section_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_section.ajax.php?farm_id=" + farm_id + "&farm_section_name=" + farm_section_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_section.ajax.php?farm_id=" + farm_id);
        xhttp.send();

    }
</script>


</body>

</html>