<?php
$must_login                 = true ;
$require_path               = '../../../' ;
$require_sub                = '../../' ;
require( $require_sub.'header.php' ) ;
require( $require_path.'languages/'.$array['lang'].'.php' ) ;

$html                       = '' ;

if ( $boolean_login ){
    $status                 = '201' ;

    $search_year            = ( $array['search_year'] != '' ? $array['search_year'] : date('Y') ) ;
    $search_type            = ( $array['search_type'] != '' ? $array['search_type'] : 'personal' ) ;

    $staff_settings         = $staff_info['staff_settings'] ;

    // select all month
    $months                 = [] ;
    $months_name            = [ $lang['Jan'], $lang['Feb'], $lang['Mar'], $lang['Apr'], $lang['May'], $lang['Jun'], $lang['Jul'], $lang['Aug'], $lang['Sep'], $lang['Oct'], $lang['Nov'], $lang['Dec'] ] ;
    for ( $a = 1 ; $a <= 12 ; $a++ ){ $months[$a] = 0 ; }

    // select all department
    $departments            = [ '0' => $months ] ;
    $departments_name       = [ '0' => [ 'desc' => $lang['Cross Department'], 'colour' => '#EB5406' ] ] ;
    $select_departments     = $mysqli->query( "SELECT a.department_id, a.department_colour, b.department_desc FROM setting_department a
                                           LEFT JOIN setting_department_translation b ON ( a.department_id = b.department_id )
                                           WHERE a.deleted_at IS NULL AND b.lang = '".$array['lang']."'" ) ;
    if ( $select_departments->num_rows > 0 ){
        while ( $row_departments = $select_departments->fetch_assoc() ){
            $departments[$row_departments['department_id']] = $months ;
            $departments_name[$row_departments['department_id']] = [
                'desc'   => dataFilter( $row_departments['department_desc'] ),
                'colour' => $row_departments['department_colour']
            ] ;
        }
    }

    // monthly report = by personal or whole branch
    $array_report           = [
        'personal'           => [
            // 'late'           => [
            //     'name'       => $lang['On Time Or Delayed Report'],
            //     'subname'    => $months_name,
            //     'sub'        => [
            //         'no'     => [ 'name' => $lang['On Time'],       'lists' => $months ],
            //         'yes'    => [ 'name' => $lang['Delayed'],       'lists' => $months ]
            //     ]
            // ],
            'complete'       => [
                'name'       => $lang['Completed Or Incompleted Report'],
                'subname'    => $months_name,
                'sub'        => [
                    'yes'    => [ 'name' => $lang['Completed'],     'lists' => $months ],
                    'no'     => [ 'name' => $lang['Incompleted'],   'lists' => $months ],
                    'cancel' => [ 'name' => $lang['Cancelled'],     'lists' => $months ]
                ]
            ],
            'department'     => [
                'name'       => $lang['Department Task Given Report'],
                'subname'    => $months_name,
                'sub'        => $departments
            ]
        ]
    ] ;
    if ( $staff_settings['reporttaskbranch'] == 'yes' ){
        $array_report['branch'] = [
            // 'late'           => [
            //     'name'       => $lang['On Time Or Delayed Report'],
            //     'subname'    => $months_name,
            //     'sub'        => [
            //         'no'     => [ 'name' => $lang['On Time'],       'lists' => $months ],
            //         'yes'    => [ 'name' => $lang['Delayed'],       'lists' => $months ]
            //     ]
            // ],
            'complete'       => [
                'name'       => $lang['Completed Or Incompleted Report'],
                'subname'    => $months_name,
                'sub'        => [
                    'yes'    => [ 'name' => $lang['Completed'],     'lists' => $months ],
                    'no'     => [ 'name' => $lang['Incompleted'],   'lists' => $months ],
                    'cancel' => [ 'name' => $lang['Cancelled'],     'lists' => $months ]
                ]
            ],
            'department'     => [
                'name'       => $lang['Department Task Given Report'],
                'subname'    => $months_name,
                'sub'        => $departments
            ]
        ] ;
    }

    $filtertype             = [] ;
    foreach ( $array_report as $k => $v ){
        if ( $k == $search_type ){
            $filtertype[]   = $k ;
        }
    }

    foreach ( $filtertype as $k => $v ){

        $search_query         =  " AND ( a.created_branch_id = '".$array['branch_id']."' XXXXXX )" ;
        switch ( $v ){
            case 'personal' :
                $search_query = str_replace( 'XXXXXX', " AND a.created_by = '".$staff_info['staff_id']."' OR a.assigned_by = '".$staff_info['staff_id']."' OR EXISTS ( SELECT b.staff_id FROM task_joinstaff b WHERE a.task_id = b.task_id AND b.staff_id = '".$staff_info['staff_id']."' LIMIT 1 )", $search_query ) ;
            break ;
            case 'branch'   :
                $search_query = str_replace( 'XXXXXX', '', $search_query ) ;
            break ;
        }




        // late report
        // $select_task     = $mysqli->query( "SELECT COUNT(a.is_late) as total, a.is_late, MONTH(a.confirmed_at) as month FROM task a
        //                                     WHERE a.deleted_at IS NULL AND a.status = 'approved' AND a.confirmed_at LIKE '%".$search_year."%' ".$search_query."
        //                                     GROUP BY a.is_late, MONTH(a.confirmed_at)" ) ;
        // if ( $select_task->num_rows > 0 ){
        //     while ( $row_task = $select_task->fetch_assoc() ){
        //         $array_report[$v]['late']['sub'][$row_task['is_late']]['lists'][$row_task['month']] = $row_task['total'] ;
        //     }
        // }




        // complete report
        $select_task     = $mysqli->query( "SELECT COUNT(a.status) as total, MONTH(a.created_at) as month FROM task a
                                            WHERE a.deleted_at IS NULL AND a.status IN ( 'approved' ) AND a.created_at LIKE '%".$search_year."%' ".$search_query."
                                            GROUP BY MONTH(a.created_at)" ) ;
        if ( $select_task->num_rows > 0 ){
            while ( $row_task = $select_task->fetch_assoc() ){
                $array_report[$v]['complete']['sub']['yes']['lists'][$row_task['month']] = $row_task['total'] ;
            }
        }


        // incomplete report
        $select_task     = $mysqli->query( "SELECT COUNT(a.status) as total, MONTH(a.created_at) as month FROM task a
                                            WHERE a.deleted_at IS NULL AND a.status IN ( 'pending','assigned','resubmit','progress','completed','confirmed' ) AND a.created_at LIKE '%".$search_year."%' ".$search_query."
                                            GROUP BY MONTH(a.created_at)" ) ;
        if ( $select_task->num_rows > 0 ){
            while ( $row_task = $select_task->fetch_assoc() ){
                $array_report[$v]['complete']['sub']['no']['lists'][$row_task['month']] = $row_task['total'] ;
            }
        }


        // cancel report
        $select_task     = $mysqli->query( "SELECT COUNT(a.status) as total, MONTH(a.created_at) as month FROM task a
                                            WHERE a.deleted_at IS NULL AND a.status IN ( 'rejected', 'cancelled' ) AND a.created_at LIKE '%".$search_year."%' ".$search_query."
                                            GROUP BY MONTH(a.created_at)" ) ;
        if ( $select_task->num_rows > 0 ){
            while ( $row_task = $select_task->fetch_assoc() ){
                $array_report[$v]['complete']['sub']['cancel']['lists'][$row_task['month']] = $row_task['total'] ;
            }
        }






        // department complete report
        $select_task     = $mysqli->query( "SELECT COUNT(a.department_id) as total, a.department_id, MONTH(a.confirmed_at) as month FROM task a
                                            WHERE a.deleted_at IS NULL AND a.status IN ( 'approved' ) AND a.confirmed_at LIKE '%".$search_year."%' ".$search_query."
                                            GROUP BY a.department_id, MONTH(a.confirmed_at)" ) ;
        if ( $select_task->num_rows > 0 ){
            while ( $row_task = $select_task->fetch_assoc() ){
                $array_report[$v]['department']['sub'][$row_task['department_id']][$row_task['month']] = $row_task['total'] ;
            }
        }
    }


    // direct echo
    if ( $array['iswebview'] == 'yes' ){

        $html         .= '
        <!DOCTYPE html>
        <html lang="en">
            <head>
                <meta http-equiv="content-type" content="text/html;charset=UTF-8" />
                <meta http-equiv="X-UA-Compatible" content="IE=edge" />
                <meta name="viewport" content="width=device-width, initial-scale=1" />
                <link rel="stylesheet" href="'.PATH.'css/bootstrap.css?v='.filemtime($require_path.'css/bootstrap.css').'" />
                <script src="'.PATH.'scripts/chart.js"></script>
            </head>
            <body>
                <div class="report_chart_main">

                    <div class="report_chart_filter_year">
                        <a href="?search_year='.( $search_year - 1 ).resetGetParams($array, [ 'search_year' ]).'" class="report_chart_filter_year_button">
                            <i class="fa fa-chevron-left" aria-hidden="true"></i>
                        </a>
                        <span class="report_chart_filter_year_span">'. $search_year .'</span>
                        <a href="?search_year='.( $search_year + 1 ).resetGetParams($array, [ 'search_year' ]).'" class="report_chart_filter_year_button">
                            <i class="fa fa-chevron-right" aria-hidden="true"></i>
                        </a>
                    </div>' ;

                    if ( count($array_report) > 1 ){
                        $html .= '
                        <div class="report_chart_filter_type">
                            <a href="?search_type=personal'.resetGetParams($array, [ 'search_type' ]).'" class="report_chart_filter_type_button '.( $search_type == 'personal' ? 'active' : '' ).'">
                                '.$lang['By Personal'].'
                            </a>
                            <a href="?search_type=branch'.resetGetParams($array, [ 'search_type' ]).'" class="report_chart_filter_type_button '.( $search_type == 'branch' ? 'active' : '' ).'">
                                '.$lang['By Branch'].'
                            </a>
                        </div>' ;
                    }

                    foreach ( $array_report as $kreport => $vreport ){

                        if ( $kreport == $search_type ){

                            foreach ( $vreport as $ktype => $vtype ){

                                $title      = $vtype['name'] ;
                                $titlename  = $title.' ( '.$lang['Year'].' '.$search_year.' )' ;

                                $idname     = 'myChart_'.$kreport.'_'.$ktype ;
                                $ctxname    = 'ctx_'.$idname ;
                                $configname = 'config_'.$idname ;

                                $datasets   = [] ;

                                switch ( $ktype ){

                                    case 'late'       :
                                    case 'complete'   :

                                        $count_color    = 0 ;
                                        foreach ( $vtype['sub'] as $ksub => $vsub ){
                                            $temp       = [] ;
                                            foreach ( $vsub['lists'] as $klist => $vlist ){
                                                $temp[] = "$vlist" ;
                                            }

                                            $datasets[] = [
                                                'label'           => $vsub['name'],
                                                'data'            => $temp,
                                                'backgroundColor' => $colors[$count_color]
                                            ] ;

                                            $count_color++ ;
                                        }

                                        $html .= '
                                        <div class="report_chart_line">
                                            <canvas id="'.$idname.'"></canvas>
                                        </div>
                                        <script>
                                            const '.$ctxname.'    = document.getElementById("'.$idname.'") ;
                                            const '.$configname.' = {
                                                type : "line",
                                                data : {
                                                    datasets : '.json_encode($datasets).',
                                                    labels   : [ "'.implode( '", "', $vtype['subname'] ).'" ]
                                                },
                                                options: {
                                                    responsive          : true,
                                                    maintainAspectRatio : false,
                                                    plugins             : {
                                                        legend          : {
                                                            position    : "top",
                                                        },
                                                        title           : {
                                                            display     : true,
                                                            text        : "'.$titlename.'"
                                                        }
                                                    }
                                                }
                                            } ;
                                            new Chart( '.$ctxname.', '.$configname.' ) ;
                                        </script>' ;

                                    break ;

                                    case 'department' :

                                        $count_color    = 0 ;
                                        foreach ( $departments_name as $kdepartment => $vdepartment ){
                                            $temp       = [] ;
                                            foreach ( $vtype['sub'][$kdepartment] as $klist => $vlist ){
                                                $temp[] = "$vlist" ;
                                            }

                                            $datasets[] = [
                                                'label'           => $vdepartment['desc'],
                                                'data'            => $temp,
                                                'backgroundColor' => $vdepartment['colour']
                                            ] ;

                                            $count_color++ ;
                                        }

                                        $html .= '
                                        <div class="report_chart_bar">
                                            <canvas id="'.$idname.'"></canvas>
                                        </div>
                                        <script>
                                            const '.$ctxname.'    = document.getElementById("'.$idname.'") ;
                                            const '.$configname.' = {
                                                type : "bar",
                                                data : {
                                                    datasets : '.json_encode($datasets).',
                                                    labels   : [ "'.implode( '", "', $vtype['subname'] ).'" ]
                                                },
                                                options: {
                                                    responsive          : true,
                                                    maintainAspectRatio : false,
                                                    elements : {
                                                        bar  : {
                                                            borderWidth : 2
                                                        }
                                                    },
                                                    indexAxis           : "y",
                                                    plugins             : {
                                                        legend          : {
                                                            position    : "top"
                                                        },
                                                        title           : {
                                                            display     : true,
                                                            text        : "'.$titlename.'"
                                                        }
                                                    }
                                                }
                                            } ;
                                            new Chart( '.$ctxname.', '.$configname.' ) ;
                                        </script>' ;

                                    break ;

                                }

                            }
                            
                        }
                    }

                $html .= '
                </div>
            </body>
        </html>' ;
    }

}




if ( $array['iswebview'] == 'yes' ){
    echo $html ;
    exit ;
}

require( $require_sub.'footer.php' ) ;
?>