<?php

include "classes/html.class.php";

$html = new html("EDIT ERRANDS");

$db = new db();

// if ($_SESSION['user_type'] != "GENERAL MANAGER" ){
//     echo "USER NOT ACCESS IS NOT AUTHORISED TO HAVE ACCESS TO THIS PAGE"
// } else{



// var_dump($_GET);

$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']}";


$farms_res = $db->exec_query('farms', ["*"], '', '', '', '', $whereFarm);
if ($whereFarm == "1") {

    $farm_list = '<option></option>';
} else {
    $farm_list = '<option></option>';

}

while ($farm = $farms_res->fetch_assoc()) {

    $farm_list = $farm_list . "<option value='{$farm['record_id']}'>{$farm['farm_name']}</option>";

    $sections_res = $db->exec_query('farm_sections', ['*'], '', '', '', '', "farm_id = {$farm['record_id']}", '', false);

    $farm_blocks_res = $db->exec_query('farm_blocks', ["*"], '', '', '', '', "name = '{$cluster[0]}'", '', false);
    $blocks = $farm_blocks_res->fetch_assoc();

    $sections_selects = $sections_selects . "<select id='section_id_{$farm['record_id']}' hidden name='section_id' onchange='show_blocks(this.value)' class='form_input'><option></option>";

    if ($whereFarm == 1 && $errand_id == $_GET['errand_id']) {
        $sections_selects = $sections_selects . "<select id='section_id_{$farm['record_id']}' value='{$blocks['section_id']}' name='section_id' onchange='show_blocks(this.value)' class='form_input'><option></option>";

        $sections_selects = $sections_selects . "<option value='{$blocks['section_id']}'>{$blocks['section_name']}</option>";
    }

    while ($sections = $sections_res->fetch_assoc()) {

        $sections_selects = $sections_selects . "<option value='{$sections['record_id']}'>{$sections['name']}</option>";

        $mananagement_res = $db->exec_query('management', ['*']);
        while ($data = $mananagement_res->fetch_assoc()) {

            $cluster = explode(', ', $data['cluster_ids']);

        }

        $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'];
        }
        $mananagement_res = $db->exec_query('management', ['*']);
        $data = $mananagement_res->fetch_assoc();

        $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);
                $cluster = explode(', ', $data['cluster_ids']);

                if (isset($cluster_array[$index])) {
                    if (in_array($cluster_array[$index], $cluster)) {

                        $table_blocks = $table_blocks . "<td><input type='checkbox' name='cluster[]' value='{$cluster_array[$index]}' 
                        checkedclass='check_box' checked><label for='' value='{$cluster_array[$index]}'>{$cluster_array[$index]}</label></td>";
                    } else {
                        $table_blocks = $table_blocks . "<td><input type='checkbox' name='cluster[]' value='{$cluster_array[$index]}' id='{$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 = "";

$mananagement_res = $db->exec_query('management', ['*'], '', '', '', '', "record_id = {$_GET['errand_id']}", '', false);
$manage_data = $mananagement_res->fetch_assoc();

$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_{$farming_type['record_id']}' hidden name='farming_action' class='form_input'><option></option>";

    $farming_action_res = $db->exec_query("farming_action", ['*'], '', '', '', '', "farming_type_id = {$farming_type['record_id']}", '', false);

    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>";
}

$user_res = $db->exec_query('users', ['*'], '', '', '', '', "user_type = 'MANAGER' AND $whereFarmUser");

$user_list = '<option></option>';

while ($users = $user_res->fetch_assoc()) {
    $user_list = $user_list . "<option value='{$users['record_id']}'>{$users['username']}</option>";
}

$cluster_res = $db->exec_query('clusters', ['*']);

$errand_info_res = $db->exec_query('management', ['*'], '', '', '', '', "record_id = {$_GET['errand_id']}", '', false);
$errand_info = $errand_info_res->fetch_assoc();

?>

<div class="form">
    <br>

    <label style="font-size:1.5vw">FARMING TYPE:</label><br>
    <select class="form_input" style="width:75%;" onchange="show_action(this.value)" name="farming_type_id"
        id="farming_type_id">
        <option></option>
        <?php
        $farming_types_res = $db->exec_query('farming_types', ["*"]);
        while ($farming_type = $farming_types_res->fetch_assoc()) {
            echo "<option value='{$farming_type['record_id']}'>{$farming_type['name']}</option>";
        }
        ?>
    </select>

    <script>
        document.getElementById("farming_type_id").value = "<?php echo $errand_info['farming_type_id'] ?>";
    </script>
    <br><br>

    <label style="font-size:1.5vw" id="action_label" hidden>FARMING ACTION:</label><br>
    <?php echo $farming_name; ?>
    <br><br>

    <script>
        document.getElementById("farming_action_<?php echo $errand_info['farming_type_id'] ?>").value = "<?php echo $errand_info['farming_action_id'] ?>";

    </script>

    <label style="font-size:1.5vw">Start Date:</label>
    <br>
    <input type="datetime-local" class="form_input" style="width:75%;" id="action_date" name="action_date">
    <script>
        document.getElementById("action_date").value = "<?php echo $errand_info['action_date'] ?>";
    </script>
    <br>
    <br>

    <label style="font-size:1.5vw">Farm:</label>
    <br>
    <select id='farm_id' onchange="hide_cluster(); show_section(this.value);" class='form_input'>
        <? echo $farm_list; ?>
    </select>

    <script>
        document.getElementById("farm_id").value = "<?php echo $errand_info['farm_id'] ?>";
    </script>

    <?php echo $sections_selects; ?>

    <script>
        document.getElementById("section_id_<?php echo $errand_info['farm_id']; ?>").value = "<?php echo $errand_info['farm_id'] ?>";
    </script>
    <br><br>
    <hr>

    <label style="font-size:1.5vw">CLUSTERS:</label>
    <br>
    <br><br>

    
    <div id="cluster_div">

    <?php

    //if the show_blocks onchange event is triggered, hide this code
    

    $cluster = explode(',', $errand_info['cluster_ids']);

    $farm_blocks_res = $db->exec_query('farm_blocks', ["*"], '', '', '', '', "name = '{$cluster[0]}'", '', false);
    $blocks = $farm_blocks_res->fetch_assoc();

    $blocks['section_id'];

    $table_blocks = $table_blocks . "<table name='blocks_tables' style='width:100%; text-align: center;' id='blocks_{$blocks['section_id']}'><tr>";
    $farm_blocks_res = $db->exec_query('farm_blocks', ['*'], '', '', '', '', "section_id = {$blocks['section_id']}", '', false);
    while ($farm_blocks = $farm_blocks_res->fetch_assoc()) {
        if (in_array($farm_blocks['name'], $cluster)) {
            echo "<tr><td><input type='checkbox' name='cluster[]' class='check_box' value='{$farm_blocks['name']}' id='{$farm_blocks['name']}' checked/><label for='' value='{$farm_blocks['name']}'>{$farm_blocks['name']}</label></td></tr>";
        } else {
            echo "<tr><td><input type='checkbox' name='cluster[]' class='check_box' value='{$farm_blocks['record_id']}' id='{$farm_blocks['record_id']}'/><label for='' value='{$farm_blocks['name']}'>{$farm_blocks['name']}</label></td></tr>";
        }
    }
    $table_blocks = $table_blocks . "</tr></table>";

    ?>
    </div>

    <?php echo $table_blocks; ?>

    <hr>
    <label style="font-size:1.5vw">RATING:</label><br>
    <select id='rating' class='form_input' value="<?php echo $row['rating'] ?>" 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>
    <script>
        document.getElementById("rating").value = "<?php echo $errand_info['rating'] ?>";
    </script>
    <br><br>

    <label style="font-size:1.5vw">MANAGER:</label><br>
    <select id='user_id' class='form_input'>
        <?php echo $user_list; ?>
    </select>
    <script>
        document.getElementById("user_id").value = "<?php echo $errand_info['user_id_assigned'] ?>";
    </script>
    <br><br>

    <label style="font-size:1.5vw">Instructions:</label>
    <br>
    <textarea class="text_input" style="width:90%; font-size:1vw" id="instructions"
        name="instructions"><?php echo $errand_info['instructions'] ?></textarea>
    <br><br>
    <div id="images">
        <label style="font-size:1.5vw">UPLOADED IMAGE:</label><br><br>

        <?php
        $image_res = $db->exec_query('management', ["*"], '', '', '', '', "record_id = '{$_GET['errand_id']}'", '', false);
        while ($image = $image_res->fetch_assoc()) {
            $imgArray = explode(',', $image['image']);

            foreach ($imgArray as $imgFile) {
                if ($imgFile == '') {
                    continue;
                } else {
                    echo "<img src='/taskimages/$imgFile' id='uploadedImage' style='width:60%;'><br><br>";

                }
            }
        }
        ?>

        <br>
        <button class="form_input" id="image_index" value="0" onclick="add_image()">ADD IMAGE</button><br><br>

    </div>
    <script>
        function add_image() {
            var index = document.getElementById('image_index').value;
            var image = document.getElementById('images');
            image.innerHTML += '<input type="file" id="image_' + index + '" name="image_' + index + '" accept="image/*" class="form_input" capture><br><br><img id="uploadedImage" style="display:none; width: 80%; height: auto; margin: 0 auto;" />';
            console.log(index);
            index++;
            document.getElementById('image_index').value = index;
        }

    </script>
    <br><br>

    <input type="text" class="form_input" id="errand_img" hidden name="errand_img"
        value="<?php echo $errand_info['image'] ?>" />

    <input type="text" class="form_input" id="errand_id" hidden name="errand_id"
        value="<?php echo $_GET['errand_id'] ?>" />

    <button class="form_btn" style="transform:scale(1);font-size: 1.5vw;" onclick="update_ajax()">UPDATE ERRAND</button>
</div>

<br><br>
<br><br>

<script>

    // on change hide the data
    function hide_data() {
        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;
        }
    }

    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 hide_cluster(){
        document.getElementById("cluster_div").style.display = "none";

    }

    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 update_ajax() {

        var errand_img = document.getElementById('errand_img').value;
        var farming_type = document.getElementById('farming_type_id').value;
        var farming_action = document.getElementsByName('farming_action')[farming_type - 1].value;
        var rating = document.getElementById('rating').value;
        var cluster = getCheckedValue()
        var user_id = document.getElementById('user_id').value;
        var instruction = document.getElementById('instructions').value;
        var farm_id = document.getElementById('farm_id').value;
        var action_date = document.getElementById('action_date').value.replace("T", " ");
        var errand_id = document.getElementById('errand_id').value;
        var image_index = document.getElementById('image_index').value;

        if (farming_type.length < 1) {
            alert("PLEASE SELECT A FARMING TYPE");
        } else {
            if (user_id.length < 1) {
                alert("PLEASE SELECT A 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("user_id", user_id);
                    formData.append("instruction", instruction);
                    formData.append("farm_id", farm_id);
                    formData.append("action_date", action_date);
                    formData.append("errand_id", errand_id);
                    formData.append("image_index", image_index);
                    formData.append("errand_img", errand_img);

                        for (var i = 0; i < image_index; i++) {
                            // alert(i);
                            var imageElement = document.getElementById('image_' + i);
                            if (imageElement && imageElement.files.length > 0) {
                                var image = imageElement.files[0];
                                console.log("Processing image " + i);
                                formData.append("image_" + i, image);
                                console.log(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('ERREND UPDATED SUCCESSFULLY');
                            window.location.href = "management.php";
                        }
                    }

                    xhttp.open("POST", "ajax/update_errend.ajax.php");
                    xhttp.send(formData);
                

            }
        }
    }
}

    show_action(<?php echo $errand_info['farming_type_id'] ?>);

    rating_color(<?php echo $errand_info['rating'] ?>);

    getCheckedValue();
</script>