<?php
/**********************************************************************
***********************************************************************/
$page_security = 'SA_MOBILE_ALLOWANCE_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/mobile_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");
        

if (!@$_GET['popup'])
{
	$js = "";
	if ($SysPrefs->use_popup_windows)
		$js .= get_js_open_window(900, 600);
	if (user_use_date_picker())
		$js .= get_js_date_picker();
}
if (!@$_GET['popup'])
	page(_($help_context = "Mobile Allowances Entry"));

$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;
        }
}

if(isset($_POST['salary_component_id'])){
    $list_value = get_list_value($_POST['salary_component_id']);
    $_POST['salary_component'] = $list_value['value_code'];
}
else{
    $_POST['salary_component'] = "";
}

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

function display_record($myrow, $bill_row, $payroll_run_id, &$total, &$k, $editable = false)
{
//    alt_table_row_color($k);
    
    $status_code = '';
    $mobile_bill = '0.00';
    $comments = '';
    $status_name = '';
    $row_id = 0;
    
    if($bill_row){
        $status_code = $bill_row['status_code'];
        $mobile_bill = $bill_row["mobile_bill"];
        $comments = $bill_row["comments"];
        $status_name = $bill_row["status_name"];
        $row_id = $bill_row["id"];
    }
    
    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["office_mobile_no"]);

    if($myrow["calculation_type"] == "V"){
        label_cell("Value");
    }
    elseif($myrow["calculation_type"] == "P"){
        label_cell("Percentage");
    }
    elseif($myrow["calculation_type"] == "T"){
        label_cell("Table");
    }
    elseif($myrow["calculation_type"] == "R"){
        label_cell("Program");
    }
    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');
    
    $_POST[$myrow["last_name"]] = qty_format($mobile_bill, $_POST['salary_component_id'], $dec);
    $_POST[$comments] = $comments;

    if($editable){
        qty_cells(null, $myrow["employee_code"]."_".$payroll_run_id."_".$_POST['salary_component']."_mobile_bill", $mobile_bill, null, null, $dec);
    }
    else{
        label_cell($mobile_bill,  'align=right');
    }
    
    if($myrow["calculation_type"] == "V"){
        if($mobile_bill - $myrow["amount"] > 0)
        {
            label_cell (number_format($mobile_bill - $myrow["amount"], 2),  'align=right');
        }
        else
        {
            label_cell("");
        }
    }
    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);

    hidden($myrow["employee_code"]."_".$payroll_run_id."_".$_POST['salary_component']."_row_id", $row_id);
    
    end_row();
    return $total = $total + $mobile_bill;
     
}

function save_mobile_allowances($payroll_run_id, $period_start_date, $period_end_date, $process = false)
{
    $result = get_mobile_allowances_assigned_employee_list($_POST['salary_component_id'], $period_start_date, $period_end_date);
    //$result = get_employee_list_for_mobile_allowances($_POST['salary_component_id'], $year_month);
    while ($myrow = db_fetch($result)){
        $bill_row = get_saved_employee_mobile_bill_values($payroll_run_id, $myrow['employee_code'], $_POST['salary_component_id']);
            
        $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_mobile_allowance_entry($myrow)){
            continue;
        }
   
        $over_used_amount = 0;
        $bill_amount = 0;
        if (!check_num($myrow["employee_code"]."_".$payroll_run_id."_".$_POST['salary_component']."_mobile_bill", 0.00)){
            continue;
        }
        else{
            $bill_amount = input_num($myrow["employee_code"]."_".$payroll_run_id."_".$_POST['salary_component']."_mobile_bill");
            $over_used_amount = $bill_amount - $myrow['amount'];
            if($over_used_amount < 0){
                $over_used_amount = 0;
            }
        }
        
        $row_id = $_POST[$myrow["employee_code"]."_".$payroll_run_id."_".$_POST['salary_component']."_row_id"];
        
        if($row_id == 0){
                $status_code = ATD_NEW;
                add_mobile_allowance($myrow['employee_code'], $_POST['salary_component'], 
                                        $bill_amount, $over_used_amount, 
                                        $payroll_run_id, $comments,
                                        $status_code);              
        }
        else{
            if($status_code == ATD_NEW){
                $status_code = ATD_UPDATED;
            }
            elseif($status_code == 0 || $status_code == ''){
                    $status_code = ATD_NEW;
            }
            
            if($status_code == ATD_NEW || $status_code == ATD_UPDATED){
                update_mobile_allowance($row_id,$myrow['employee_code'], 
                                        $bill_amount, $over_used_amount, 
                                        $payroll_run_id, $comments, $status_code);
            }
        }
        
        if($process && ($status_code == ATD_NEW || $status_code == ATD_UPDATED)){
                approve_mobile_allowance($row_id, $myrow['employee_code'], 
                                        $_POST['payroll_run_id']);
            }
	}   
}

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

