<?php
session_start();
$currDir = __DIR__;
$rootDir = dirname(dirname($currDir));
$mysydeDir = $rootDir . '/mysyde';

require_once($rootDir .  '/vendor/autoload.php');
require_once($rootDir . "/mysyde/frontend/frontend_functions.inc.php");

$envDir = $rootDir . '/config';
$envFilePath = $envDir . '/.env';
if (is_dir($envDir) && file_exists($envFilePath) && is_file($envFilePath) && is_readable($envFilePath)) {
    $dotenv = new \Dotenv\Dotenv($envDir);
    $dotenv->load();
}
$common = $mysydeDir ."/common/common_functions.inc.php";
require_once($common);

$connEnv = (local_environment()) ? $mysydeDir."/dc.config.php" : $mysydeDir."/dc-server.config.php";

require_once($connEnv);

db_connect();

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $task_id = $_POST['task_id'];
    switch ($_POST['action']) {
        case 'complete_task':
            complete_task($task_id, $_POST['status']);
            break;
        case 'load_card':
            load_card($task_id);
            break;
        case 'delete_group':
            delete_group($task_id);
            break;
        case 'delete_task':
            delete_task($task_id);
            break;
        case 'get_tasks':
            get_tasks_ajax($task_id, $_POST['status'], $_POST['main_contact_id']);
            break;
        case 'count_tasks':
            count_tasks_ajax($task_id, $_POST['status'], $_POST['main_contact_id']);
            break;
        default:
            break;
    }
}

function complete_task($task_id, $status){
    $query = "UPDATE tasks SET
        status = ".$status."
        WHERE id = ".$task_id."
    LIMIT 1";
    $result = @mysqli_query($GLOBALS['mysql_con'], $query);
}

function delete_group($group_id){
    $query_delete = "DELETE FROM task_group WHERE id = ".$group_id;
    $result_delete = @mysqli_query($GLOBALS['mysql_con'], $query_delete);


    $query = "SELECT * FROM tasks WHERE task_group_id = ".$group_id;
    $result = @mysqli_query($GLOBALS['mysql_con'], $query);
    
    while($row = @mysqli_fetch_array($result)){
        $query_link = "DELETE FROM task_contact_link WHERE task_id = ".$row['id'];
        $result_link = @mysqli_query($GLOBALS['mysql_con'], $query_link);

        $query_task = "DELETE FROM tasks WHERE id = ".$row['id'];
        $result_task = @mysqli_query($GLOBALS['mysql_con'], $query_task);
    }
}

function delete_task($task_id){
    $query_link = "DELETE FROM task_contact_link WHERE task_id = ".$task_id;
    $result_link = @mysqli_query($GLOBALS['mysql_con'], $query_link);

    $query_task = "DELETE FROM tasks WHERE id = ".$task_id;
    $result_task = @mysqli_query($GLOBALS['mysql_con'], $query_task);
}

function get_main_contact($main_contact_id){
    $query = "SELECT * FROM main_contact WHERE id = ".$main_contact_id;
    $result = @mysqli_query($GLOBALS['mysql_con'], $query);
    $row = @mysqli_fetch_array($result);
    return $row;
}

function get_tasks_ajax($task_group_id, $status, $main_contact_id){
    $query = "SELECT tasks.* FROM tasks LEFT JOIN task_contact_link ON tasks.id = task_contact_link.task_id WHERE main_contact_id = ".$main_contact_id . " AND modified_user = ".$main_contact_id." AND task_group_id = ".$task_group_id . " AND status = ".$status;
    if($task_group_id == -1){
        $query = "SELECT tasks.* FROM tasks LEFT JOIN task_contact_link ON tasks.id = task_contact_link.task_id WHERE main_contact_id = ".$main_contact_id . " AND modified_user != ".$main_contact_id." AND status = ".$status;
    }
    if($task_group_id == -2){
        $query = "SELECT tasks.* FROM tasks LEFT JOIN task_contact_link ON tasks.id = task_contact_link.task_id WHERE main_contact_id = ".$main_contact_id . " AND status = ".$status;
    }
    $result = @mysqli_query($GLOBALS['mysql_con'], $query);
    $i = 0;
    while($row = @mysqli_fetch_array($result)){
        $class = '';
        $complete = 1;
        if($status == 1){
            $complete = 0;
        }
        if($row['modified_user'] != $main_contact_id){
            $class = 'asap';
        }
        echo "<div class='task_item ".$class."' data-complete='".$complete."' data-id='".$row['id']."'>".$row['title']."<span class='complete_task'></span></div>";
        $i++;
    }
    if($i == 0 && $status == 0){
        echo "<div class=''>Aktuell sind keine Tasks vorhanden.</div>";
    }
}

