<?php
/**********************************************************************
***********************************************************************/
$page_security = 'SA_SALARY_ADVANCE';
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/inventory.inc");
include_once($path_to_root . "/includes/data_checks.inc");
include_once($path_to_root . "/payroll/includes/db/salary_advances_db.inc");
include_once($path_to_root . "/payroll/includes/db/salary_advances_accounts_setup_db.inc");
include_once($path_to_root . "/includes/db/module_settings_db.inc");

$js = '';

if ($SysPrefs->use_popup_windows) {
	$js .= get_js_open_window(900, 500);
}

if (user_use_date_picker()) {
	$js .= get_js_date_picker();
}

page(_($help_context = "Salary Advances"));

//----------------------------------------------------------------------------------------
simple_page_mode(true);

if (isset($_GET['employee_code']))
{
	$_POST['employee_code'] = $_GET['employee_code'];
}

/*
function get_status_name($status_code)
{
    switch ($status_code)
    {
        case 'N':
            return "New";
            break;
        case 'U':
            return "Updated";
            break;
        case 'C':
            return "Calculating";
            break;
        case 'L':
            return "Calculated";
            break;
        case 'S':
            return "Calculation Stopped";
            break;
        case 'P':
            return "Processing";
            break;
        case 'R':
            return "Processed";
            break;
        case 'T':
            return "Processing Stopped";
            break;
        default:
            return "Unknown Status";
            break;

    }
    
}
 * 
 */

function make_payment($id)
{
    $myrow = get_salary_advance_details($id);
    
    $account_codes = get_salary_advance_account_detail($myrow['type_id']);
    if(!$account_codes){
        display_error( _("Could not retrieve payment account details for this slary advance type. Not possible to make the payment."));
    }
    
    if(($account_codes['debit_code'] == "" || $account_codes['credit_code'] == ""))
    {
        display_error( _("Account definition for this salary advance type is not complete. Not possible to make the payment."));

    }
    elseif($myrow['status_code'] == "D"){
        display_error( _("Payment has been already processed for this salary advance."));
    }
    elseif($myrow['status_code'] != "A"){
        display_error( _("This salary advance has not been approved."));
    }
    else{
        pay_salary_advance($id, $_POST['employee_code'], $myrow['salary_advance'], 
                        $account_codes['debit_code'], $account_codes['credit_code']);
    }
    
}


function check_data($Mode, $selected_id)
{	
        if (!isset($_POST['employee_code']) || strlen($_POST['employee_code']) < 1)
   	{
            display_error( _("Please select an employee."));
            set_focus('employee_code');
            return false;
   	}
        
        if (!check_num('salary_advance',0))
   	{
            display_error( _("Amount entered is not numeric or negative."));
            set_focus('salary_advance');
            return false;
   	}
        
        if (!is_date($_POST['due_date']))
   	{
            display_error( _("Due date entered is not a valid date."));
            set_focus('due_date');
            return false;
   	}
    
    $outside = is_outside_payroll_entries_allowed_date_range($_POST['due_date']);
    if($outside["success"] !== true)
   	{
            display_error( _("Due date: ".$outside['message']));
            set_focus('due_date');
            return false;
   	}
    
    
    if($Mode == "ADD_ITEM"){
        $rec = get_salary_advance_existing_record($_POST['employee_code'], $_POST['type_id'], input_num('salary_advance'), $_POST['due_date']);
        if ($rec)
        {
                display_error( _("There is an identical salary advance entered for current employee."));
                set_focus('salary_addition');
                return false;
        }
    }
    
        return true;
    
}
//--------------------------------------------------------------------------------------------------


if (($Mode=='ADD_ITEM' || $Mode=='UPDATE_ITEM') && check_data($Mode, $selected_id))
{

    if ($Mode == 'ADD_ITEM') 
    {
            $rec_id = add_salary_advance($_POST['employee_code'], $_POST['type_id'],
                                    input_num('salary_advance'), 
                                    $_POST['due_date'], $_POST['comments'], 'N');

            if($rec_id > 0){
                display_notification(_("Salary advance has been added."));
            }
            else{
                display_error(_("Salary advance could not be added."));
            }
    } 
    if ($Mode == 'UPDATE_ITEM') 
    {
            $recs = update_salary_advance($selected_id, $_POST['employee_code'], 
                                    $_POST['type_id'], input_num('salary_advance'), 
                                    $_POST['due_date'], $_POST['comments'], 'U');

            $selected_id = -1;
            
            if($recs == 1){
                display_notification(_("Salary advance has been updated."));
            }
            else{
                display_error(_("Salary advance could not be updated."));
            }
    }
    $Mode = 'RESET';

}

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

