<?php

function mergeSpecialAddOnDeduction($arr1, $arr2, $sumTitles = []) {
    foreach ($arr2 as $item2) {
        $found = false;

        if (isset($item2['title'])) {
            foreach ($arr1 as $i => $item1) {
                if (isset($item1['title']) && $item1['title'] === $item2['title']) {
                    $found = true;

                    // ✅ If title is in sumTitles → sum recursively
                    if (in_array($item1['title'], $sumTitles)) {
                        $arr1[$i] = mergeAndSum($item1, $item2);
                    } 
                    // ✅ If title not in sumTitles → replace
                    else {
                        $arr1[$i] = $item2;
                    }
                    break;
                }
            }
        }

        // ✅ If not found at all → append as new entry
        if (!$found) {
            $arr1[] = $item2;
        }
    }

    return $arr1;
}

function mergeAndSum($array1, $array2) {
    foreach ($array2 as $key => $value) {
        // If key doesn't exist, copy it directly
        if (!isset($array1[$key])) {
            $array1[$key] = $value;
        } 
        // special keys sum
        else if(in_array($key, ['add_on', 'deduction'])){
            $sumTitles = ['ESIC Employer Share @ 3.25% of (A)', 'ESIC Employee Share @ 0.75% of (A)', ];
            $array1[$key] = mergeSpecialAddOnDeduction($array1[$key], $value, $sumTitles);
        }
        // If both are arrays, merge recursively
        elseif (is_array($array1[$key]) && is_array($value)) {
            // If numeric array (like fixed_pay, add_on)
            // if (array_is_list($value)) {
            if (array_keys($value) === range(0, count($value) - 1)) {
                foreach ($value as $index => $item) {
                    if (isset($array1[$key][$index])) {
                        $array1[$key][$index] = mergeAndSum($array1[$key][$index], $item);
                    } else {
                        $array1[$key][$index] = $item;
                    }
                }
            } else {
                $array1[$key] = mergeAndSum($array1[$key], $value);
            }
        } 
        // If both numeric, sum them
        elseif (is_numeric($array1[$key]) && is_numeric($value)) {
            $array1[$key] = (float)$array1[$key] +  (float)$value;
        }
        // Otherwise, replace
        else {
            $array1[$key] = $value;
        }
    }
    return $array1;
}

