<?php 
if(strpos($_SERVER['REQUEST_URI'], "/company/") !== false){
        if (session_status() === PHP_SESSION_NONE) {
            if (strpos($_SERVER['REQUEST_URI'], 'timesheet_new') !== false) {
                session_save_path($_SERVER['DOCUMENT_ROOT'].'/timesheet_new/sessions');
            } else {
                session_save_path($_SERVER['DOCUMENT_ROOT'].'/sessions');
            }
        
            ini_set('session.gc_probability', 1);
            session_start();
        }
    
        
        if(isset($_SERVER['HTTPS'])){
            $protocol = ($_SERVER['HTTPS'] && $_SERVER['HTTPS'] != "off") ? "https" : "http";
        }else{
            $protocol = 'http';
        }

        $site_url = $protocol . "://" . $_SERVER['HTTP_HOST']."/";
        if(!isset($_SESSION['loggedin_user'])){
            header("location:".$site_url."login.php");
        } 
        
        
        $_SERVER['REQUEST_URI'] = strtok($_SERVER['REQUEST_URI'], '?');
        $req_url = explode('/', $_SERVER['REQUEST_URI']);
        //print_r($req_url);
        if(isset($req_url[3]) && !empty($req_url[3])){
            unset($req_url[1]); unset($req_url[2]);
             include($_SERVER['DOCUMENT_ROOT'].implode('/',$req_url));
             die();
            
        }
        
       
    }

    include("header.php");
    function timeToSeconds($time)
    {
        $timeArr = array_reverse(explode(":", $time));
        $seconds = 0;
        foreach ($timeArr as $key => $value)
        {
            if ($key > 2) break;
            $seconds += pow(60, $key) * $value;
        }
        
        return $seconds;
    } 
    function format_time($t,$f=':') // t = seconds, f = separator 
    {
        $hours_arr = array();

        array_push($hours_arr, floor($t/3600));
        array_push($hours_arr, (($t/60)%60));
        //array_push($hours_arr, ($t%60).'s');
        return implode($f,$hours_arr);

    }
    if($emp_list['type'] == 'admin'){
        $q = mysqli_query($conn,"SELECT project_id, SUM( TIME_TO_SEC( total_time ) ) AS timeSum from db_timelog GROUP BY project_id ORDER BY timeSum DESC LIMIT 3");
    
        $re = mysqli_fetch_all($q);

        $q_t = mysqli_query($conn,"SELECT * from db_tasks ORDER BY id DESC LIMIT 5");
       // $re_t = mysqli_fetch_all($q_t);c

    } elseif ($emp_list['type'] == 'manager') { 
        $all_projects = mysqli_query($conn, "SELECT * FROM db_projects WHERE manager_id=".$_SESSION['loggedin_user']);
        $my_projects = array();
        while($row = mysqli_fetch_array($all_projects)){
            array_push($my_projects, $row['id']);
        }
        $q = mysqli_query($conn,"SELECT project_id, SUM( TIME_TO_SEC( total_time ) ) AS timeSum from db_timelog WHERE project_id in(".implode(',',$my_projects).") GROUP BY project_id ORDER BY timeSum DESC LIMIT 3");
        $re = mysqli_fetch_all($q);

        $q_t = mysqli_query($conn,"SELECT * from db_tasks where project_id in(".implode(',',$my_projects).") ORDER BY id DESC LIMIT 5");
        //$re_t = mysqli_fetch_all($q_t);
    } elseif($emp_list['type'] == 'company'){
        $all_users = mysqli_fetch_assoc(mysqli_query($conn, "SELECT GROUP_CONCAT(id SEPARATOR ',') AS ids FROM db_users WHERE type = 'manager' and company_name=".$_SESSION['loggedin_user']));

        $all_projects = mysqli_query($conn, "SELECT * FROM db_projects WHERE manager_id in (".$all_users['ids'].") or user_id=".$_SESSION['loggedin_user']);
        $my_projects = array();
        while($row = mysqli_fetch_array($all_projects)){
            array_push($my_projects, $row['id']);
        }
        $q = mysqli_query($conn,"SELECT project_id, SUM( TIME_TO_SEC( total_time ) ) AS timeSum from db_timelog WHERE project_id in(".implode(',',$my_projects).") GROUP BY project_id ORDER BY timeSum DESC LIMIT 3");
        $re = mysqli_fetch_all($q);

        $q_t = mysqli_query($conn,"SELECT * from db_tasks where project_id in(".implode(',',$my_projects).") ORDER BY id DESC LIMIT 5");

    } else {
        $q = mysqli_query($conn,"SELECT project_id, SUM( TIME_TO_SEC( total_time ) ) AS timeSum from db_timelog WHERE user_id=".$_SESSION['loggedin_user']." GROUP BY project_id ORDER BY timeSum DESC LIMIT 3");

        $re = mysqli_fetch_all($q);

        $q_t = mysqli_query($conn,"SELECT * from db_tasks where user_id=".$_SESSION['loggedin_user']." or emplyee_id REGEXP '.*[0-9]+;s:[0-9]+:\"".$_SESSION['loggedin_user']."\".*' ORDER BY id DESC LIMIT 5");
        //$re_t = mysqli_fetch_all($q_t);

    }
   
