<?php
/**********************************************************************
***********************************************************************/
$page_security = 'SA_I_OWE_YOU_REQUESTS_ENTRY';
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 . "/petty_cash/includes/db/i_owe_you_db.inc");
include_once($path_to_root . "/petty_cash/includes/db/approve_i_owe_you_enties_db.inc");
include_once($path_to_root . "/petty_cash/includes/db/project_floats_db.inc");
include_once($path_to_root . "/petty_cash/includes/petty_cash_functions.inc");

include_once($path_to_root . "/includes/approval_functions.inc");
include_once($path_to_root . "/includes/project_cost_functions.inc");
include_once($path_to_root . "/reporting/includes/reporting.inc");
//include_once($path_to_root . "/includes/references.inc");

include_once($path_to_root . "/includes/ui/ui_lists_group_companies.inc");
include_once($path_to_root . "/includes/db/group_companies_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 = "I Owe You / Petty Cash Entry"), false, false, "", $js);

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

$iou_id = -1;
if (isset($_GET['ModifyMRNumber']))
{
	$_POST['ModifyMRNumber'] = $_GET['ModifyMRNumber'];
    set_session_variable("ST_I_OWE_YOU_iou_no", $_POST['ModifyMRNumber']);
}

if (isset($_GET['NewOrder']))
{
    $_POST['ModifyMRNumber'] = -1;
    set_session_variable("ST_I_OWE_YOU_iou_no", $_POST['ModifyMRNumber']);
} 

if (isset($_POST['ModifyMRNumber']) && $_POST['ModifyMRNumber'] > 0){
    $iou_id = $_POST['ModifyMRNumber'];
}
else{
    $iou_id = get_session_variable("ST_I_OWE_YOU_iou_no");
    
}
//if(isset($_POST['ModifyMRNumber'])){
//    $iou_id = $_POST['ModifyMRNumber'];
//}


if (isset($_GET['IOU_ID'])) 
{
	//return;
        
    $trans_no = $_GET['IOU_ID'];
	$trans_type = ST_I_OWE_YOU;
    $message = get_session_variable('iou_messages');
    clear_session_variable('iou_messages');
    set_session_variable('ST_I_OWE_YOU_iou_no', -1);
    
	display_notification_centered($message);
        
	display_note(print_document_link($trans_no, _("&Print this I Owe You"), true, $trans_type), 0, 0);

	hyperlink_no_params("$path_to_root/petty_cash/i_owe_you.php", _("Create another &I Owe You"));

//	hyperlink_params("$path_to_root/admin/attachments.php", _("Add an Attachment"), "filterType=$trans_type&trans_no=$trans_no");

	display_footer_exit();
}

function can_process_iou($iou_id = '-1', &$row_state = 0)
{	
    if($iou_id > 0){
        $iou = get_i_owe_you_record($iou_id);
        $row_state = $iou['row_state'];
        if(!($iou['approval_status'] == AS_NEW || $iou['approval_status'] == AS_WITH_THE_APPROVER || 
                $iou['approval_status'] == AS_AWAITING_APPROVAL || $iou['approval_status'] == AS_REOPENED)){
            $message = ("This I Owe You status does not allow further updating.");
            $set_focus = '';
            return array("success" => false, "focus_to" => $set_focus, "message" => $message);
        }

        $ced_msg = can_edit_document(ST_I_OWE_YOU, $iou['project_id'], $iou['next_approval_group_id'], 
                            $_SESSION['wa_current_user']->user, $iou['created_by']);
        if($ced_msg['success'] !== true){
            $message = $ced_msg['message'];
            $set_focus = '';
            return array("success" => false, "focus_to" => $set_focus, "message" => $message);
        }
    }
        
    if(!($iou_id > 0)){
        if (strlen($_POST['ref']) == 0)
        {
            $message = "Reference is mandatory.";
            $set_focus = 'ref';
            return array("success" => false, "focus_to" => $set_focus, "message" => $message);
        }
//        if (!is_new_reference($_POST['ref'], ST_I_OWE_YOU)) 
        $ref_msg = reference_exists($_POST['ref'], ST_I_OWE_YOU);
        if($ref_msg)
        {
            display_error($ref_msg);
            set_focus('ref');
            return false;
        }
    }
    
    if (!(strlen(get_post('group_company_code')) > 0))
   	{
        $message = "Please select a company.";
        $set_focus = 'group_company_code';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);
   	}
    
    
    if (!isset($_POST['employee_code']) || strlen($_POST['employee_code']) <= 1)
   	{
        $message = "Please select an employee.";
        $set_focus = 'employee_code';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);
   	}
    
    if (get_post('project_id') == -1)
    {
        $message = "Please select a project.";
        $set_focus = 'project_id';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);
    }
    
    
    if (get_post('float_id') == -1)
    {
        $message = "Please select a float.";
        $set_focus = 'float_id';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);
    }
    
    if ($_POST['type_id'] == -1)
    {
        $message = "Please select a type.";
        $set_focus = 'type_id';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);
    }
        
    if (!check_num('total_amount',0.001))
   	{
        $message = "Amount entered has to be numeric and positive.";
        $set_focus = 'total_amount';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);
   	}

    if (!is_date($_POST['tran_date']))
   	{
        $message = "Date entered is not a valid date.";
        $set_focus = 'tran_date';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);
   	}
   
    return array("success" => true, "message" => "");
    
}