function salaryCode($user, $firstDayLast, $lastDayLast){

    $join_month = date("Y-m", strtotime($user['joining_date']));
    $wsDate = date("Y-m", strtotime($user['working_status_date']));
    if (!empty($user['joining_date']) && ($join_month == date("Y-m", strtotime($firstDayLast)))) {
        $firstDayLast = date("Y-m-d", strtotime($user['joining_date']));
    } else {
        $firstDayLast = $user['firstDayLast'];
    }
    if (!empty($user['working_status_date']) && ($wsDate == date("Y-m", strtotime($firstDayLast)))) {
        $lastDayLast = date("Y-m-d", strtotime($user['working_status_date']));
    } else {
        $lastDayLast = $user['lastDayLast'];
    }


    // require_once "salaryCodeCalculate.php";
    // in salary.php
    // in fun/exportSalary.php
    // in fun/function.php
    // in fun/storeSalaryForYear.php
    // in pay_slip/payslip.php

    // $finalLeaveOffer = 1.5;
    $finalSalaryArray = array();
    $array = array();

    $firstMonthOne = date("Y-m", strtotime($firstDayLast));
    $firstMonthTwo = date("Y-m", strtotime($lastDayLast));
    $firstMonthOneYear = date("Y-01", strtotime("$firstDayLast -1 year"));
    $firstMonthTwoYear = date("Y-12", strtotime("$lastDayLast +1 year"));
    // #####################################
    $employeeSalary = mysqli_query($GLOBALS['db'], "SELECT * FROM employee_salary 
    WHERE employee_id='$user[employee_id]' AND
    '$firstMonthOne'>=
    (CASE
        WHEN (revision_start_date is null or revision_start_date='') THEN '$firstMonthOneYear' 
        ELSE DATE_FORMAT(revision_start_date, '%Y-%m')
    END) 
    AND 
    '$firstMonthOne'<=
    (CASE
        WHEN (revision_end_date is null or revision_end_date='') THEN '$firstMonthTwoYear' 
        ELSE  DATE_FORMAT(DATE_SUB(revision_end_date, INTERVAL 1 DAY), '%Y-%m')
    END)");
    // echo "SELECT * FROM employee_salary 
    // WHERE employee_id='$user[employee_id]' AND
    // '$firstMonthOne'>=
    // (CASE
    //     WHEN (revision_start_date is null or revision_start_date='') THEN '$firstMonthOneYear' 
    //     ELSE DATE_FORMAT(revision_start_date, '%Y-%m')
    // END) 
    // AND 
    // '$firstMonthOne'<=
    // (CASE
    //     WHEN (revision_end_date is null or revision_end_date='') THEN '$firstMonthTwoYear' 
    //     ELSE  DATE_FORMAT(DATE_SUB(revision_end_date, INTERVAL 1 DAY), '%Y-%m')
    // END)";

    // #####################################
    $finalSalaryArray = [];
    if (mysqli_num_rows($employeeSalary) > 1) {

        while ($salary = mysqli_fetch_assoc($employeeSalary)) {
            $finalSalaryArray = $salary;

            if (empty($salary['revision_start_date']) || $salary['revision_start_date'] < $firstDayLast) {
                $salaryFirstDayLast = $firstDayLast;
            } else {
                $salaryFirstDayLast = $salary['revision_start_date'];
            }
            if (empty($salary['revision_end_date']) || $salary['revision_end_date'] > $lastDayLast) {
                $salaryLastDayLast = $lastDayLast;
            } else {
                $salaryLastDayLast = date("Y-m-d", strtotime("$salary[revision_end_date] -1 day"));
            }

            $newArray = calculateSalary($salary, $user, $salaryFirstDayLast, $salaryLastDayLast);

            // echo "<script>console.log(JSON.stringify(".json_encode($newArray)."));</script>";
            // ############################
            if (empty($array)) {
                $array = $newArray;
            } else {
                $array = mergeAndSum($array, $newArray);
            }
            // ############################
        }
    } else {
        $finalSalaryArray = mysqli_fetch_assoc($employeeSalary);
        $array =  calculateSalary($finalSalaryArray, $user, $firstDayLast, $lastDayLast);
    }
    // echo "<script>console.log(".json_encode($array).");</script>";

    $monthDay = date("t", strtotime($firstDayLast));

    // $leaveOffer = 1.5;
    // $l = $array['l'];
    // $hd = $array['hd'];
    // $p = $array['p'];
    // $wo = $array['wo'];
    // $ho = $array['ho'];
    // $wfh = $array['wfh'];
    // $totalLeave = $array['totalLeave'];
    // $totalWorkingDay = $array['totalWorkingDay'];

    // if ($monthDay == $array['month_day']) {
    //     $basic_salary = $array['basic_salary'];
    //     $hra = $array['hra'];
    //     $books_per = $array['books_per'];
    //     $sp_allowance = $array['sp_allowance'];
    //     $comp_epf = $array['comp_epf'];
    // } else {
    //     $basic_salary = $finalSalaryArray['basic_salary'] / 12;
    //     $hra = $finalSalaryArray['hra'] / 12;
    //     $books_per = $finalSalaryArray['books_per'] / 12;
    //     $sp_allowance = $finalSalaryArray['special_allowance'] / 12;
    //     $comp_epf = $finalSalaryArray['company_epf'] / 12;
    //     $monthDay = $array['month_day'];
    //     // echo "<script>console.log(" . json_encode($finalSalaryArray) . ", '$user[employee_id]');</script>";
    // }

    // $working_basic_salary = $array['working_basic_salary'];
    // $working_hra = $array['working_hra'];
    // $working_books_per = $array['working_books_per'];
    // $working_sp_allowance = $array['working_sp_allowance'];

    // // deduction side
    // $working_tds = (!empty($finalSalaryArray['tds'])) ? ($finalSalaryArray['tds'] / 12) : 0;
    // $working_company_epf = 0;
    // $working_employee_epf = 0;
    // if ($finalSalaryArray['epf_status'] == 'Yes' && $finalSalaryArray['company_epf'] != 0) {
    //     $working_employee_epf = ceil((min($basic_salary, 15000)) * 12 / 100);
    //     $working_company_epf = $working_employee_epf;
    // } else if ($finalSalaryArray['epf_status'] == 'Yes' && $finalSalaryArray['company_epf'] == '0') {
    //     $working_employee_epf = ceil((min($basic_salary, 15000)) * 12 / 100);
    // } else {
    // }

    // $working_company_esi = 0;
    // $working_employee_esi = 0;
    // if ($finalSalaryArray['esi_status'] == 'Yes') {
    //     $forEsi = $working_basic_salary + $working_hra + $working_books_per + $working_sp_allowance;
    //     $working_company_esi = ceil($forEsi * 3.25 / 100);
    //     $working_employee_esi = ceil($forEsi * 0.75 / 100);
    // }

    // // working days salary
    // $working_salary = array($working_basic_salary, $working_hra, $working_books_per, $working_sp_allowance, $working_company_epf);
    // $working_day_salary = 0;
    // foreach ($working_salary as $s) {
    //     $working_day_salary += $s;
    // }

    // $deduction = round($working_tds + $working_employee_epf + $working_company_epf + $working_employee_esi);
    // // $deduction = round($working_tds + $working_employee_epf + $working_company_epf);
    // $monthlySalary = round($basic_salary + $hra + $books_per + $sp_allowance + $comp_epf);
    // $payableSalary = round($working_day_salary - $deduction);

    // $monthSalaryDetails = array('basic_salary' => $basic_salary, 'hra' => $hra, 'books_per' => $books_per, 'special_allowance' => $sp_allowance, 'company_epf' => $comp_epf, 'ctc' => $monthlySalary);

    // ###############################################################################
    $bi_date =  date("Y-m", strtotime($firstDayLast));
    $bonusIncentive = mysqli_fetch_assoc(mysqli_query($GLOBALS['db'], "select sum(bonus) as bonus, sum(incentive) as incentive from employee_bonusIncentive where employee_id='$user[employee_id]' and date='$bi_date' "));

    $bonus = (!empty($bonusIncentive['bonus'])) ? $bonusIncentive['bonus'] : 0;
    $incentive = (!empty($bonusIncentive['incentive'])) ? $bonusIncentive['incentive'] : 0;
    // ###############################################################################

    // echo "$user[name]<br> leave=$l<br> holiday=$hd<br> present=$p<br> weekoff=$wo<br> holiday=$ho<br> workfromhome=$wfh<br> monthday=$monthDay<br> leaveoffer=$leaveOffer<br> totalleave=$totalLeave<br> totalWorkingDay=$totalWorkingDay<br> basic_salary=$basic_salary<br> hra=$hra<br> books_per=$books_per<br> sp_allowance=$sp_allowance<br> comp_epf=$comp_epf<br> working_basic_salary=$working_basic_salary<br> working_hra=$working_hra<br> working_books_per=$working_books_per<br> working_sp_allowance=$working_sp_allowance<br> working_tds=$working_tds<br> working_company_epf=$working_company_epf<br>  working_employee_epf=$working_employee_epf<br> working_esi=$working_esi<br> deduction=$deduction<br> monthlySalary=$monthlySalary<br> payableSalary=$payableSalary"; echo "<br><br>";

    // return [
    //     'monthSalaryDetails' => $monthSalaryDetails,
    //     'monthlySalary' => $monthlySalary,
    //     'l' => $l,
    //     'hd' => $hd,
    //     'totalLeave' => $totalLeave,
    //     'totalWorkingDay' => $totalWorkingDay,
    //     'working_salary' => $working_salary,
    //     'working_day_salary' => $working_day_salary,
    //     'working_tds' => $working_tds,
    //     'working_employee_epf' => $working_employee_epf,
    //     'working_company_epf' => $working_company_epf,
    //     'working_company_esi' => $working_company_esi,
    //     'working_employee_esi' => $working_employee_esi,
    //     'deduction' => $deduction,
    //     'payableSalary' => $payableSalary,
    //     'bonus' => $bonus,
    //     'incentive' => $incentive,
    //     'monthDay' => $monthDay,
    //     'leaveOffer' => 0,
    //     'working_basic_salary' => $working_basic_salary,
    //     'working_hra' => $working_hra,
    //     'working_sp_allowance' => $working_sp_allowance,
    //     'working_books_per' => $working_books_per,
    // ];


    // echo "<script>console.log(".json_encode($array).");</script>";

    $leaves = $array['leaves'];

    $fixed_pay = [];
    $add_on = [];
    $deduction = [];
    $fixed_pay = $array['fixed_pay'];
    $add_on = $array['add_on'];
    $deduction = $array['deduction'];
    // if($monthDay == $leaves['Month Days']){
    //     $fixed_pay = $array['fixed_pay'];
    //     $add_on = $array['add_on'];
    //     $deduction = $array['deduction'];
    // }else{
    //     $fixed_pay = !empty($finalSalaryArray['fixed']) ? json_decode($finalSalaryArray['fixed'], true) : [];
    //     $add_on = !empty($finalSalaryArray['add_on']) ? json_decode($finalSalaryArray['add_on'], true) : [];
    //     $deduction = !empty($finalSalaryArray['deduction']) ? json_decode($finalSalaryArray['deduction'], true) : [];
    //     // calculate according to 1 day all details
    //     foreach ($fixed_pay as $key => $value) {
    //         if ($value['yearly_amount'] != 0) {
    //             $fixed_pay[$key]['per_day_amount'] = $array['fixed_pay'][$key]['per_day_amount'];
    //             $fixed_pay[$key]['monthly_amount'] = ($value['yearly_amount'] / 12);
    //             $fixed_pay[$key]['working_amount'] = $array['fixed_pay'][$key]['working_amount'];
    //         }
    //     }
    //     foreach ($add_on as $key => $value) {
    //         if ($value['yearly_amount'] != 0) {
    //             $add_on[$key]['monthly_amount'] = $value['yearly_amount'] / 12;
    //         }
    //     }
    //     foreach ($deduction as $key => $value) {
    //         if ($value['yearly_amount'] != 0) {
    //             $deduction[$key]['monthly_amount'] = $value['yearly_amount'] / 12;
    //         }
    //     }
    //     $monthDay = $leaves['Month Days'];
    // }

    // echo "<script>console.log(".json_encode($fixed_pay).");</script>";
    // echo "<script>console.log(".json_encode($add_on).");</script>";
    // echo "<script>console.log(".json_encode($deduction).");</script>";

    $deduction_arr = [];
    foreach ($deduction as $key => $value) {
        $deduction_arr[$value['title']] = round(isset($value['working_amount']) ? $value['working_amount'] : $value['monthly_amount'], 2);
    }



    $fixed_ctc_components = [];
    foreach ($fixed_pay as $key => $value) {
        $fixed_ctc_components[$value['title']] = round($value['monthly_amount_payable'], 2);
    }

    $gross_ctc_components = [];
    foreach ($fixed_pay as $key => $value) {
        $gross_ctc_components[$value['title']] = round($value['monthly_amount_payable'], 2);
    }
    foreach ($add_on as $key => $value) {
        $gross_ctc_components[$value['title']] = round($value['monthly_amount_payable'], 2);
    }

    $payable_ctc_components = [];
    foreach ($fixed_pay as $key => $value) {
        $payable_ctc_components[$value['title']] = round($value['working_amount'], 2);
    }
    foreach ($add_on as $key => $value) {
        $payable_ctc_components[$value['title']] = round(isset($value['working_amount']) ? $value['working_amount'] : $value['monthly_amount'], 2);
    }

    $working_fixed_ctc_components = [];
    foreach ($fixed_pay as $key => $value) {
        $working_fixed_ctc_components[$value['title']] = round($value['working_amount'], 2);
    }

    $fixed_ctc_amount = ceil(array_sum($fixed_ctc_components));
    $gross_ctc_amount = ceil(array_sum($gross_ctc_components));
    $payable_ctc_amount = ceil(array_sum($payable_ctc_components));
    $working_fixed_ctc_amount = ceil(array_sum($working_fixed_ctc_components));

    

    $fixedMonthlySalary = $fixed_ctc_amount;
    $monthlySalary = $gross_ctc_amount;
    $deduction_amount = ceil(array_sum($deduction_arr));
    $payableSalary = ceil($working_fixed_ctc_amount - $deduction_amount);


    // not add any extra key without asking or without understanding the code
    $returnData = [
        'monthSalaryDetails' => $gross_ctc_components,
        'leaves' => $leaves,
        'working_salary' => $payable_ctc_components,
        'deduction' => $deduction_arr,
        'final_salary' => [
            'Payable Salary' => $payableSalary,
            'Bonus' => $bonus,
            'Incentive' => $incentive,
        ],
        "salary_components" => [
            'fixed_pay' => $fixed_pay,
            'add_on' => $add_on,
            'deduction' => $deduction,
        ],
        'monthlySalary' => $monthlySalary,
        'fixedMonthlySalary' => $fixedMonthlySalary,
        'fixedWorkingSalary' => $working_fixed_ctc_amount,
        'grossWorkingPayable' => $payable_ctc_amount,
    ];
    // echo "<script>console.log(".json_encode($returnData).");</script>";
    return $returnData;
}
