<?php

$task_group_id = 0;
if(isset($_GET['task_group_id'])){
    $task_group_id = $_GET['task_group_id'];
    if($task_group_id == "-1/"){
        $task_group_id = "-1";
    }
}

function get_task_groups($task_group_id){
    $query_group = "SELECT * FROM task_group WHERE main_contact_id = ".$GLOBALS['main_contact']['id'];
    $result_group = @mysqli_query($GLOBALS['mysql_con'], $query_group);
    while($row_group = @mysqli_fetch_array($result_group)){
        echo "<li data-id='".$row_group['id']."'><svg xmlns='http://www.w3.org/2000/svg' width='17.5' height='18.421' viewBox='0 0 17.5 18.421'>
        <g id='bx-building-house' transform='translate(-3 -3)'>
          <path id='Pfad_20' data-name='Pfad 20' d='M18.658,3H9.448A1.844,1.844,0,0,0,7.605,4.842V9.987L3.27,14.322A.921.921,0,0,0,3.921,15.9V20.5a.921.921,0,0,0,.921.921H19.579A.921.921,0,0,0,20.5,20.5V4.842A1.844,1.844,0,0,0,18.658,3ZM11.29,19.579H5.763V14.434l2.763-2.763,2.763,2.763Zm7.369,0H13.132V15.9a.92.92,0,0,0,.651-1.573L9.448,9.987V4.842h9.211Z' transform='translate(0)' />
          <path id='Pfad_21' data-name='Pfad 21' d='M14.184,9h1.842v1.842H14.184Zm3.684,0h1.842v1.842H17.869Zm0,3.713h1.842v1.814H17.869Zm0,3.656h1.842v1.842H17.869ZM10.5,17.29h1.842v1.842H10.5Z' transform='translate(-2.895 -2.316)' />
        </g>
        </svg>
        <a href='?task_group_id=".$row_group['id']."'>".$row_group['description']."</a> <span class='number count_group_".$row_group['id']."'></span> <span data-id='".$row_group['id']."' class='delete_group'><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></span></li>";
    }
}

function get_contact_from_id($main_contact_id){
    $query_select = "SELECT * FROM main_contact WHERE id = '".$main_contact_id."'";
    $result_select = @mysqli_query($GLOBALS['mysql_con'], $query_select);
    $row_select = @mysqli_fetch_array($result_select);
    return $row_select;
}

function send_mail($recipient_id, $task_id){
    $query_select = "SELECT * FROM tasks WHERE id = '".$task_id."'";
    $result_select = @mysqli_query($GLOBALS['mysql_con'], $query_select);
    $row_select = @mysqli_fetch_array($result_select);

    $due_date = new DateTime($row_select['due_date']);

    $recipient = get_contact_from_id($recipient_id);
    $sender = get_contact_from_id($row_select['modified_user']);

    $subject = "Neuer Task im Intranet";
    $message .= "<h1>Es wurde in neuer Task im Intranet zugewiesen.</h1>" . "\n";
    $message .= "<strong>Titel:</strong> " .$row_select['title']. "\n";
    $message .= "<strong>Beschreibung:</strong> " .$row_select['description']. "\n";
    $message .= "<strong>Fälligkeitsdatum</strong> " .$due_date->format('d.m.Y'). "\n";
    $message .= "<strong>Erstellt von:</strong> " .$sender['name']. "\n\n";
    $message .= "<a href='https://".$_SERVER['HTTP_HOST']."'>Zum Intranet</a>";

    if (mail_create($subject,
    $message,
    'tasks@ihnen-group.de',
    $recipient["email"],
    'Tasks Intranet',
    $recipient["name"],
    FALSE,
    "",
    "",
    "", 0, "", "")) {
                
        mail_send();
        clearstatcache();
    }
}