function can_release_iou($iou_id)
{

    $detail_total = get_i_owe_you_details_sum($iou_id);

    if ($detail_total != input_num('total_amount'))
   	{
        $message = "Total Amount and the total of amounts entered in the details do not match.";
        $set_focus = 'amount';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);
   	}
    
    return array("success" => true, "message" => "");
    
}


function add_iou()
{
    global $Refs;
    
    $cd = can_process_iou(-1);
    if($cd["success"] !== true) 
    {
        return $cd;
    }
    
    begin_transaction();
    $iou_id = add_i_owe_you_header($_POST['ref'], $_POST['type_id'],  $_POST['project_id'], 
                                    $_POST['float_id'], $_POST['group_company_code'], $_POST['employee_code'], input_num('total_amount'),                                   
                                    $_POST['tran_date'], $_POST['comments'], AS_NEW);
    
    if(!($_POST['boq_group_id'] > 0)){
        $boq_group_id = 0;
    }
    else{
        $boq_group_id = $_POST['boq_group_id'];
    }
    $q = get_i_owe_you_details_new(-1, $_POST['project_id'], $boq_group_id);
    while ($iou_line = db_fetch($q))
    {
        if(input_num("amount_".$iou_line["task_id"]) > 0){
            add_i_owe_you_detail($iou_id,  $iou_line['task_id'], 
                                input_num("amount_".$iou_line["task_id"]), $_POST['comments_'.$iou_line["task_id"]]);
        }
    }

    if($iou_id > 0){
        $Refs->save(ST_I_OWE_YOU, $iou_id, $_POST['ref']);
        commit_transaction();
        set_session_variable("ST_I_OWE_YOU_iou_no", $iou_id);
        return array("success" => true, "trans_no" => $iou_id, "message" => "I Owe You $iou_id has been added.");
    }
    else{
        cancel_transaction();
        return array("success" => false, "message" => "I Owe You could not be added.");
    }
}

function update_iou($iou_id)
{
    $header_row_state = get_post('row_state');
    $cd = can_process_iou($iou_id, $header_row_state);
    if($cd["success"] !== true) 
    {
        return $cd;
    }
    
    begin_transaction();
    $recs = update_i_owe_you_header($iou_id, $_POST['float_id'], $_POST['group_company_code'], $_POST['employee_code'], input_num('total_amount'),
                                    $_POST['type_id'], $_POST['tran_date'], $_POST['comments'], 
                                    $header_row_state);
    
    if($recs == 1){
        if(!($_POST['boq_group_id'] > 0)){
            $boq_group_id = 0;
        }
        else{
            $boq_group_id = $_POST['boq_group_id'];
        }
        $q = get_i_owe_you_details_new($iou_id, $_POST['project_id'], $boq_group_id);
        while ($iou_line = db_fetch($q))
        {
            if(input_num("amount_".$iou_line["task_id"]) > 0){
                if($iou_line['row_state'] === null ){
                    add_i_owe_you_detail($iou_id, $iou_line['task_id'], 
                                        input_num("amount_".$iou_line["task_id"]), $_POST['comments_'.$iou_line["task_id"]]);
                }
                else{
                    $un = update_i_owe_you_detail($iou_line['id'], input_num("amount_".$iou_line["task_id"]),
                                        $iou_line['task_id'], $_POST['comments_'.$iou_line["task_id"]],
                                        $iou_line['row_state']);
                    if($un != 1){
                        $recs = 0;
                        break;
                    }
                }
            }
            elseif(input_num("amount_".$iou_line["task_id"]) == 0 && $iou_line['id'] > 0){
                $dn = delete_i_owe_you_detail($iou_line['id'], $iou_line['row_state']);
                if($dn != 1){
                    $recs = 0;
                    break;
                }
            }
        }
    }
    
    if($recs == 1){
        commit_transaction();
        return array("success" => true, "trans_no" => $iou_id, "message" => "I Owe You $iou_id has been updated.");
    }
    else{
        cancel_transaction();
        return array("success" => false, "message" => "I Owe You $iou_id could not be updated.");
    }
}