function count_tasks_ajax($task_group_id, $status, $main_contact_id){
    $query = "SELECT tasks.* FROM tasks LEFT JOIN task_contact_link ON tasks.id = task_contact_link.task_id WHERE main_contact_id = ".$main_contact_id . " AND modified_user = ".$main_contact_id." AND task_group_id = ".$task_group_id . " AND status = ".$status;
    if($task_group_id == -1){
        $query = "SELECT tasks.* FROM tasks LEFT JOIN task_contact_link ON tasks.id = task_contact_link.task_id WHERE main_contact_id = ".$main_contact_id . " AND modified_user != ".$main_contact_id." AND status = ".$status;
    }
    if($task_group_id == -2){
        $query = "SELECT tasks.* FROM tasks LEFT JOIN task_contact_link ON tasks.id = task_contact_link.task_id WHERE main_contact_id = ".$main_contact_id . " AND status = ".$status;
    }
    $result = @mysqli_query($GLOBALS['mysql_con'], $query);
    $count = 0;
    while($row = @mysqli_fetch_array($result)){
        $count++;
    }
    echo $count;
}

function create_contact_select($task_id){
    $query = "SELECT * FROM main_contact ORDER BY name";
    $contact_result = @mysqli_query($GLOBALS['mysql_con'], $query);
    
    $preselect = array();

    $query = "SELECT * FROM task_contact_link WHERE task_id = ".$task_id;
    $result = @mysqli_query($GLOBALS['mysql_con'], $query);
    
    while($row = @mysqli_fetch_array($result)){
        array_push($preselect,$row['main_contact_id']);
    }
    ?>
    <div class="contact bc-select-ui ui fluid multiple search selection dropdown" style="clear:both;display:inline-block;">
    <input id='task_persons' class='code' type='hidden' name='task_persons'>
        <i class="dropdown icon"></i>
        <div class="default text">Person hinzufügen</div>
        <div class="menu">
            <?  
                while($contact = @mysqli_fetch_array($contact_result)) {
                    echo "<div class=\"item\" data-value=\"{$contact['id']}\">".$contact["name"]."</div>";
                }
            ?>
        </div>
    </div>
    <script type="text/javascript" src="/plugins/jquery/jquery-3.5.1.min.js"></script>
    <script type="text/javascript" src="/plugins/Semantic-UI-master/semantic.min.js"></script>
    <!-- <link rel="stylesheet" type="text/css" href="/plugins/Semantic-UI-master/bc-semantic.css?time=<?= filemtime($_SERVER['DOCUMENT_ROOT'] . '/plugins/Semantic-UI-master/bc-semantic.css')?>"> -->
    <script>
        var $y = jQuery.noConflict();
        $y( document ).ready(function() {
            $y('.contact.ui.fluid.multiple.dropdown').dropdown('set selected', <?= json_encode($preselect) ?>); 
        });
    </script>
<?
}
function load_card($task_id){
    $query = "SELECT * FROM tasks WHERE id = ".$task_id;
    $result = @mysqli_query($GLOBALS['mysql_con'], $query);
    $row = @mysqli_fetch_array($result);
    $due_date = new DateTime($row['due_date']);
    $modified_date = new DateTime($row['modified_date']);
    ?>
    <button id="back">Zurück</button>
    <div class='task_item_card'>
        <h4 class='task_item_card_title'><span class='complete_task'></span><?= $row['title']?></h4>
        <p class='task_item_card_text'><?= $row['description']?></p>
        <div class='task_item_card_info'>
            <span>von: <?= get_main_contact($row['modified_user'])['name']?></span>
            <span>erstellt am: <?= $modified_date->format('d.m.Y')?></span>
        </div>
    </div>
    <div class='due_date'>Fälligkeit: <?= $due_date->format('d.m.Y')?></div>
    <form method='post' class="edit_task">
        <input type='hidden' name='task_id' value='<?= $task_id?>'>
        <div class="form_group">
            <label for="due_date">Fälligkeit:</label>
            <input type='date' name='due_date' value='<?= $due_date->format('Y-m-d')?>'>
        </div>
        <!-- <input type='datetime-local' name='memory_date'> -->
        <?= create_contact_select($row['id'])?>
        <div class="form_group">
            <label for="due_date">Aufgabenname:</label>
            <input type='text' name='title' value='<?= $row['title']?>' placeholder='Titel'>
            </div>
        <textarea name='description' placeholder='Notiz hinzufügen'><?= $row['description']?></textarea>
        <input type='submit' class='button_main' name='submit_edit' value='Änderungen speichern'>
    </form>
    <div data-id='<?= $task_id ?>' class='delete_task'><svg xmlns="http://www.w3.org/2000/svg" width="27" height="31.5" viewBox="0 0 27 31.5">
  <g id="delete" transform="translate(-4.5 -2.25)">
    <path id="Pfad_276" data-name="Pfad 276" d="M13.5,13.5h2.25V27H13.5Z"/>
    <path id="Pfad_277" data-name="Pfad 277" d="M20.25,13.5H22.5V27H20.25Z"/>
    <path id="Pfad_278" data-name="Pfad 278" d="M4.5,6.75V9H6.75V31.5A2.25,2.25,0,0,0,9,33.75H27a2.25,2.25,0,0,0,2.25-2.25V9H31.5V6.75ZM9,31.5V9H27V31.5Z"/>
    <path id="Pfad_279" data-name="Pfad 279" d="M13.5,2.25h9V4.5h-9Z"/>
  </g>
</svg>
</div>
<?php }