if(isset($_POST['submit_edit'])){
    $current_date = new DateTime();
    $query = "UPDATE tasks SET
        title = '".$_POST['title']."',
        description = '".$_POST['description']."',
        modified_date = '".$current_date->format('Y-m-d')."',
        due_date = '".$_POST['due_date']."'
        WHERE id = ".$_POST['task_id']."
    LIMIT 1";
    $result = @mysqli_query($GLOBALS['mysql_con'], $query);


    $contacts = $_POST['task_persons'];
    $contact = explode(',', $contacts);
    if(!empty($contact) && gettype($contact) == 'array')  { 
        foreach($contact as $key => $contact_value){
            $query_select = "SELECT * FROM task_contact_link WHERE task_id = '".$_POST['task_id']."' AND main_contact_id = '".$contact_value."'";
            $result_select = @mysqli_query($GLOBALS['mysql_con'], $query_select);
            $row_select = @mysqli_fetch_array($result_select);
            if(!$row_select){
                send_mail($contact_value, $_POST['task_id']);
            }
        }
        $deleteLink = @mysqli_query($GLOBALS["mysql_con"], "DELETE FROM task_contact_link WHERE task_id = '".$_POST['task_id']."'");
        foreach($contact as $key => $contact_value){
            $query = "INSERT INTO task_contact_link
            (task_id, main_contact_id)
            VALUES (
                " . $_POST['task_id'] . ",
                '" . $contact_value . "'
            )";
            @mysqli_query($GLOBALS['mysql_con'], $query);
        }
    }
}

if(isset($_POST['submit_task'])){
    $modified_date = new DateTime();
    $insertquery = "INSERT INTO tasks
    (title, description, modified_date, modified_user, due_date, status, task_group_id)
    VALUES (
        '" . $_POST['title'] . "',
        '',
        '" . $modified_date->format('Y-m-d') . "',
        '" . $GLOBALS['main_contact']['id'] . "',
        '".$modified_date->format('Y-m-d')."',
        '0',
        '" . $task_group_id . "'
    )";
    @mysqli_query($GLOBALS['mysql_con'], $insertquery);
    $input_id = mysqli_insert_id($GLOBALS['mysql_con']);
    
    $contactquery = "INSERT INTO task_contact_link
    (task_id, main_contact_id)
    VALUES (
        " . $input_id . ",
        " . $GLOBALS['main_contact']['id'] . "
    )";
    @mysqli_query($GLOBALS['mysql_con'], $contactquery);
    $_POST = array();
}

if(isset($_POST['submit_list'])){
    $insertquery = "INSERT INTO task_group
    (description, main_contact_id)
    VALUES (
        '" . $_POST['list_description'] . "',
        '" . $GLOBALS['main_contact']['id'] . "'
    )";
    @mysqli_query($GLOBALS['mysql_con'], $insertquery);
    $_POST = array();
}

?>

<div class='tasks'>
    <div class="tasks_container">
        <div class='tasks_groups_wrapper'>
            <ul>
                <li data-id='0'><a href='?task_group_id=0'>Aufgaben <span class='number count_group_0'></span></a></li>
                <li data-id='-1'><a href='?task_group_id=-1/'>Mir zugewiesen <span class='number count_group_-1'></span></a></li>
                <?= get_task_groups($task_group_id, 'list'); ?>
            </ul>
            <p class='new_list'>+ Neue Liste erstellen</p>
            <form method='post' class='create_list' style='display: none'>
                <input class="add_task"type='text' required name='list_description' placeholder='Name der neuen Liste'>
                <input class="send_task" type='submit' name='submit_list' value='Liste hinzufügen'>
            </form>
        </div>
        <div class='tasks_wrapper'>
            <div class="mobile_menu_toggle">
                <svg xmlns="http://www.w3.org/2000/svg" width="30" height="21" viewBox="0 0 30 21">
                <g id="menu-left" transform="translate(-3 -7.5)">
                    <path id="Pfad_282" data-name="Pfad 282" d="M3,8.992A1.492,1.492,0,0,1,4.492,7.5H16.507a1.493,1.493,0,1,1,0,2.985H4.492A1.492,1.492,0,0,1,3,8.992Z"/>
                    <path id="Pfad_283" data-name="Pfad 283" d="M3,18a1.492,1.492,0,0,1,1.492-1.492H31.507a1.493,1.493,0,0,1,0,2.985H4.492A1.492,1.492,0,0,1,3,18Z"/>
                    <path id="Pfad_284" data-name="Pfad 284" d="M4.492,25.515a1.492,1.492,0,1,0,0,2.985H22.507a1.493,1.493,0,0,0,0-2.985Z"/>
                </g>
                </svg>
            </div>
            <h2 class='task_group_title'>Aufgaben</h2>
            <div class="tasks_list_overflow">
                <div class="task_item_list opened_tasks">
                </div>
                <p class="task_done_title">Erledigt <span class='count_tasks'></span></p>
                <div class="task_item_list done closed_tasks">
                </div>
            </div>
            <?php 
            if($task_group_id != -1){ ?>
            <form method='post' class='create_task'>
                <input class="add_task"type='text' required name='title' placeholder='Neue Aufgabe erstellen'>
                <input class="send_task" type='submit' name='submit_task' value='Aufgabe hinzufügen'>
            </form>
            <?php } ?>
        </div>
        <div class='tasks_content_wrapper'>

        </div>
    </div>