function release_iou_for_approval($iou_id){
    
    $current_user_id = $_SESSION['wa_current_user']->user;
    
    $mr_details = get_i_owe_you_details($iou_id);
    $task_costs_summary = array();
    while ($myrow = db_fetch($mr_details))
    {
//        $a['row_id'] = $myrow['id'];
//        $a['task_id'] = $myrow['task_id'];
//        $a['amount'] = $myrow['amount'];
//        $task_costs_summary[] = $a;
     
        add_to_task_cost($task_costs_summary, $myrow['task_id'], $myrow['amount'], $myrow['amount'], $myrow['amount']);
    }
        
    get_task_cost_details($task_costs_summary);
//    $task_costs_summary = calculate_task_remaining_totals($mr_details_array);
    
    begin_transaction();
    
    $iou = get_i_owe_you_record($iou_id);

//    add_to_task_cost($task_costs_summary, $iou['task_id'], $iou['amount'], $iou['amount'], $iou['amount']);
    
    $info = approve_document(ST_I_OWE_YOU, $iou_id, $iou['project_id'], $task_costs_summary, 
                                        $iou['next_approval_group_id'], $current_user_id, $iou['row_state'], $iou['created_by']);
    if($info['success'] !== true)
    {
        cancel_transaction();
        return array("success" => $info['success'],"trans_no" => $iou_id, "message" => $info['message']);
    }

    if($info['approval_status'] == AS_APPROVED)
    {            
        $apc_msg = allocate_to_tasks(ST_I_OWE_YOU, $iou_id, 
                                    $task_costs_summary, $current_user_id);
        if($apc_msg['success'] !== true)
        {
            cancel_transaction();
            return array("success" => $apc_msg['success'], "trans_no" => $iou_id, "message" => $info['message']);
        }
    }
    
    commit_transaction();
    return array("success" => true, "trans_no" => $iou_id, "message" => $info['message']);
}


function add_iou_and_release_for_approval(&$Mode){

    $iou_msg = add_iou();
    if($iou_msg["success"] !== true){
       return $iou_msg;        
    }
    
    $iou_id = $iou_msg["trans_no"];
    
    $criou_msg = can_release_iou($iou_id);
    if($criou_msg["success"] !== true){
        return $criou_msg;
    }
    
    $Mode = 'RESET';    
 
    $iou_apr_msg = release_iou_for_approval($iou_id);
    return $iou_apr_msg;
}

function update_iou_and_release_for_approval(&$Mode, $iou_id){

    $iou_msg = update_iou($iou_id);
    if($iou_msg["success"] !== true){
        return $iou_msg;
    }
    
    $criou_msg = can_release_iou($iou_id);
    if($criou_msg["success"] !== true){
        return $criou_msg;
    }
    
    $Mode = 'RESET';

    $iou_apr_msg = release_iou_for_approval($iou_id);
    return $iou_apr_msg;
}

function send_iou_back_to_originator(&$Mode, $iou_id)
{
    $boiou = can_process_iou($iou_id, $row_state);
    if($boiou["success"] !== true){
        return $boiou;
    }
    
    $iou = get_i_owe_you_record($iou_id);
    $current_user_id = $_SESSION['wa_current_user']->user;
    
    $rd_msg = send_back_to_document_originator(ST_I_OWE_YOU, $iou_id, $iou['project_id'],
                                    $iou['next_approval_group_id'], $current_user_id, $iou['row_state'], 
                                    $iou['created_by']);
    
    return array("success" => true, "trans_no" => $iou_id, "message" => $rd_msg['message']);
}

