<?php

include "classes/html.class.php";

$html = new html("FARMING");


$db = new db();

$whereFarm = ($_SESSION['farm_id'] == 0) ? "1" : "record_id = {$_SESSION['farm_id']}";
$whereFarmUser = ($_SESSION['farm_id'] == 0) ? "1" : "farm_id = {$_SESSION['farm_id']}";

$farms_res = $db->exec_query('farms', ["*"], '', '', '', '', $whereFarm);
if ($whereFarm == "1") {

    $farm_list = '<option value="0">ALL</option>';
} else {
    $farm_list = '';

}
while ($farms = $farms_res->fetch_assoc()) {
    $farm_list = $farm_list . "<option value='{$farms['record_id']}'>{$farms['farm_name']}</option>";
}

// fetch all the log reasons
$task_name_res = $db->exec_query('task_names', ['*']);
$task_type_res = $db->exec_query('task_types', ['*']);
$user_res = $db->exec_query('users', ['*'], '', '', '', '', "user_type = 'Section Manager' AND $whereFarmUser");
$cluster_res = $db->exec_query('clusters', ['*']);

?>

<div class='form'>
    <br>

    <label style="font-size:1.5vw">FARM:</label><br>
    <select id='farm_id' class='form_input'>
        <?
        echo $farm_list;
        ?>
    </select>
    <br><br>
    <!-- <h1 style="font-size:3.5vw">TASK:</h1> -->
    <label style="font-size:1.5vw">ACTION DATE:</label><br>
    <input type="DateTime-Local" name="action_date" id="action_date" class="form_input">
    <br><br>
    <!-- <h1 style="font-size:3.5vw">TASK:</h1> -->
    <label style="font-size:1.5vw">TASKS NAME:</label><br>
    <select id='task_name' class='form_input'>
        <option></option>
        <?
        while ($row = $task_name_res->fetch_assoc()) {
            echo "<option value='{$row['record_id']}'>{$row['task_name']}</option>";
        }
        ?>
    </select>
    <br><br>
    <label style="font-size:1.5vw">TASK TYPE:</label><br>
    <select id='task_type' class='form_input'>
        <option></option>
        <?
        while ($row = $task_type_res->fetch_assoc()) {
            echo "<option value='{$row['record_id']}'>{$row['task_type']}</option>";
        }
        ?>
    </select>
    <br><br>
    <hr>
    <br><br>

    <label style="font-size:1.5vw; ">CLUSTER:</label><br><br>
    <table style="width:100%; text-align: center;">
        <?
        $cluster_array = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z');
        $cluster_count = count($cluster_array);
        $cluster_per_col = ceil($cluster_count / 3);
        for ($i = 0; $i < $cluster_per_col; $i++) {
            echo "<tr>";
            for ($j = 0; $j < 3; $j++) {
                $index = $i + ($j * $cluster_per_col);
                if (isset($cluster_array[$index])) {
                    echo "<td><input type='checkbox' name='cluster[]' value='{$cluster_array[$index]}' class='check_box'><label for='' value='{$cluster_array[$index]}'>{$cluster_array[$index]}</label></td>";
                }
            }
            echo "</tr>";
        }
        ?>
    </table>
    <br><br>

    <hr>
    <br><br>
    <label style="font-size:1.5vw">RATING:</label><br>
    <select id='rating' class='form_input' onchange="rating_color(rating)">
        <option></option>
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
        <option value="4">4</option>
        <option value="5">5</option>
        <option value="6">6</option>
        <option value="7">7</option>
        <option value="8">8</option>
        <option value="9">9</option>
        <option value="10">10</option>
    </select>
    <br><br>
    <label style="font-size:1.5vw">SECTION MANAGER:</label><br>
    <select id='username' class='form_input'>
        <option></option>
        <?
        while ($row = $user_res->fetch_assoc()) {
            echo "<option value='{$row['record_id']}'>{$row['username']}</option>";
        }
        ?>
    </select>
    <br><br>
    <label style="font-size:1.5vw">INSTRUCTIONS:</label><br>
    <textarea type='text' style="width: 80%;" id='instruction' class='form_input'
        oninput="this.style.height = ''; this.style.height = this.scrollHeight + 'px'"></textarea>
    <br><br>
    <label style="font-size:1.5vw">UPLOAD IMAGE:</label><br>
    <input type="file" id="image" name="image" accept="image/*" class='form_input' capture><br><br>
    <img id="uploadedImage" style="display:none; width: 80%; height: auto; margin: 0 auto;" />

    <script>
        document.getElementById('image').addEventListener('change', function (event) {
            var file = event.target.files[0];
            if (file) {
                var reader = new FileReader();
                reader.onload = function (e) {
                    var imgElement = document.getElementById('uploadedImage');
                    imgElement.src = e.target.result;
                    imgElement.style.display = 'block';
                }
                reader.readAsDataURL(file);
            }
        });
    </script>
    <br><br>
    <input type='submit' value='ADD' class='form_btn' onclick='this.disabled=true; this.value="LOADING..."; setTimeout(function(){ document.querySelector(".form_btn").disabled=false; document.querySelector(".form_btn").value="ADD"; }, 30000); ajax_func()' />
    <br><br>



