<?php
/**********************************************************************
***********************************************************************/
$page_security = 'SA_EMPLYEE_ALLOWANCES_USAGE';
if (!@$_GET['popup'])
    $path_to_root = "..";
else	
    $path_to_root = "../..";

include_once($path_to_root . "/includes/session.inc");
include_once($path_to_root . "/includes/date_functions.inc");
include_once($path_to_root . "/includes/ui.inc");
include_once($path_to_root . "/includes/data_checks.inc");
include_once($path_to_root . "/inventory/includes/inventory_db.inc");
include_once($path_to_root . "/payroll/includes/db/employee_allowances_usage_db.inc");
include_once($path_to_root . "/payroll/includes/db/salary_deductions_db.inc");
include_once($path_to_root . "/payroll/includes/db/approve_salary_adjustments_db.inc");
include_once($path_to_root . "/admin/db/list_values_db.inc");

include_once($path_to_root . "/includes/db/module_settings_db.inc");
include_once($path_to_root . "/payroll/includes/db/payroll_run_db.inc");      

$js = "";
$js .= get_js_open_window(900, 600);
$js .= get_js_date_picker();

page(_($help_context = "Employee Allowances Usage"));

$payroll_run_id = 0;
if (isset($_POST['payroll_run_id'])) {
    $payroll_run_id = $_POST['payroll_run_id'];
}

$payroll_run = get_payroll_run_details($payroll_run_id);

$editable = false;
if ($payroll_run) {
    $s = $payroll_run["status"];                    
    if ($s == "N" || $s == "U" || $s == "C" || $s == "L") {
        $editable = true;
    }
}

//------------------------------------------------------------------------------------

function display_record($myrow, $bill_row, $payroll_run_id, &$total, &$k, $editable = false) {   
    $status_code = '';
    $spent_amount = '0.00';
    $comments = '';
    $status_name = '';
    
    if ($bill_row) {
        $status_code = $bill_row['status_code'];
        $spent_amount = $bill_row["spent_amount"];
        $comments = $bill_row["comments"];
        $status_name = $bill_row["status_name"];
    }
    
    if ($editable == true && ($status_code == ATD_NEW || $status_code == ATD_UPDATED || $status_code == '')) {
        $editable = true;
    } else {
        $editable = false;
    }
    label_cell($myrow["employee_code"]);
    label_cell($myrow["initials"]. " " . $myrow["last_name"]." (".$myrow["first_name"].")");
    label_cell($myrow["comments"]);

    if ($myrow["calculation_type"] == "V") {
        label_cell("Value");
    } elseif ($myrow["calculation_type"] == "P") {
        label_cell("Percentage");
    } elseif($myrow["calculation_type"] == "T") {
        label_cell("Table");
    } else {
        label_cell("");
    }

    if ($myrow["calculation_type"] == "T") {
        $a = get_list_value($myrow["table_id"]);
        label_cell($a["value_name"]);
    } else {
        label_cell(number_format($myrow["amount"], 2), 'align=right');
    }
    
    $dec = 2;
    
//    $_POST[$myrow["last_name"]] = qty_format($spent_amount, $_POST['salary_component'], $dec);
    $_POST[$comments] = $comments;

    if ($editable) {
        qty_cells(null, $myrow["employee_code"]."_".$payroll_run_id."_".$_POST['salary_component']."_spent_amount", $spent_amount, null, null, $dec);
    } else {
        label_cell($spent_amount,  'align=right');
    }
    
    if ($myrow["calculation_type"] == "V") {
        if ($spent_amount - $myrow["amount"] > 0) {
            label_cell (number_format($spent_amount - $myrow["amount"], 2),  'align=right');
        } else {
            label_cell("0.00");
        }
    } else {
        label_cell("To be calculated", "align=center");
    }
    
    if ($editable) {
        text_cells(null, $myrow["employee_code"]."_".$payroll_run_id."_".$_POST['salary_component']."_comments", $comments);
    } else {
        label_cell($comments);
    }

    label_cell($status_name);

//    end_row();    
}