function reject_iou(&$Mode, $iou_id)
{
    $riou = can_process_iou($iou_id, $row_state);
    if($riou["success"] !== true){
        return $riou;
    }
    
    $iou = get_i_owe_you_record($iou_id);
    $current_user_id = $_SESSION['wa_current_user']->user;
    
    $rd_msg = reject_document(ST_I_OWE_YOU, $iou_id, $iou['project_id'],
                    $iou['next_approval_group_id'], $current_user_id, $iou['row_state']);
    
    return array("success" => true, "trans_no" => $iou_id, "message" => $rd_msg['message']);

}

function display_i_owe_you_details($iou_id)
{
    $result = get_i_owe_you_details2($iou_id);
    div_start('saved_iou_details');

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

    $th = array("Id","BOQ Item Group", "Budget Name", "Amount", "Comments");
    table_header($th);

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

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

        //label_cells('',$myrow["id"]);
        label_cells('',$iou_line["id"]);
        
        if($iou_line["boq_group_id"] > 0){
            label_cells('',"[".$iou_line["boq_group_code"]."] - ".$iou_line["boq_group_description"]);
        }
        else{
            label_cells('',"No BOQ item group");
        }
        label_cells('',$iou_line["task_description"]);
        amount_decimal_cell($iou_line["amount"]);
        label_cells('',$iou_line["comments"]);
        
        $iou_total += $iou_line["amount"];
    }
    
    start_row();
        label_cell("Total", "colspan=3 align=right");
        amount_cell($iou_total, true);
    end_row();
    
    end_table(1);
    div_end();
}


function display_i_owe_you_edit_controls($iou_id, $project_id, $boq_group_id = 0)
{
    global $Ajax;
    
    if(!($boq_group_id > 0)){
        $boq_group_id = 0;
    }
    
    $Ajax->activate('iou_details');

    $result = get_i_owe_you_details_new($iou_id, $project_id, $boq_group_id);
    div_start('iou_details');

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

    $th = array("Id","Budget Name",_("Budget Value"), _("Available"),  "Amount", "Comments");
    table_header($th);

    $k=0; //row colour counter

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

        //label_cells('',$myrow["id"]);
        label_cells('',$iou_line["id"]);
        label_cells('',$iou_line["description"]);
        amount_decimal_cell($iou_line["budget"]);
//        amount_decimal_cell($iou_line["budget_allocated"]);
//        amount_decimal_cell($iou_line["budget_used"]);

        amount_decimal_cell($iou_line["budget"] - $iou_line["budget_allocated"] - $iou_line["budget_used"]);
        
//        $_POST["required_date_".$iou_line["task_id"]] = $iou_line["required_date"];
//        date_cells(null, "required_date_".$iou_line["task_id"]);
        
        if(!isset($_POST["amount_".$iou_line["task_id"]])){
            $_POST["amount_".$iou_line["task_id"]] = $iou_line["amount"];
        }
        if(!($_POST["amount_".$iou_line["task_id"]] > 0)){
            $_POST["amount_".$iou_line["task_id"]] = 0.00;
        }
        amount_cells(null, "amount_".$iou_line["task_id"]);
        
        text_cells(null, "comments_".$iou_line["task_id"], $iou_line["comments"], 30,500);
    }

    end_table(1);
    div_end();
}