</div>
<script>

$('.task_item_list').on('click', '.task_item', function() {
    var task_id = $(this).attr('data-id');
    $('.task_item').removeClass('active_item');
    $('.tasks_content_wrapper').addClass("change_opacity");
    $(this).addClass('active_item');
    ajax_action(task_id, 'load_card', 0, true, ".tasks_content_wrapper ");
}); 
$('.task_item_list').on('click', '.task_item .complete_task', function() {
    var task_id = $(this).parent().attr('data-id');
    var complete = $(this).parent().attr('data-complete');
    ajax_action(task_id, 'complete_task', complete, false);
    $(this).addClass("animated_check");
    setTimeout(function() {
        ajax_action(<?= $task_group_id ?>, 'get_tasks', 0, true, ".opened_tasks");
        ajax_action(<?= $task_group_id ?>, 'get_tasks', 1, true, ".closed_tasks");
        ajax_action(<?= $task_group_id ?>, 'count_tasks', 1, true, ".count_tasks");
        ajax_action(<?= $task_group_id ?>, 'count_tasks', 0, true, ".count_group_<?= $task_group_id?>");
    }, 850);
}); 
$(".new_list").click(function() {
    $(".create_list").toggle();
}); 

$('.tasks_content_wrapper').on('click', 'button#back', function() {
    $(".tasks_content_wrapper").text("");
    $('.tasks_content_wrapper').removeClass("change_opacity");

}); 

$(".delete_group").click(function() {
    var group_id = $(this).attr('data-id');
    if (confirm("Sind Sie sicher, dass Sie diese Gruppe und alle beeinhalteten Tasks löschen möchten?")) {
        ajax_action(group_id, 'delete_group', 0, false);
        location.reload();
    }
}); 

$('.tasks_content_wrapper').on('click', '.delete_task', function() {
    var task_id = $(this).attr('data-id');
    ajax_action(task_id, 'delete_task', 0, false);
    location.reload();
}); 

$("p.task_done_title").click(function() {
    $(".done").children(".task_item").toggle();
}); 

$(".mobile_menu_toggle").click(function() {
    $(".tasks_groups_wrapper").toggle();
}); 

function ajax_action(task_id, action, status = 0, show, content_class = 0){
    $.ajax({
        type: 'POST',
        url: "/module/tasks/tasks_ajax.inc.php",
        data: { 
            task_id : task_id,
            action : action,
            status : status,
            main_contact_id : <?= $GLOBALS['main_contact']['id'] ?>,
        }, 
        success: function(data){
            if(show == true){
                $(content_class).html(data)
            }
        }
    });     
}

$(document).ready(function() {
    var urlParams = new URLSearchParams(window.location.search);
    var paramValue = 0;
    if (urlParams.has('task_group_id')) {
        paramValue = urlParams.get('task_group_id');
    }
    var targetLi = $('li[data-id="' + paramValue + '"]');
    var liText = targetLi.children().text();
    $(".task_group_title").text(liText);
    targetLi.addClass('active_list');
});

$(document).ready(function() {
    ajax_action(<?= $task_group_id ?>, 'get_tasks', 0, true, ".opened_tasks");
    ajax_action(<?= $task_group_id ?>, 'get_tasks', 1, true, ".closed_tasks");
    ajax_action(<?= $task_group_id ?>, 'count_tasks', 1, true, ".count_tasks");
    $(".tasks_groups_wrapper li").each(function(){
        var task_group_id = $(this).attr('data-id');
        ajax_action(task_group_id, 'count_tasks', 0, true, ".count_group_"+task_group_id);
    });
});
</script>