function save_mobile_allowances($payroll_run_id, $period_start_date, $period_end_date, $process = false) {
    $result = get_employee_allowances_assigned_employee_list($_POST['salary_component'], $period_start_date, $period_end_date);
    while ($myrow = db_fetch($result)) {
        $bill_row = get_saved_employee_allowances_usage($payroll_run_id, $myrow['employee_code'], $_POST['salary_component']);
            
        $status_code = '';
        if ($bill_row) {
            $status_code = $bill_row['status_code'];
        }
        
        $comments = '';
        if (isset($_POST[$myrow["employee_code"]."_".$payroll_run_id."_".$_POST['salary_component']."_comments"])) {
            $comments = $_POST[$myrow["employee_code"]."_".$payroll_run_id."_".$_POST['salary_component']."_comments"];
        }
        
        if (! can_process_employee_allowances_usage_entry($myrow)) {
            continue;
        }
   
        $over_spent_amount = 0;
        $spent_amount = 0;
        if (! check_num($myrow["employee_code"]."_".$payroll_run_id."_".$_POST['salary_component']."_spent_amount", 0.00)) {
            continue;
        } else {
            $spent_amount = input_num($myrow["employee_code"]."_".$payroll_run_id."_".$_POST['salary_component']."_spent_amount");
            $over_spent_amount = $spent_amount - $myrow['amount'];
            if ($over_spent_amount < 0) {
                $over_spent_amount = 0;
            }
        }
        
        if ($status_code == '') {
            $status_code = ATD_NEW;
            add_employee_allowances_usage($myrow['employee_code'], $_POST['salary_component'], $spent_amount, $over_spent_amount, $payroll_run_id, $comments, $status_code);              
        } elseif ($status_code == ATD_NEW || $status_code == ATD_UPDATED) {  
            if ($status_code == ATD_NEW) {
                $status_code = ATD_UPDATED;
            }
            
            update_employee_allowances_usage($myrow['employee_code'], $_POST['salary_component'], $spent_amount, $over_spent_amount, $payroll_run_id, $comments, $status_code);
        }
        
        if ($process && ($status_code == ATD_NEW || $status_code == ATD_UPDATED)) {
            approve_employee_allowances_usage($myrow['employee_code'], $_POST['salary_component'], $_POST['payroll_run_id']);
        }
    }   
}

function can_process_employee_allowances_usage_entry($row) {
    return true;
    
    if($row['calculation_type'] == 'V') {
        return true;
    } else {
        return false;
    }
}

function display_total(&$total, &$k) {
    label_cell("Total", "colspan=4 align=right");
    label_cell(number_format($total, 2), 'align=right style="font-weight:bold"');
    label_cell("");
    label_cell("");
    label_cell("");
    $total = 0;
}

$Ajax->activate('show_heading');
$Ajax->activate('allowances');

if (isset($_POST['process'])) {
    save_mobile_allowances($payroll_run_id, $payroll_run['period_start_date'], $payroll_run['period_end_date'], true);
}

if (isset($_POST['addupdate'])) {
    save_mobile_allowances($payroll_run_id, $payroll_run['period_start_date'], $payroll_run['period_end_date']);
}

//------------------------------------------------------------------------------------

$Ajax->activate('allowances');

start_form();
    start_table();
        $salary_componet_list_code = "EMPLOYEE_ALLOWANCES_OVER_USAGE";
        value_list_code_row("Salary Component:", "salary_component", $salary_componet_list_code, null, false, false);
        payroll_run_list_row('Payroll Run:', 'payroll_run_id', null);
    end_table(1);
    submit_center_first('RefreshInquiry', _("Search"), _('Refresh Inquiry'), false, ICON_SUBMIT);
    br(2);

    div_start('allowances');
        start_table(TABLESTYLE, "width=80%");
            $th = array(_("Code"), _("Name"),_("Note"), _("Calculation Type"), _("Amount"), _("Spent Amount"), _("Over Spent Amount"), _("Comment"), _("Status"));
            table_header($th);


            if (@$_GET['popup']) {
                hidden('_tabs_sel', get_post('_tabs_sel'));
                hidden('popup', @$_GET['popup']);
            }
            
            if (is_array($payroll_run)) {
                $result = get_employee_allowances_assigned_employee_list($_POST['salary_component'], $payroll_run['period_start_date'], $payroll_run['period_end_date']);
            }
            
            $total = 0;
            $show_buttons = false;
            $j = 1;
            $k = 0; //row colour counter
            
            if (isset($result)) {
                while ($myrow = db_fetch($result)) {
                    $bill_row = get_saved_employee_allowances_usage($_POST['payroll_run_id'], $myrow['employee_code'], $_POST['salary_component']);
                    if ($bill_row) {        
                        if (!$bill_row["status_code"] || $bill_row["status_code"] == "N" || $bill_row["status_code"] == "U") {
                            $show_buttons = true;
                        }
                    } else {
                        $show_buttons = true;
                    }

                    alt_table_row_color($k);
                        if (input_num($myrow["employee_code"]."_".$_POST['salary_component']."_spent_amount")> $myrow['amount']) {
                            $over_spent_amount =input_num($myrow["employee_code"]."_".$_POST['salary_component']."_spent_amount") - $myrow['amount'];
                        } else {
                            $over_spent_amount = 0;
                        }  

                        $total = display_record($myrow, $bill_row, $payroll_run_id, $total, $k, $editable); 
                }
            }
            
            alt_table_row_color($k);

            end_table(1);

            if ($editable) {
                if ($show_buttons == true) {
                    submit_center_first('addupdate', _("Update"), '', @$_REQUEST['popup'] ? true : 'default');
                    submit_center_last('process', _("Approve"), '', @$_REQUEST['popup'] ? true : 'default');
                } else {
                    //submit_center_first('addupdate', _("Update"), '', @$_REQUEST['popup'] ? true : 'default');
                }
            }
    div_end();
    
end_form(2);
end_page(@$_GET['popup'], false, false);

?>