<?php
/**********************************************************************
***********************************************************************/
include_once($path_to_root . "/includes/date_functions.inc");
include_once($path_to_root . "/payroll/includes/salary_totals.inc");
include_once($path_to_root . "/payroll/includes/db/salary_totals_db.inc");

function calculate_payroll_summries($payroll_run_id)
{
    delete_payroll_calculations($payroll_run_id);
    
    $payroll_run = get_payroll_run_details($payroll_run_id);
    
    $result = get_payroll_summary_calculation_seq($payroll_run['payroll_id']);
    if(!db_num_rows($result) > 0){
        return array("passed" => false, "message" => _("No applicable components found for payroll summary calculation."));
    }
    while ($myrow = db_fetch($result)){
        $pcs[] = array('process_code' => $myrow['process_code'], 'process_type' => $myrow['process_type']);
    } 
    
    $last_completed_employee_code = get_last_completed_emloyee($payroll_run['id']);
    $employee = get_next_payroll_employee($last_completed_employee_code, $payroll_run);
    if($employee != null){
        $employee_code = $employee['employee_code'];
    }else{
        // if the last completed employee of the previous run is the final employee of the list, start from the beginning.
        if(strlen($last_completed_employee_code)> 0){
            $employee = get_next_payroll_employee('', $payroll_run);
            $employee_code = $employee['employee_code'];

        }
        else{
            return array("passed" => false, "message" => _("No next payroll employee found. Could not run payroll summay calculation"));
        }
    }
    
    update_payroll_run_status($payroll_run['id'], "C", true, false, true); // Calculating
    
    while (strlen($employee_code) > 0)
    {
        foreach ($pcs as $process){
            switch ($process['process_type']){
                case 'ATTENDANCE_ALLOWANCES':
                        if($process['process_code'] == "DRIVER_ATT_ALLOWANCE"){
                            $summary_value = calculate_payroll_employee_attendance_summary(SCT_ATTENDANCE_ALLOWANCES, $process['process_code'], $employee, $payroll_run);
                        }
                        elseif($process['process_code'] == "LABOUR_ATT_ALLOWANCE"){
                            $summary_value = calculate_payroll_employee_leave_summary(SCT_ATTENDANCE_ALLOWANCES, $process['process_code'], $employee, $payroll_run);
                        }
                        break;
                case 'WORKTIME_DEFICITS':
                            $summary_value = calculate_payroll_employee_worktime_deficit_summary(SCT_WORKTIME_DEFICITS, $process['process_code'], $employee, $payroll_run);                        
                        break;
                default:
            }
        }
        
        $last_completed_employee_code = $employee_code;
        update_last_completed_employee_code($last_completed_employee_code, $payroll_run['id']);
        $employee = get_next_payroll_employee($last_completed_employee_code, $payroll_run);
        if($employee != null){
            $employee_code = $employee['employee_code'];
        }
        else{
            $employee_code = '';
        }
    }

    return array("passed" => true, "message" => $payroll_run['id']);

}


function calculate_payroll_employee_worktime_deficit_summary($record_type, $process_code, $employee, $payroll_run, $nopay_days = 0)
{
    $employee_code = $employee['employee_code'];
    $payroll_days_factor = 1;
    $applicable_days = 30;
    
    $my_row = select_salary_component($record_type, $process_code, $employee_code, $payroll_run);
    if($my_row == null){
        return 0;
    }
   
    //---------------------------
    $applicable_start_date = $applicable_end_date = '';
    $applicable_days = get_payroll_calculation_applicable_values($payroll_run, $employee, 
                                                $my_row, $nopay_days, 
                                                $applicable_start_date, $applicable_end_date, $payroll_days_factor);      
    
    if($applicable_days == 0){
        return 0;
    }

    $total_worktime_deficit = get_worktime_total_deficit_hours($employee_code, $payroll_run, $applicable_start_date, $applicable_end_date);
    
    if($total_worktime_deficit['period_total_deficit_s'] > 0){  
        insert_payroll_employee_worktime_deficit_summary($payroll_run['id'], $employee_code, $process_code, $total_worktime_deficit['period_total_deficit_s'], $total_worktime_deficit['comment']);
    }  
    
    return $total_worktime_deficit['period_total_deficit_s'];
}


function get_worktime_total_deficit_hours($employee_code, $payroll_run, $effective_start_date, $effective_end_date)
{ 
    $period_total_deficit_s = 0;
    $comment = '';
    
    $result = select_all_approved_worktime_deficits($employee_code, $effective_start_date, $effective_end_date);
    while ($myrow = db_fetch($result)){
        $daily_defficit_s = strtotime("1970-01-01 ".$myrow['deducted_deficit_time']." UTC");
        if($daily_defficit_s > 0){
            $comment .= $myrow['entry_date']." - (".substr($myrow['from_date_time1'],11,5).")".substr($myrow['deducted_deficit_time'],0,5)."\r\n";
            update_worktime_deficit_record_status($myrow["id"], "L", $payroll_run['id'], 0);
            $period_total_deficit_s += $daily_defficit_s;
        }
    }
    
    //$period_total_deficit_h = number_format(($period_total_deficit_s / 3600), 2); 
    
    return array("period_total_deficit_s" => $period_total_deficit_s, "comment" => $comment);
    
}