?>
 <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
 <script>
    function convert_to_time_format(pass_val) {
        var sec_num = parseInt(pass_val, 10); // don't forget the second param
        var hours   = Math.floor(sec_num / 3600);
        var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
        var seconds = sec_num - (hours * 3600) - (minutes * 60);

        if (hours   < 10) {hours   = "0"+hours;}
        if (minutes < 10) {minutes = "0"+minutes;}
        if (seconds < 10) {seconds = "0"+seconds;}
        return hours + ':' + minutes + ':' + seconds;
    }
   
var exp_date = new Date(Date.now() + 86400e3).toUTCString();
var time_zone = Intl.DateTimeFormat().resolvedOptions().timeZone;
document.cookie = "user_timezone="+time_zone+"; expires=" + exp_date;
</script>

            <!-- Body: Body -->
            <div class="body d-flex py-3">
                <div class="container-xxl">
                    
                 
                    <div class="row g-3 mb-3 row-deck">
                        <div class="col-xl-6">
                            <div class="card">
                                <div class="card-header d-flex justify-content-between align-items-center bg-transparent border-bottom-0 py-3">
                                    <h6 class="m-0 fw-bold">Top projects</h6>
                                    <div class="report ms-3">
                                        <a href="<? $site_url; ?>/dist/all_reports.php" class="text-secondary underline">Project Report</a>
                                    </div>
                                </div>
                                <div class="card-body">
                                    <div class="row g-3 row-cols-1 row-cols-sm-3 row-cols-md-3 row-cols-lg-3">
                                        <?php 
                                            if(empty($re)){
                                                echo '<p>No project to show here.</p>';
                                            } else {
                                                $color_arr = array('rgb(255, 99, 132)',
                                                    'rgb(54, 162, 235)',
                                                    'rgb(255, 205, 86)'
                                                  ); 
                                                foreach($re as $k => $single_re){
                                               
                                                    $get_project_name = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM db_projects WHERE id=".$single_re[0]));

                                                    
                                                    if(empty($get_project_name['name'])){
                                                        continue;
                                                    }
                                                    echo '<div class="col col_p"><canvas id="myChart_'.$k.'"></canvas></div>';
                                                    echo '<script>
                                                            window.addEventListener("DOMContentLoaded", function() { 
                                                                const ctx_'.$k.' = document.getElementById("myChart_'.$k.'");
                                                                console.log(ctx_'.$k.');
                                                                chart_obj_'.$k.' = new Chart(ctx_'.$k.', {
                                                                    type: "doughnut",
                                                                   
                                                                    data: {
                                                                      labels: ["'.$get_project_name['name'].'"], 
                                                                      datasets: [{
                                                                        label: "Hours",
                                                                        data: ["'.timeToSeconds($single_re[1]).'"],
                                                                        backgroundColor: ["'.$color_arr[$k].'"
                                                                          ],
                                                                        hoverOffset: 4
                                                                      }]
                                                                    },
                                                                    options: {
                                                                        plugins: {
                                                                        tooltip: {
                                                                            callbacks: {
                                                                                label: function(context) {
                                                                                    console.log(context);
                                                                                    let label = context.dataset.label || "";
                                                                                    if (context.parsed !== null) {
                                                                                        label += " : "+convert_to_time_format(context.parsed);
                                                                                    }
                                                                                    
                                                                                    return label;
                                                                                }
                                                                            }
                                                                        }
                                                                       }
                                                                    }
                                                            
                                                                    /*options: {
                                                                      scales: {
                                                                        y: {
                                                                          beginAtZero: true
                                                                        }
                                                                      }
                                                                    }*/
                                                                  });
                                                                    /*var options = {
                                                                                chart: {
                                                                                    height: 180,
                                                                                    type: "radialBar",
                                                                                },
                                                                                colors: ["var(--chart-color1)"],
                                                                                plotOptions: {
                                                                                    radialBar: {
                                                                                        hollow: {
                                                                                            size: "70%",
                                                                                        }
                                                                                    },
                                                                                },
                                                                                series: [0],
                                                                                labels: [""],
                                                                            }
                                                                            if(document.querySelector("#apex-circle-chart-'.$k.'") != null){
                                                                                var chart = new ApexCharts(
                                                                                    document.querySelector("#apex-circle-chart-'.$k.'"),
                                                                                    options
                                                                                );
                                                                                chart.render();
                                                                            }*/
                                                                            
                                                            });

                                                        </script>';
                                                }

                                         } ?>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="col-xl-6">
                            <div class="card">
                                <div class="card-header d-flex justify-content-between align-items-center bg-transparent border-bottom-0 py-3">
                                    <h6 class="m-0 fw-bold">Latest tasks</h6>
                                    <div class="report ms-3">
                                        <a href="<? $site_url; ?>/dist/all_reports.php" class="text-secondary underline">Task Report</a>
                                    </div>
                                </div>
                                <div class="card-body">

                                    <?php 
                                        $task_bg = array(
                                                'light-info-bg',
                                                'bg-lightgreen',
                                                'bg-lightyellow',
                                                'light-success-bg',
                                                'light-orange-bg',
                                                'bg-careys-pink',
                                                'bg-lightblue'
                                            );
                                        
                                        if($q_t->num_rows == 0){
                                            echo 'No task to show here.';
                                        } else {

                                            while($single_t = mysqli_fetch_array($q_t)):
                                                
                                                $fetch_cat = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM db_tasks_cat WHERE cat_id=".$single_t['cat_id']));
                                                $code_key = $fetch_cat['cat_color']-1;
                                                $color_code = $task_bg[$code_key];

                                            echo '<div class="site-block-list d-flex align-items-center flex-wrap justify-content-sm-between mb-3">
                                                    <div class="site-list w-25 mb-2 mb-sm-0">
                                                        '.$single_t['name'].'
                                                    </div>
                                                    <div class="site-time">
                                                        <span class="'.$color_code.' px-3 py-1 d-inline rounded">'.$fetch_cat['cat_name'].'</span>
                                                    </div>
                                                </div>';
                                            endwhile;
                                        }

                                        
                                    ?>
                                    
                                    
                                </div>
                            </div>
                        </div>
                        
                    </div>      
                </div>
            </div>    
        
<?php 
    include("footer.php"); 
?>

<style type="text/css">
    div.top-chart{
        position: relative;
    }
    .col_p{
        position: relative;
    }
   /* div.top-chart p {*/
    p.out_side_p{
        position: absolute;
        max-width: 86px;
        text-align: center;
        left: 0;
        right: 0;
        margin: auto;
        top: 50%;
        transform: translateY(-56%);
        line-height: 18px;
        font-weight: 600;
    }
    div.apexcharts-canvas svg text {
    display: none;
}
</style>
<!-- <script src="../js/page/dashboard.js"></script> -->


