<?php 
include 'db_connect.php';
error_reporting(0);

//echo $id=$_SESSION['login_id']; 
?>
<div class="col-lg-12">
    <div class="card card-outline card-success">
        <div class="card-header">
            <div class="row">
                <div class="col-md-3">
                    <div class="form-group">
                        <label>From Date</label>
                        <input type="date" name="from_date" id="from_date" value="<?php if(isset($_GET['from_date'])){ echo $_GET['from_date']; } ?>" class="form-control">
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="form-group">
                        <label>To Date</label>
                        <input type="date" name="to_date" id="to_date" value="<?php if(isset($_GET['to_date'])){ echo $_GET['to_date']; } ?>" class="form-control">
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="form-group">
                        <label>Users<?php //echo "<pre>"; print_r($_SESSION['login_id']);?></label>
                        
                        <select name="user_id" id="user_id" class="form-control">
                             <option value="">Select users</option>
                            <?php 
                             $role_str = '';
                             if($_SESSION['login_type'] !='1')
                             {
                                 $role_str = "  AND manager_id='".$_SESSION['login_id']."'";
                             }
                            $qry_user = $conn->query("SELECT id, concat(firstname, ' ',lastname) as name  FROM `users` WHERE type!='1' $role_str");
                             if ($qry_user->num_rows > 0)
                             { 
                                while($row_users = $qry_user->fetch_assoc()) 
                                { ?>
                                   <option value="<?=$row_users['id']?>" <?php if(isset($_GET['user_id'])){ echo 'selected'; } ?>><?=$row_users['name']?></option>
                           <?php  }
                             }
                         
                            ?>
                            
                            
                        </select>
                    </div>
                </div>
                
                <div class="col-md-3">
                    <div class="form-group">
                        <label></label> <br>
                        <button type="button" id="filter_btn" class="btn btn-primary" style="margin-top:24px;">Filter Date</button>
                    </div>
                </div>
            </div>
            <div class="card-tools">
                <a class="btn btn-block btn-sm btn-default btn-flat border-primary" href="./index.php?page=new_task"><i class="fa fa-plus"></i> Add New taskt</a>
            </div>
        </div>
        <div class="card-body">
            <table class="table tabe-hover table-condensed" id="list">
                <colgroup>
                    <col width="5%">
                    <col width="15%">
                    <col width="20%">
                    <col width="15%">
                    <col width="15%">
                    <col width="10%">
                    <col width="10%">
                    <col width="10%">
                </colgroup>
                <thead>
                    <tr>
                        <th class="text-center">#</th>
                        <th>Task</th>
                        <!--<th>Project</th>-->
                        <th>Task date</th>
                        <th>Time taken</th>
                        <th>Total Time Taken</th>
                        <!--<th>Project Started</th>-->
                        <!--<th>Project Due Date</th>-->
                        <!--<th>Project Status</th>-->
                        <!--<th>Task Status</th>-->
                        <th>Action</th>
                    </tr>
                </thead>
                <tbody id="table_data">
                    <?php
                    $i = 1;
                    $where = "";
                    if($_SESSION['login_type'] == 2){
                        $where = " where p.manager_id = '{$_SESSION['login_id']}' ";
                    } elseif($_SESSION['login_type'] == 3){
                        $where = " where concat('[',REPLACE(p.user_ids,',','],['),']') LIKE '%[{$_SESSION['login_id']}]%' ";
                    }

                    $stat = array("Pending","Started","On-Progress","On-Hold","Over Due","Done");
                    $qry = $conn->query("SELECT t.*, p.name as pname, p.user_ids, p.status as pstatus, p.end_date, p.id as pid 
                                        FROM task_list t 
                                        INNER JOIN project_list p on p.user_ids = t.user_ids 
                                        $where 
                                        ORDER BY p.name ASC");

                    while($row= $qry->fetch_assoc()):
                        $trans = get_html_translation_table(HTML_ENTITIES,ENT_QUOTES);
                        unset($trans["\""], $trans["<"], $trans[">"], $trans["<h2"]);
                        $desc = strtr(html_entity_decode($row['description']),$trans);
                        $desc=str_replace(array("<li>","</li>"), array("",", "), $desc);
                        $tprog = $conn->query("SELECT * FROM task_list where project_id = {$row['pid']}")->num_rows;
                        $cprog = $conn->query("SELECT * FROM task_list where project_id = {$row['pid']} and status = 3")->num_rows;
                        $prog = $tprog > 0 ? ($cprog/$tprog) * 100 : 0;
                        $prog = $prog > 0 ?  number_format($prog,2) : $prog;
                        $prod = $conn->query("SELECT * FROM user_productivity where project_id = {$row['pid']}")->num_rows;
                        if($row['pstatus'] == 0 && strtotime(date('Y-m-d')) >= strtotime($row['start_date'])):
                            if($prod  > 0  || $cprog > 0)
                                $row['pstatus'] = 2;
                            else
                                $row['pstatus'] = 1;
                        elseif($row['pstatus'] == 0 && strtotime(date('Y-m-d')) > strtotime($row['end_date'])):
                            $row['pstatus'] = 4;
                        endif;
                        $tasks = unserialize($row['task']);
                        $time_taken_values = unserialize($row['time_taken']);
                        // Calculate total time taken
                        $total_seconds = 0;
                        foreach ($time_taken_values as $time_taken) {
                            list($hours, $minutes, $seconds) = explode(':', $time_taken);
                            $total_seconds += $hours * 3600 + $minutes * 60 + $seconds;
                        }
                        $total_hours = floor($total_seconds / 3600);
                        $total_minutes = floor(($total_seconds % 3600) / 60);
                        $total_seconds_remaining = $total_seconds % 60;
                        $total_time_taken = sprintf('%02d:%02d:%02d', $total_hours, $total_minutes, $total_seconds_remaining);
                    ?>
                    <tr>
                        <td class="text-center"><?php echo $i++ ?></td>
                        <td>
                            <?php foreach($tasks as $task): ?>
                                <p><b><?php echo $task ?></b></p>
                            <?php endforeach; ?>
                        </td>
                        <td>
                            <p><b><?php echo ucwords($row['start_date']) ?></b></p>
                        </td>
                         <td>
                            <?php foreach($time_taken_values as $time_taken): ?>
                                <p><b><?php echo $time_taken ?></b></p>
                            <?php endforeach; ?>
                        </td>
                        <td>
                            <p><b><?php echo $total_time_taken ?> Hrs</b></p>
                        </td>
                        <td class="text-center">
                            <button type="button" class="btn btn-default btn-sm btn-flat border-info wave-effect text-info dropdown-toggle" data-toggle="dropdown" aria-expanded="true">
                                Action
                            </button>
                            <div class="dropdown-menu" style="">
                                <a class="dropdown-item view_task" href="./index.php?page=view_task&id=<?php echo $row['id'] ?>" data-id="<?php echo $row['id'] ?>">View</a>
                                <div class="dropdown-divider"></div>
                                <?php if(isset($_SESSION['login_type']) && $_SESSION['login_type'] == 3): ?>
                                    <a class="dropdown-item" href="./index.php?page=edit_task&id=<?php echo $row['id'] ?>">Edit</a>
                                    <div class="dropdown-divider"></div>
                                    <a class="dropdown-item delete_task" href="javascript:void(0)" data-id="<?php echo $row['id'] ?>">Delete</a>
                                <?php endif; ?>
                            </div>
                        </td>
                    </tr>   
                    <?php endwhile; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>
<style>
    table p{
        margin: unset !important;
    }
    table td{
        vertical-align: middle !important
    }
</style>
<script>
    $(document).ready(function(){
        $('#list').dataTable();
        
        $('#filter_btn').click(function(){
            var from_date = $('#from_date').val();
            var to_date = $('#to_date').val();
            var user_id = $('#user_id').val();
            //alert(user_id);
            $.ajax({
                url: 'filter.php',
                method: 'POST',
                data: {'action':'filter_data','from_date':from_date,'to_date':to_date,'user_id':user_id},
                success: function(response){
                   // alert(response);
                    $('#table_data').html(response);
                }
            });
        });
    });
  $(document).ready(function(){
		$('#list').dataTable()
	
	$('.delete_task').click(function(){
	_conf("Are you sure to delete this Task?","delete_task",[$(this).attr('data-id')])
	})
	})
    function delete_task($id){
        start_load();
        $.ajax({
            url:'ajax.php?action=delete_task',
            method:'POST',
            data:{id:$id},
            success:function(resp){
                if(resp==1){
                    alert_toast("Data successfully deleted",'success');
                    setTimeout(function(){
                        location.reload();
                    },1500);
                }
            }
        });
    }
</script>
