<?php
require_once 'config.php';

$result = mysqli_query($db, "SELECT * FROM employee_salary WHERE COALESCE(basic_salary, 0) > 0 ORDER BY id ASC");
while($row = mysqli_fetch_assoc($result)) {

    // [{"title":"Basic Salary","yearly_amount":"120000"},{"title":"House Rent Allowance (HRA)","yearly_amount":"60000"},{"title":"Books & Periodicals","yearly_amount":"30000"},{"title":"Special Allowance","yearly_amount":"30000"}]
    $components = [
        ["title" => "Basic Salary", "yearly_amount" => $row['basic_salary']] ?? "0",
        ["title" => "House Rent Allowance (HRA)", "yearly_amount" => $row['hra']] ?? "0",
        ["title" => "Special Allowance", "yearly_amount" => $row['special_allowance']] ?? "0",
        ["title" => "Books & Periodicals", "yearly_amount" => $row['books_per']] ?? "0",
    ];

    $fixed = [];

    // Only add if the yearly_amount is not empty and not 0
    foreach ($components as $item) {
        if (!empty($item['yearly_amount']) && $item['yearly_amount'] != 0) {
            $fixed[] = $item;
        }
    }
    // echo "<pre>";
    // print_r($fixed);
    // echo "</pre>";

    $fixed_salary = array_sum(array_column($fixed, 'yearly_amount'));
    echo "Total Fixed Salary: " . $fixed_salary . "<br>";


    // [{"title":"EPF Employer Share","yearly_amount":"14400"}]
    $addOn = [];
    if($row['epf_status'] =='Yes') {
        $addOn[] = ["title" => "EPF Employer Share", "yearly_amount" => $row['company_epf']];
    }
    if($row['esi_status'] =='Yes'){
        $addOn[] = ["title" => "ESIC Employer Share @ 3.25% of (A)", "yearly_amount" => ceil($fixed_salary * 0.0325)];
    }
    echo "<pre>";
    print_r($addOn);
    echo "</pre>";


    // [{"title":"EPF Employee Share","yearly_amount":"14400"}]
    $deductions = [];
    if($row['epf_status'] =='Yes') {
        $deductions[] = ["title" => "EPF Employee Share", "yearly_amount" => ceil(min($row['basic_salary'] * 0.12, 1800*12))];
    }
    if($row['esi_status'] =='Yes') {
        $deductions[] = ["title" => "ESIC Employee Share @ 0.75% of (A)", "yearly_amount" => ceil($fixed_salary * 0.0075)];
    }
    if(!empty($row['tds'])) {
        $deductions[] = ["title" => "TDS", "yearly_amount" => ceil($row['tds'])]; // Assuming 15% TDS for demonstration
    }
    // echo "<pre>";
    // print_r($deductions);
    // echo "</pre>";

    $ctc = $fixed_salary + ($addOn ? array_sum(array_column($addOn, 'yearly_amount')) : 0);
    echo "CTC: " . $ctc . "<br>";

    $net_payable = $fixed_salary - array_sum(array_column($deductions, 'yearly_amount'));
    echo "Net Payable: " . $net_payable . "<br>";


    $fixed_json = json_encode($fixed);
    $addOn_json = json_encode($addOn);
    $deductions_json = json_encode($deductions);

    mysqli_query($db, "UPDATE employee_salary SET ctc='$ctc', net_payable='$net_payable', fixed='$fixed_json', add_on='$addOn_json', deduction='$deductions_json' WHERE id='{$row['id']}'");
}

?>