<?php
/**********************************************************************
***********************************************************************/
$page_security = 'SA_PERFORMANCE_INCENTIVE';
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/performance_incentives_entry_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 = "Perfornamce Incentives Achievements"));

$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, $saved_row, $payroll_run_id, &$total, &$k, $editable = false)
{
//    alt_table_row_color($k);
    
    $status_code = '';
    $amount_achieved = '0.00';
    $comments = '';
    $status_name = '';
    $row_id = 0;
    $dec = 2;
    
    if($saved_row){
        $status_code = $saved_row['status_code'];
        $amount_achieved = $saved_row["amount_achieved"];
        $comments = $saved_row["comments"];
        $status_name = $saved_row["status_name"];
        $row_id = $saved_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["note"]);

    $amount = '';
    $calculation_type = "";
//    if($myrow["calculation_type"] == "V"){
//        $calculation_type = "Value";
//        $amount = number_format($myrow["amount"],$dec);
//    }
//    elseif($myrow["calculation_type"] == "P"){
//        $calculation_type = "Percentage";
//        $dec = 5;
//        $amount = number_format($myrow["amount"],$dec);
//    }
//    elseif($myrow["calculation_type"] == "T"){
//        $calculation_type = "Table";
//    }
//    elseif($myrow["calculation_type"] == "R"){
//        $calculation_type = "Program";
//    }
//    else{
//        $calculation_type = "";
//    }
//    
//    label_cell($calculation_type, "align=center");
    
//    label_cell($amount, "align=center");
    
    //label_cell($myrow["salary_total_name"]);
    
//    if($myrow["calculation_type"] == "T"){
//        $a = get_list_value($myrow["table_id"]);
//        label_cell($a["value_name"]);
//    }
//    else{
//        label_cell("");
//    }
        //label_cell(number_format($myrow["amount"], 2), 'align=right');
    
//    $_POST[$myrow["last_name"]] = qty_format($amount_achieved, $_POST['salary_component_id'], $dec);
//    $_POST[$comments] = $comments;

    
    $prefix = $myrow["employee_code"]."_".$payroll_run_id."_".$_POST['salary_component']."_";
    if($editable){
        qty_cells(null, $prefix."amount_achieved", $amount_achieved, null, null, $dec);
    }
    else{
        label_cell($amount_achieved,  '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, $prefix."comments", $comments, 50);
    }
    else{
        label_cell($comments);
    }

    label_cell($status_name);

    
    if($editable){
        check_cells('', $prefix.'selected',0);
    }
    else{
        label_cell("");
    }
    
    hidden($prefix."row_id", $row_id);
    
    end_row();
    return $total = $total + $amount_achieved;
     
}

function save_performance_incentive_values($payroll_run_id, $period_start_date, $period_end_date, $approve = false)
{
    $result = get_performance_incentives_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)){
        $prefix = $myrow["employee_code"]."_".$payroll_run_id."_".$_POST['salary_component']."_";

        $bill_row = get_saved_performance_incentives_amounts($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[$prefix."comments"])){
            $comments = $_POST[$prefix."comments"];
        }
        
        if(!can_process_performance_incentive_entry($prefix, $myrow)){
            continue;
        }
   
        $amount_achieved = input_num($prefix."amount_achieved");
        
        $row_id = $_POST[$prefix."row_id"];
        
        if($row_id == 0){
            if($amount_achieved > 0){
                $status_code = ATD_NEW;
                add_performance_incentive_value($myrow['employee_code'], $_POST['salary_component'], 
                                        $amount_achieved, 
                                        $payroll_run_id, $comments,
                                        $status_code);   
            }
        }
        else{
            if($amount_achieved > 0){
                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_performance_incentive_value($row_id,$myrow['employee_code'], 
                                            $amount_achieved, 
                                            $payroll_run_id, $comments, $status_code);
                }
            }
            else{
                delete_performance_incentive_value($row_id);
            }
        }    
        
        if($approve && ($status_code == ATD_NEW || $status_code == ATD_UPDATED)){
            if((isset($_POST[$prefix."selected"]) && $_POST[$prefix."selected"] == true))
            {
                approve_performance_incentive_detail($row_id, $myrow['employee_code'], 
                                            $_POST['payroll_run_id']);
            }
        }
	}
    
    if($approve){
        display_notification("Selected records, if any, have been approved");
    }
    else{
        display_notification("All the records have been updated");
    }
}

function can_process_performance_incentive_entry($prefix, $row)
{
    if (!check_num($prefix."amount_achieved", 0.00)){
            return false;
    }
        
    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['approve'])){
    save_performance_incentive_values($payroll_run_id, $payroll_run['period_start_date'], $payroll_run['period_end_date'], true);
}

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

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

$Ajax->activate('allowances');

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

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

if (!@$_GET['popup'])
{
    $salary_component_list_codes = "'PERFORMANCE_RATE_INCENTIVES','PERFORMANCE_VALUE_INCENTIVES'";
    //value_list_row("Salary Component:", "salary_component_id", $salary_componet_list_code, null, false, false);
    salary_components_list_row("Salary Component", "salary_component_id", $_POST['salary_component_id'], $salary_component_list_codes);
    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("Performance Incentives Achievements");

br(1);

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

$th = array(_("Code"), _("Name"),_("Note"), _("Amount Achieved"), _("Comment"), _("Status"), _("Select"));

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

$result = get_performance_incentives_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']);
}

table_header($th);

$total = 0;
$show_buttons = false;
while ($myrow = db_fetch($result))
{
        $saved_row = get_saved_performance_incentives_amounts($_POST['payroll_run_id'], $myrow['employee_code'], $_POST['salary_component_id']);
        if($saved_row){        
            if(!$saved_row["status_code"] || $saved_row["status_code"] == "N" || $saved_row["status_code"] == "U" )
            {
                $show_buttons = true;
            }
        }
        else{
            $show_buttons = true;
        }

        alt_table_row_color($k);

        $total = display_record($myrow, $saved_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 All Records"), '', @$_REQUEST['popup'] ? true : 'default');
        submit_center_last('approve', _("Approve Selected Records"), '', @$_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);
}
?>