function display_total(&$total, &$k)
{
//    alt_table_row_color($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;
}

if (isset($_GET['stock_id']))
	$_POST['stock_id'] = $_GET['stock_id'];

//if (list_updated('stock_id')) 
{
	$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');

if (!@$_GET['popup'])
	start_form();

if (!isset($_POST['stock_id']))
	$_POST['stock_id'] = get_global_stock_item();

if (!@$_GET['popup'])
{
    $salary_componet_list_code = "MOBILE_ALLOWANCES_OVER_USAGE";
    value_list_row("Salary Component:", "salary_component_id", $salary_componet_list_code, null, false, false);
    payroll_run_list_row('Payroll Run:', 'payroll_run_id', $payroll_run_id);
    submit_cells('RefreshInquiry', _("Search"),'',_('Refresh Inquiry'), 'default');
//	echo "<hr></center>";
}
br(2);

div_start('allowances');
br(1);
display_heading2("Mobile Bill Expences");

br(1);

start_table(TABLESTYLE, "width=80%");

$th = array(_("Code"), _("Name"), _("Mobile No"), _("Calculation Type"), _("Amount"), _("Mobile Bill"),
                            _("Over Used Amount"), _("Comment"), _("Status"));

$j = 1;
$k=0; //row colour counter

$result = get_mobile_allowances_assigned_employee_list($_POST['salary_component_id'], $payroll_run['period_start_date'], $payroll_run['period_end_date']);

if (@$_GET['popup'])
{
	hidden('_tabs_sel', get_post('_tabs_sel'));
	hidden('popup', @$_GET['popup']);
}
$total = 0;
$previous_mobile_no_prefix = '';
$current_mobile_no_prefix = '';
$show_buttons = false;
while ($myrow = db_fetch($result))
{
        $bill_row = get_saved_employee_mobile_bill_values($_POST['payroll_run_id'], $myrow['employee_code'], $_POST['salary_component_id']);
        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;
        }
        if($current_mobile_no_prefix == '' && $previous_mobile_no_prefix == '')
        {
            display_heading('Mobile Network Provider - '."$current_mobile_no_prefix");
            table_header($th);
        }
        $current_mobile_no_prefix = substr($myrow['office_mobile_no'], 0, 3);
        if($current_mobile_no_prefix == '')
        {
            $current_mobile_no_prefix = "No mobile number assigned";
        }
        
        alt_table_row_color($k);
        $updated_mobile_mobile_bill_detail_id = 0;
        $mobile_mobile_bill_detail_id = 0;
        if(input_num($myrow["employee_code"]."_".$_POST['salary_component']."_mobile_bill")> $myrow['amount']){
            $over_used_amount =input_num($myrow["employee_code"]."_".$_POST['salary_component']."_mobile_bill") - $myrow['amount'];
        }
        else{
            $over_used_amount = 0;
        }  
        
        if($current_mobile_no_prefix != $previous_mobile_no_prefix && $previous_mobile_no_prefix != '')
        {
            display_total($total, $k);
            end_table();
            start_table(TABLESTYLE, "width=80%");
            br(2);
            display_heading('Mobile Network Provider - '." $current_mobile_no_prefix");
//            echo 'Mobile Network Provider'." $current_mobile_no_prefix";
            table_header($th);
            alt_table_row_color($k);
            display_record($myrow, $bill_row, $payroll_run_id, $total, $k, $editable);
            $previous_mobile_no_prefix = $current_mobile_no_prefix;
        }
        else
        {
            $total = display_record($myrow, $bill_row, $payroll_run_id, $total, $k, $editable); 
            $previous_mobile_no_prefix = $current_mobile_no_prefix;
        }
        
}
alt_table_row_color($k);
if($current_mobile_no_prefix != '')
{
    display_total($total, $k);
} 
end_table(1);

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