if(isset($_POST['pay_salary_advance']))
{
    make_payment($selected_id);
    $selected_id = -1;
}

if ($Mode == 'Delete')
{
        $recs = delete_salary_advance($selected_id, $_POST['employee_code']);
        
        if($recs == 1){
                display_notification(_("Salary advance has been deleted."));
        }
        else{
                display_error(_("Salary advance could not be deleted."));
        }

	$Mode = 'RESET';
}

if ($Mode == 'RESET')
{
	$selected_id = -1;
}

if (isset($_POST['_selected_id_update']) )
{
	$selected_id = $_POST['selected_id'];
	//$Ajax->activate('_page_body');
}

//if (list_updated('employee_code')) 
	$Ajax->activate('_page_body');
//--------------------------------------------------------------------------------------------------

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


        emoplyees_list_cells(_("Select an Employee:"), 'employee_code', null,
	  false, true, check_value('show_inactive'));

br(2);	

    $result = get_salary_advances($_POST['employee_code']);
    
    div_start('price_table');
    
    if (db_num_rows($result) == 0)
    {
    	display_note(_("There are no salary advances created for the selected employee"));
    }
    else
    {
        start_table(TABLESTYLE, "width=60%");

		$th = array(_("Type Name"), _("Amount"), _("Due Date"), _("Comment"), _("Status"),"", "");

        table_header($th);

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

        while ($myrow = db_fetch($result))
        {
            alt_table_row_color($k);

            //label_cell($myrow["id"]);
            label_cell($myrow["type_name"]);
            amount_cell($myrow["salary_advance"]);
            label_cell(sql2date($myrow["due_date"]),"align=center");
            label_cell($myrow["comments"]);
            label_cell($myrow["status_name"]);
                
            if($myrow["status_code"] == "N" || $myrow["status_code"] == "U" || 
                    $myrow["status_code"] == "O"){
                edit_button_cell("Edit".$myrow['id'], _("Edit"));
                delete_button_cell("Delete".$myrow['id'], _("Delete"));
            }
            elseif($myrow["status_code"] == "A"){
                button_cell("Edit".$myrow['id'], _("Edit"), "Pay", ICON_DOC);
                label_cell("");
            }
            else{
                label_cell("");
                label_cell("");
            }
            
            end_row();

            $j++;
            If ($j == 12)
            {
            	$j = 1;
        		table_header($th);
            } //end of page full new headings
        } //end of while loop

        end_table();
    }
    div_end();

//-----------------------------------------------------------------------------------------------
    $_POST['id'] = 0;
    $_POST['salary_advance'] = 0;
    $_POST['due_date'] = "";
    $_POST['comments'] = "";
    $_POST['type_id'] = "";
    
$dec2 = 6;
if ($Mode =='Edit')
{
    $myrow = get_salary_advance_details($selected_id);

    $_POST['id'] = $myrow["id"];
    $_POST['salary_advance'] = $myrow["salary_advance"];
    $_POST['due_date'] = sql2date($myrow["due_date"]);
    $_POST['comments'] = $myrow["comments"];
    $_POST['type_id'] = $myrow["type_id"];
    $_POST['status_code'] = $myrow['status_code'];
    
    hidden('id', $_POST['id']); 
}

br();

hidden('selected_id', $selected_id);

start_table(TABLESTYLE2);

if(isset($_POST['status_code']) && $_POST['status_code'] == "A"){
    label_row("Type:", $_POST['type_id']);
    label_row('Amount:', $_POST['salary_advance']);
    label_row("Due Date:", $_POST['due_date']);
    label_row('Comments:', $_POST['comments']);
}
else{
    value_list_row("Type:", "type_id", "SALARY_ADVANCES", $_POST['type_id']);
    amount_row('Amount:', 'salary_advance', $_POST['salary_advance'], null, null, 2);
    date_row("Due Date:", "due_date", $_POST['due_date']);
    textarea_row('Comments:', 'comments', $_POST['comments'], 35, 2);

    if($selected_id > 0){
        set_focus('salary_advance');
    }
}
end_table(1);

if(isset($_POST['status_code']) && $_POST['status_code'] == "A"){
    submit("pay_salary_advance", "Pay",true, _('Pay Salary Advance'), 'default');
    submit('RESET', _("Cancel"), true, _('Cancel edition'), 'cancel');
}
else{
    submit_add_or_update_center($selected_id == -1, '', 'both');
}

if (!@$_GET['popup'])
{
	end_form();
	end_page(@$_GET['popup'], false, false);
}
?>