</div>
<br><br>
<br><br>

<script>
    function rating_color() {
        var rating = document.getElementById('rating').value;

        if (rating == 10) {
            document.getElementById('rating').style.backgroundColor = 'red';
        } else if (rating >= 7) {
            document.getElementById('rating').style.backgroundColor = 'rgba(255, 0, 0, 0.4)';
        } else if (rating >= 4) {
            document.getElementById('rating').style.backgroundColor = '#ffa50091';
        } else if (rating < 3) {
            document.getElementById('rating').style.backgroundColor = 'lightgreen';
        }
    }


    function getCheckedValue() {
        // Select all checked checkboxes
        const checkboxes = document.querySelectorAll('input[type="checkbox"]:checked');
        // Extract values from the checked checkboxes
        const values = Array.from(checkboxes).map(checkbox => checkbox.value);
        // Join values into a string
        const resultString = values.join(',');
        return resultString;
    }

    function ajax_func() {

        var task_name = document.getElementById('task_name').value;
        var task_type = document.getElementById('task_type').value;
        var rating = document.getElementById('rating').value;
        var cluster = getCheckedValue()
        var username = document.getElementById('username').value;
        var instruction = document.getElementById('instruction').value;
        var farm_id = document.getElementById('farm_id').value;
        var action_date = document.getElementById('action_date').value.replace("T", " ");

        var image = document.getElementById('image').files[0];

        if (task_name.length < 1) {
            alert("PLEASE SELECT A TASK NAME");
        } else {

            if (task_type.length < 1) {
                alert("PLEASE SELECT A TASK TYPE");
            } else {
                if (username.length < 1) {
                    alert("PLEASE SELECT A SECTION MANAGER");
                } else {

                    if (rating.length < 1) {
                        alert("PLEASE SELECT A RATING");
                    } else {

                        var formData = new FormData();
                        formData.append("task_name", task_name);
                        formData.append("task_type", task_type);
                        formData.append("cluster", cluster);
                        formData.append("rating", rating);
                        formData.append("username", username);
                        formData.append("instruction", instruction);
                        formData.append("farm_id", farm_id);
                        formData.append("action_date", action_date);
                        formData.append("image", image);

                        // Create an XMLHttpRequest object
                        const xhttp = new XMLHttpRequest();
                        // Define a callback function
                        xhttp.onload = function () {
                            // alert(this.responseText);

                            // Here you can use the Data
                            if (this.responseText != 1) {

                                alert(this.responseText);

                            } else {
                                alert('TASK ADDED');
                                window.location.href = "tasks.php";
                            }
                        }

                        xhttp.open("POST", "ajax/new_task.ajax.php");
                        xhttp.send(formData);
                    }
                }
            }
        }
    }
</script>


</body>

</html>