function calculate_payroll_employee_leave_summary($record_type, $process_code, $employee, $payroll_run, $nopay_days = 0)
{
    $employee_code = $employee['employee_code'];
    $payroll_days_factor = 1;
    
    $my_row = select_salary_component($record_type, $process_code, $employee_code, $payroll_run);
    if($my_row == null){
        return 0;
    }
   
    //---------------------------
    $applicable_start_date = $applicable_end_date = '';
    $applicable_days = get_payroll_calculation_applicable_values($payroll_run, $employee, 
                                                $my_row, $nopay_days, 
                                                $applicable_start_date, $applicable_end_date, $payroll_days_factor);       
    
    if($applicable_days == 0){
        return;
    }
    
    //-----------------------------
    
    $leave_summary = get_leave_records_summary($employee_code, $applicable_start_date, $applicable_end_date);
    if(!$leave_summary){
        $total_leave_days = 0;
        $comment = '';
    }
    else{
        $total_leave_days = $leave_summary['leave_days_count'];
        $comment = $leave_summary['comment'];
    }
    
    if($total_leave_days >= 0){
        insert_payroll_employee_attendance_summary($payroll_run['id'], $employee_code, $process_code, $total_leave_days, $comment);
    }  
    
    return $total_leave_days;
}


function get_leave_records_summary($employee_code, $period_start_date, $period_end_date)
{ 
    $leave_days_count = 0;
    $comment = '';
    
    $result = select_period_leave_records($employee_code, $period_start_date, $period_end_date);
    while($my_row = db_fetch($result)){
        $day_leave_amount = $my_row['leave_days'];
        if($my_row['is_revoke'] == 1){
            $day_leave_amount = $day_leave_amount * -1;
            $leave_days_count--;
            $comment .= $my_row['date']." - ".$day_leave_amount."\r\n";
        }
        else{
            $leave_days_count++;
            $comment .= $my_row['date']." - ".$day_leave_amount."\r\n";
        }
    }
    
    if($leave_days_count < 0){
        $leave_days_count = 0;
    }
    return array("leave_days_count" => $leave_days_count, "comment" => $comment);
}


function calculate_payroll_employee_attendance_summary($record_type, $process_code, $employee, $payroll_run, $nopay_days = 0)
{
    $employee_code = $employee['employee_code'];
    $payroll_days_factor = 1;
    
    $my_row = select_salary_component($record_type, $process_code, $employee_code, $payroll_run);
    if($my_row == null){
        return 0;
    }
   
    //---------------------------
    $applicable_start_date = $applicable_end_date = '';
    $applicable_days = get_payroll_calculation_applicable_values($payroll_run, $employee, 
                                                $my_row, $nopay_days, 
                                                $applicable_start_date, $applicable_end_date, $payroll_days_factor);       
    
    if($applicable_days == 0){
        return;
    }
    
    //-----------------------------
    
    $attendance_records_summary = get_attendance_records_summary($employee_code, $applicable_start_date, $applicable_end_date);
    $no_of_valid_records = $attendance_records_summary['total_days_count'];
    $comment = $attendance_records_summary['comment'];
    
    if($no_of_valid_records > 0){
        insert_payroll_employee_attendance_summary($payroll_run['id'], $employee_code, $process_code, $no_of_valid_records, $comment);
    }  
    
    return $no_of_valid_records;
}


function get_attendance_records_summary($employee_code, $period_start_date, $period_end_date)
{ 
    $holiday_records_count = 0;
    $attendance_records_count = 0;
    $comment = '';
    
    $attendance_records_summary = select_attendance_records_summary($employee_code, $period_start_date, $period_end_date);
    if($attendance_records_summary){
        $attendance_records_count = $attendance_records_summary['record_count'];
    }
    
    $holiday_records_summary = select_fullday_holiday_summary($period_start_date, $period_end_date);  
    if($holiday_records_summary){
        $holiday_records_count = $holiday_records_summary['record_count'];
    }
    
    $period_days_count = date_diff2(sql2date($period_end_date), sql2date($period_start_date), 'd') + 1;
    $month_days_adjustments = 31 - $period_days_count;
    if($month_days_adjustments < 0){
        $month_days_adjustments = 0;
    }
    $total_days_count = $attendance_records_count + $holiday_records_count + $month_days_adjustments;
    
    $comment = "(".$attendance_records_count.") + (".$holiday_records_count.") + (".$month_days_adjustments.") = ".$total_days_count;
    
    return array("total_days_count" => $total_days_count, "comment" => $comment);
    
}


function delete_payroll_calculations($payroll_run_id)
{
    begin_transaction();
    delete_attendance_records_summary($payroll_run_id);
    delete_work_time_deficit_summary($payroll_run_id);
    delete_payroll_run_details($payroll_run_id);
    commit_transaction();
}

?>