function display_iou_header($iou_id)
{
    global $approval_statuses, $Refs;
    if(!isset($_POST['amount'])){
        $_POST['amount'] = 0;
    }
    if(!isset($_POST['tran_date'])){
        $_POST['tran_date'] = '';
    }
    if(!isset($_POST['comments'])){
        $_POST['comments'] = '';
    }


    $dec2 = 6;
    //if ($Mode =='Edit')
    $_POST['row_state'] = 0;
    $_POST['approval_status'] = 0;
        
    if($iou_id > 0)
    {
        $myrow = get_i_owe_you_record($iou_id);

        $project_id = $myrow['project_id'];    
        $user_id = $_SESSION['wa_current_user']->user;
        $cap = can_access_project($project_id, $user_id);
        if($cap['success'] !== true) 
        {
            display_error($cap["message"]);
            set_focus('project_id');
            display_footer_exit();
            exit;
        }

        $_POST['id'] = $myrow["id"];
        $_POST['ref'] = $myrow["reference"];
        $_POST['type_id'] = $myrow["type"];

        if(!isset($_POST['project_id'])){
            $_POST['project_id'] = $myrow["project_id"];
        }
        $_POST['project_name'] = $myrow["project_name"];
        $_POST['float_id'] = $myrow["float_id"];

        $_POST['group_company_code'] = $myrow["company_code"];

        if(!isset($_POST['employee_code'])){
            $_POST['employee_code'] = $myrow["employee_code"];  
        }
        $_POST['total_amount'] = $myrow["amount"];
        $_POST['tran_date'] = sql2date($myrow["tran_date"]);
        $_POST['comments'] = $myrow["comments"];
        $_POST['approval_status'] = $myrow['approval_status'];

        $_POST['row_state'] = $myrow["row_state"];
        $selected_id = $_POST['ModifyMRNumber'];
    //    hidden('selected_id', $_POST['ModifyMRNumber']); 
    }

    br();

    

    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{
        if($iou_id > 0){
            label_row("Reference:", $_POST['ref']);
        }
        else{
            ref_row(_("Reference:"), 'ref', '', $Refs->get_next(ST_I_OWE_YOU));
        }

    //    value_list_row("Type:", "type_id", "PETTY_CASH_TYPES", null, '');
        $list_value = get_listvalue_by_code('PETTY_CASH_TYPES', 'I_OWE_YOU');
        hidden('type_id', $list_value['id']);
        label_row("Type:", $list_value['value_name']);

        //family_members_list_row("Family Member:", "family_member_id", $_POST['employee_code'], null, '');
        if($iou_id > 0){
            label_row("Project:",$_POST['project_name']);
            hidden('project_id', $_POST['project_id']);
        }
        else{
            project_list_row(_("Project:"), 'project_id', null, _('Select a project'), true);
        }
        if(!(isset($_POST['employee_code']) && strlen($_POST['employee_code']) > 1)){
            if($_POST['project_id'] > 0 ){
                $project_float = get_project_float_by_project_id($_POST['project_id']);
                if($project_float){
                    $_POST['group_company_code'] = $project_float['company_code'];
                    $_POST['employee_code'] = $project_float['employee_code'];                           
                }
            }
        }

        group_companies_list_row("Company:", 'group_company_code', null, false, true);

        group_company_employees_simple_list_row(_("Select an Employee:"), 'employee_code', get_post('group_company_code'),'', null, "Select an employee", false);    

        petty_cash_floats_list_row('Float', 'float_id',null, "Select a float");

        amount_row('Total Amount:', 'total_amount', null, null, null, 2);
        //hidden('amount', $_POST['amount']);

        date_row("Date:", "tran_date", $_POST['tran_date']);
        textarea_row('Comments:', 'comments', $_POST['comments'], 35, 2); 

        $s = get_project_trans_view_str(ST_APPROVAL_LOG, $iou_id."&source_type_id=".ST_I_OWE_YOU, "Approval Status");
        label_row($s,$approval_statuses[$_POST['approval_status']]);

        hidden("ModifyMRNumber", $iou_id);
        hidden('row_state', $_POST['row_state']);

    //    if($selected_id > 0){
    //        set_focus('type_id');
    //    }
    //}
    end_table(1);
    
    if($_POST['project_id'] > 0 ){
        display_project_float_message($_POST['project_id'], $_POST['group_company_code'], $_POST['employee_code']);
    }
}

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

    if(isset($_POST['Add_IOU'])){
        $aiou = add_iou();
        if($aiou["success"] === true){
            $Mode = 'RESET';
    //        set_session_variable('iou_messages', $aiou["message"]);
    //        meta_forward($_SERVER['PHP_SELF'], "IOU_ID=".$aiou["trans_no"]);  
            $iou_id = get_session_variable("ST_I_OWE_YOU_iou_no");
            display_notification("IOU ".$aiou["trans_no"]." has been created.");
        }
        else{
            if(isset($aiou["focus_to"])){
                set_focus($aiou["focus_to"]);
            }
            display_error($aiou["message"]);
        }
    } 
    
 
if(isset($_POST['Update_IOU'])){
    $uiou = update_iou($iou_id, $selected_id);
    if($uiou["success"] === true){
//        $Mode = 'RESET';
//        $selected_id = -1;
//        set_session_variable('iou_messages', $uiou["message"]);
//        meta_forward($_SERVER['PHP_SELF'], "IOU_ID=".$uiou["trans_no"]); 
        display_notification("IOU ".$uiou["trans_no"]." has been updated.");
    }
    else{
        if(isset($uiou["focus_to"])){
            set_focus($uiou["focus_to"]);
        }
        display_error($uiou["message"]);
    }

}

if(isset($_POST['Add_IOU_Release'])){
    $aiour = add_iou_and_release_for_approval($Mode);
    if($aiour["success"] !== true){
        if(isset($aiour["focus_to"])){
            set_focus($aiour["focus_to"]);
        }
        display_error($aiour["message"]);
    }
    else{
        $Mode = 'RESET';
        $selected_id = -1;
        $iou_id = get_session_variable("ST_I_OWE_YOU_iou_no");
        set_session_variable('iou_messages', $aiour["message"]);
        meta_forward($_SERVER['PHP_SELF'], "IOU_ID=".$aiour["trans_no"]); 
    }
}


if(isset($_POST['Update_IOU_Release'])){
    $uiour = update_iou_and_release_for_approval($Mode, $iou_id);
    if($uiour["success"] !== true){
        if(isset($uiour["focus_to"])){
            set_focus($uiour["focus_to"]);
        }
        display_error($uiour["message"]);
    }
    else{
        $Mode = 'RESET';
        $selected_id = -1;
        set_session_variable('iou_messages', $uiour["message"]);
        meta_forward($_SERVER['PHP_SELF'], "IOU_ID=".$uiour["trans_no"]); 
    }
}


if(isset($_POST['Back_To_IOU_Originator'])){
    $sioub = send_iou_back_to_originator($Mode, $iou_id);
    if($sioub["success"] !== true){
        if(isset($sioub["focus_to"])){
            set_focus($sioub["focus_to"]);
        }
        display_error($sioub["message"]);
    }
    else{
        $Mode = 'RESET';
        $selected_id = -1;
        set_session_variable('iou_messages', $sioub["message"]);
        meta_forward($_SERVER['PHP_SELF'], "IOU_ID=".$sioub["trans_no"]); 
    }
}


if (isset($_POST['Reject_IOU'])){
    $riou = reject_iou($Mode, $iou_id);
    if($riou["success"] !== true){
        if(isset($riou["focus_to"])){
            set_focus($riou["focus_to"]);
        }
        display_error($riou["message"]);
    }
    else{
        $Mode = 'RESET';
        $selected_id = -1;
        set_session_variable('iou_messages', $riou["message"]);
        meta_forward($_SERVER['PHP_SELF'], "IOU_ID=".$riou["trans_no"]); 
    }
} 
//--------------------------------------------------------------------------------------------------

if ($Mode == 'Delete')
{
        $recs = delete_i_owe_u($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();
}
      

display_iou_header($iou_id);

br(1);

hidden('selected_id', $selected_id);

//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(!isset($_POST['ModifyMRNumber']), '', 'both');
//}

display_i_owe_you_details($iou_id, $_POST['project_id']);

start_table(TABLESTYLE2);
project_boq_item_groups_list_row("BOQ Group", "boq_group_id", $_POST['project_id'], null, "Select a BOQ Item Group", true);
end_table(1);

display_i_owe_you_edit_controls($iou_id, $_POST['project_id'], $_POST['boq_group_id']);

if($iou_id > 0)
{
    submit_center_first('Update_IOU', _("Update"), '', 'default');
    submit('Update_IOU_Release', 'Update and Release for Approval', true, '', 'default');
    submit_center_last('cancel', _("Cancel"), _("Cancel Edition"), 'cancel');
    
    br();
    submit_center_first('Back_To_IOU_Originator', "Back To Originator", '', 'default');
    submit_center_last('Reject_IOU', "Reject", '', 'default');
}
else
{
    submit_center_first('Add_IOU', _("Add I Owe You"), '', 'default');
    submit('Add_IOU_Release', 'Add and Release for Approval', true, '', 'default');
    submit_center_last('cancel', _("Cancel"), _("Cancel Edition"), 'cancel');
}

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

?>
