<?php

include "classes/html.class.php";

$html = new html("ADD TASK");


$db = new db();

$whereFarm = ($_SESSION['farm_id'] == 9) ? "record_id = {$_SESSION['farm_id']} OR record_id = 10" : "record_id = {$_SESSION['farm_id']}";

$whereFarm = ($_SESSION['farm_id'] == 0) ? "1" : "record_id = {$_SESSION['farm_id']}";

$whereFarmUser = ($_SESSION['farm_id'] == 9) ? "1" : "farm_id = {$_SESSION['farm_id']} OR farm_id = 10";
$whereFarmUser = ($_SESSION['farm_id'] == 0) ? "1" : "farm_id = {$_SESSION['farm_id']}";

if ($_SESSION['farm_id'] == "5" || $_SESSION['farm_id'] == "12" || $_SESSION['farm_id'] == "13") {

    $whereFarm = ($_SESSION['farm_id'] == 5) ? "5" : "record_id = {$_SESSION['farm_id']}";

    $whereFarmUser = ($_SESSION['farm_id'] == 5) ? "5" : "farm_id = 5 AND farm_id = 13 AND farm_id = 12";

    $farms_res = $db->exec_query('farms', ["*"], '', '', '', '', "farm_name LIKE 'Brondal 1%'", '', false);

} else {
    $farms_res = $db->exec_query('farms', ["*"], '', '', '', '', $whereFarm, '', false);
}

if ($whereFarm == "1") {

    $farm_list = '<option></option>';

} else {
    $farm_list = '<option></option>';

}

while ($farms = $farms_res->fetch_assoc()) {
    $farm_list = $farm_list . "<option value='{$farms['record_id']}'>{$farms['farm_name']}</option>";

    $sections_res = $db->exec_query('farm_sections', ['*'], '', '', '', '', "farm_id = {$farms['record_id']}");

    $sections_selects = $sections_selects . "<select id='section_id_{$farms['record_id']}' hidden name='section_id' onchange='show_blocks(this.value)' class='form_input'><option></option>";
    while ($sections = $sections_res->fetch_assoc()) {

        $sections_selects = $sections_selects . "<option value='{$sections['record_id']}'>{$sections['name']}</option>";

        $block_res = $db->exec_query('farm_blocks', ['*'], '', '', '', '', "section_id = {$sections['record_id']}");

        $table_blocks = $table_blocks . "<table hidden name='blocks_tables' style='width:100%; text-align: center;' id='blocks_{$sections['record_id']}'>";
        $block_arr = [];
        while ($block = $block_res->fetch_assoc()) {
            $block_arr[] = $block['name'];
        }
        $cluster_array = $block_arr;
        $cluster_count = count($cluster_array);
        $cluster_per_col = ceil($cluster_count / 3);
        for ($i = 0; $i < $cluster_per_col; $i++) {
            $table_blocks = $table_blocks . "<tr>";
            for ($j = 0; $j < 3; $j++) {
                $index = $i + ($j * $cluster_per_col);
                if (isset($cluster_array[$index])) {
                    $table_blocks = $table_blocks . "<td><input type='checkbox' name='cluster[]' value='{$cluster_array[$index]}' class='check_box'><label for='' value='{$cluster_array[$index]}'>{$cluster_array[$index]}</label></td>";
                }
            }
            $table_blocks = $table_blocks . "</tr>";
        }

        $table_blocks = $table_blocks . "</table>";

    }
    $sections_selects = $sections_selects . "</select>";
}

$farm_list = $farm_list . "<option value='{$farms['record_id']}'>{$farms['farm_name']}</option>";
$farming_name = "";
$farming_type_options = "";
$farming_type_res = $db->exec_query('farming_types', ['*']);
while ($farming_type = $farming_type_res->fetch_assoc()) {
    $farming_type_options = $farming_type_options . "<option value='{$farming_type['record_id']}'>{$farming_type['name']}</option>";

    $farming_name = $farming_name . "<select id='farming_action' hidden name='farming_action' class='form_input'><option></option>";

    $farming_action_res = $db->exec_query("farming_action", ['*'], '', '', '', '', "farming_type_id = {$farming_type['record_id']}");

    while ($farming_action = $farming_action_res->fetch_assoc()) {
        $farming_name = $farming_name . "<option value='{$farming_action['record_id']}'>{$farming_action['name']}</option>";

    }

    $farming_name = $farming_name . "</select>";
}


// 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' OR user_type = 'Section Manager with fuel' AND $whereFarmUser", '', false);
$cluster_res = $db->exec_query('clusters', ['*']);


?>

<div class='form'>
    <br>

    <label style="font-size:1.5vw">FARM:</label><br>
    <select id='farm_id' onchange="show_section(this.value)" class='form_input'>
        <?
        echo $farm_list;
        ?>
    </select>

    <?php echo $sections_selects; ?>
    <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">FARMING TYPE:</label><br>
    <select id='farming_type' onchange="show_action(this.value)" class='form_input'>
        <option></option>
        <?
        echo $farming_type_options;
        ?>
    </select>
    <br><br>
    <label style="font-size:1.5vw" id="action_label" hidden>FARMING ACTION:</label><br>
    <?php echo $farming_name; ?>
    <hr>
    <br><br>

    <label style="font-size:1.5vw; ">BLOCKS:</label><br><br>

    <br><br>
    <?php echo $table_blocks; ?>

    <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>
        <?
        if ($_SESSION['user_type'] == "SECTION MANAGER" || $_SESSION['user_type'] == "SECTION MANAGER WITH FUEL") {
            echo "<option value='{$_SESSION['user_id']}'>{$_SESSION['username']}</option>";
        } else {
            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 show_blocks(section_id) {
        for (var i = 0; i < document.getElementsByName("blocks_tables").length; i++) {
            document.getElementsByName("blocks_tables")[i].hidden = true;
        }

        document.getElementById("blocks_" + section_id).hidden = false;
    }

    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 show_section(farm_id) {
        for (var i = 0; i < document.getElementsByName("section_id").length; i++) {
            document.getElementsByName("section_id")[i].hidden = true;
        }
        for (var i = 0; i < document.getElementsByName("blocks_tables").length; i++) {
            document.getElementsByName("blocks_tables")[i].hidden = true;
        }
        // alert("section_id_" + farm_id);/
        document.getElementById("section_id_" + farm_id).hidden = false;

    }

    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 show_action(id) {
        for (var i = 0; i < document.getElementsByName("farming_action").length; i++) {
            document.getElementsByName("farming_action")[i].hidden = true;
        }
        var action_label = document.getElementById('action_label');
        var select = document.getElementsByName("farming_action")[id - 1];
        action_label.hidden = false;
        select.hidden = false;

    }

    function ajax_func() {

        var farming_type = document.getElementById('farming_type').value;
        var farming_action = document.getElementsByName('farming_action')[farming_type - 1].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 (farming_action < 1) {
            alert("PLEASE SELECT A FARMING ACTION");
        } else {
            if (farming_type.length < 1) {
                alert("PLEASE SELECT A FARMING 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("farming_action", farming_action);
                        formData.append("farming_type", farming_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>