<?php
/**********************************************************************
***********************************************************************/

$page_security = 'SA_PETTY_CASH_EXPENSES_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/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/i_owe_you_expenses_db.inc");
include_once($path_to_root . "/petty_cash/includes/petty_cash_functions.inc");
include_once($path_to_root . "/petty_cash/includes/ui/petty_cash_ui.inc");
include_once($path_to_root . "/payroll/includes/db/employees_db.inc");
include_once($path_to_root . "/projects/includes/db/projects_db.inc");
include_once($path_to_root . "/includes/db/group_companies_db.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 . "/petty_cash/includes/db/petty_cash_expenses_entry_db.inc");
include_once($path_to_root . "/petty_cash/includes/db/project_floats_db.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 = "Petty Cash Expenses Entry"), false, false, "", $js);
//----------------------------------------------------------------------------------------
simple_page_mode(true);


$peh_id = -1;

if(isset($_GET['NewExpense']) && $_GET['NewExpense'] == "Yes"){
    $peh_id = -1;
    clear_session_variable("ST_PETTY_CASH_EXPENSE_pce_no");
}

if(isset($_GET['PCENo']) && $_GET['PCENo'] > 0 ){
    $peh_id = $_GET['PCENo'];
    set_session_variable('ST_PETTY_CASH_EXPENSE_pce_no', $peh_id);    
}

if(get_session_variable("ST_PETTY_CASH_EXPENSE_pce_no") != ""){
    $peh_id = get_session_variable("ST_PETTY_CASH_EXPENSE_pce_no");
}


if (isset($_GET['Released_ID'])) 
{
	//return;
        
    $trans_no = $_GET['Released_ID'];
    $trans_type = ST_I_OWE_YOU_BATCH;
    $message = get_session_variable('iou_batch_messages');
    clear_session_variable('iou_batch_messages');
    
	display_notification_centered($message);
        
//	display_note(print_document_link($trans_no, _("&Print this I Owe You  batch"), true, $trans_type), 0, 0);

	hyperlink_no_params("$path_to_root/petty_cash/approve_i_owe_you_expenses_select.php", _("Approve another &I Owe You  batch"));

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

	display_footer_exit();
}


//$batch = get_i_owe_you_batch_header($batch_no);
//$project_id = $batch['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"]);
//    display_footer_exit();
//    return false;
//}
    

function can_process_pce_line(){
            
    if(!($_POST['batch_task'] > 0))
    {
        $message = "Please select a budget.";
        $set_focus = 'batch_task';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);       
    }
    
    if(!is_date($_POST['expence_date']))
    {
        $message = _("Line Date entered is not a valid date.");
        $set_focus = 'expence_date';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);         
    }
    
    if(!check_num('amount', 0.00000001))
    {
        $message = _("Amount entered should be greater than zero.");
        $set_focus = 'amount';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);      
    }          
          
    if(!(strlen($_POST['expence_description']) > 0))
    {
        $message = _("Expense description can not be empty.");
        $set_focus = 'expence_description';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);         
    }
    
    return array("success" => true, "message" => "");     
}


//function display_petty_cash_expenses_header2($peh_id)
//{
//    global $Refs;
//      
//    if($peh_id > 0){
//        
//        $pce_header = get_petty_cash_expenses_header($peh_id);
//        $_POST['project_id'] = $pce_header['project_id'];
//        
//        if(!isset($_POST['reference'])){
//            $_POST['reference'] = $pce_header['reference'];
//        }
//        
//        if(!isset($_POST['project_description'])){
//            $_POST['project_description'] = $pce_header['project_description'];
//        }
//        
//        if(!isset($_POST['float_id'])){
//            $_POST['float_id'] = $pce_header['float_id'];
//        }
//                       
//        if(!isset($_POST['tran_date'])){
//            $_POST['tran_date'] = sql2date($pce_header['tran_date']);
//        }
//        
//        if(!isset($_POST['comments'])){
//            $_POST['comments'] = $pce_header['comment'];
//        }               
//    }
//    
//    start_table(TABLESTYLE2);
//    
//    text_row("Reference:", 'reference', null, 30, 200);
//    
////    else{
////        ref_row(_("Reference:"), 'reference', '', $Refs->get_next(ST_I_OWE_YOU));
////    }
//     $list_value = get_listvalue_by_code('PETTY_CASH_TYPES', 'PETTY_CASH');
//     hidden('type_id', $list_value['id']);
//    
//     label_row("Type:", $list_value['value_name']);
//    //value_list_row("Type:", "type_id", "PETTY_CASH_TYPES", null, '');
//     
//    
//    if($peh_id > 0){        
//        label_row("Project:", $_POST['project_description']);
//        hidden('project_id', $_POST['project_id']); 
//    }
//    else{
//        project_list_row(_("Project:"), 'project_id', null, _('Select a project'), true);
//    }
//    
////    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);
//       
//    date_row("Date:", "tran_date");
//    textarea_row('Comments:', 'comments', null, 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']]);
//    
//    end_table(1);
//}

function display_petty_cash_expenses_header($peh_id)
{

    if(!isset($_POST['tran_date'])){
        $_POST['tran_date'] = '';
    }
    if(!isset($_POST['header_comments'])){
        $_POST['header_comments'] = '';
    }
    //    $_POST['tran_date'] ="";
    //    $_POST['comments'] ="";
    
    global $approval_statuses, $Refs;

    $dec2 = 6;
    $batch_no = 0;
    //if ($Mode =='Edit')
    $_POST['row_state'] = 0;
    $_POST['approval_status'] = 0;
        
    if($peh_id > 0)
    {
//        $myrow = get_i_owe_you_record($iou_id);
        $myrow = get_petty_cash_expenses_header($peh_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['reference'] = $myrow["reference"];
        $_POST['type_id'] = $myrow["type"];

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

        if(!isset($_POST['group_company_code'])){
        $_POST['group_company_code'] = $myrow["company_code"];
        }

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

        $_POST['tran_date'] = sql2date($myrow["tran_date"]);
        $_POST['header_comments'] = $myrow["comments"];
        $_POST['approval_status'] = $myrow['approval_status'];
        $_POST['float_name'] = $myrow['float_name'];
        $_POST['row_state'] = $myrow["row_state"];
        $batch_no = $myrow["batch_no"];
//        $selected_id = $_POST['ModifyMRNumber'];
    //    hidden('selected_id', $_POST['ModifyMRNumber']); 
    }

    br();

//    hidden('selected_id', $selected_id);

    start_table(TABLESTYLE2);

    if($peh_id > 0){
        ref_row(_("Reference:"), 'reference');
    }
    else{
        ref_row(_("Reference:"), 'reference', '', $Refs->get_next(ST_PETTY_CASH));
    }
//    value_list_row("Type:", "type_id", "PETTY_CASH_TYPES", null, '');
    $list_value = get_listvalue_by_code('PETTY_CASH_TYPES', 'PETTY_CASH');
    hidden('type_id', $list_value['id']);
    label_row("Type:", $list_value['value_name']);
    
    if($peh_id > 0){
        label_row("Project:",$_POST['project_description']);
        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", true);    
    
    if($peh_id > 0){
        label_row("Float:",$_POST['float_name']);
        hidden('float_id', $_POST['float_id']);
    }
    else{
        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:', 'header_comments', $_POST['header_comments'], 35, 2); 
    
    $s = get_project_trans_view_str(ST_APPROVAL_LOG, $batch_no."&source_type_id=".ST_I_OWE_YOU_BATCH, "Approval Status");
    label_row($s,$approval_statuses[$_POST['approval_status']]);
    
    hidden("ModifyMRNumber", $peh_id);
    hidden('row_state', $_POST['row_state']);

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



function display_petty_cash_expenses_edit_controls($selected_id, $Mode){
       
    global $Ajax;
    
    $Ajax->activate('_page_body');
     
    if ($Mode =='Edit')
    {
        $myrow = get_i_owe_you_expence_line($selected_id);

        $_POST['id'] = $myrow["id"];  
        $_POST['expense_type_id'] = $myrow["expense_type_id"];  
        $_POST['batch_task'] = $myrow["task_id"];  
        $_POST['expence_date'] = sql2date($myrow["expence_date"]);
        $_POST['bill_no'] = $myrow["bill_no"];        
        $_POST['expence_description'] = $myrow["expence_description"];
        $_POST['amount'] = $myrow["amount"];       
        $_POST['iou_batch_no'] = $myrow["iou_batch_no"];         
       
    }
 

    div_start('billing_items');
    start_table(TABLESTYLE2);     
        value_list_row("Expense Type:", "expense_type_id", "PETTY_CASH_EXPENSE_TYPES", null, 'Select an expense type');
        tasks_list_row("Budget:", "batch_task", $_POST['project_id'], null, "Select a budget");
        date_row("Date:", "expence_date");
        text_row("Invoice No.:", "bill_no", null,30,50);
        textarea_row("Description:", "expence_description",null,30,3);
        amount_row('Amount:', 'amount', input_num('amount'), null, null, 2);
    
    end_table(1); 
    div_end();
}


function clear_data()
{
    $_POST['id'] = 0;
    $_POST['expence_date'] = "";
    $_POST['bill_no'] = "";
    $_POST['expence_description'] = "";   
    $_POST['amount'] = 0;  
}

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


function can_process_pce_header($peh_id)
{
    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(!$_POST['project_id'] > 0)
    {
        $message = "Please select a Project.";
        $set_focus = 'project_id';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);         
    }

    
    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(!($peh_id > 0) && $_POST['float_id'] == -1)
    {
        $message = "Please select a Float.";
        $set_focus = 'float_id';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);    
    }
    
    if(!is_date($_POST['tran_date']))
    {
        $message = "Entered date is not a valid date.";
        $set_focus = 'tran_date';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);         
    }
    
    if (!is_date_in_fiscalyear($_POST['tran_date'])) {
        $message = (_("The entered date is not in fiscal year."));         
        $set_focus = 'tran_date';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);    
    }
        
    $msg = is_accounting_period_open($_POST['tran_date']);
    if ($msg['success'] !== true)
    {
        $message = ($msg['message']);         
        $set_focus = 'tran_date';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);    
    }
    
    $ref_msg = reference_exists($_POST['reference'], ST_PETTY_CASH, $peh_id);
    if($ref_msg)        
    {
        $message = $ref_msg;
        $set_focus = ('reference');
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);         
    }
        
    if($peh_id > 0){
        $pceh = get_petty_cash_expenses_header($peh_id);
        $batch_no = $pceh['batch_no'];
        $batch = get_i_owe_you_batch_header($batch_no);

//        if(!($batch['approval_status'] == AS_NEW || $batch['approval_status'] == AS_AWAITING_APPROVAL || $batch['approval_status'] == AS_WITH_THE_APPROVER))
        if(!(in_array($batch['approval_status'], array(AS_NEW, AS_AWAITING_APPROVAL, AS_WITH_THE_APPROVER, AS_BACK_TO_ORIGINATOR))))
        {
            $message = ( _("This expense batch status does not allow any changes to its details."));
            $focus_to = ('batch_task');
            return array("success" => false, "focus_to" => $focus_to, "message" => $message);
        }
        
        $current_user_id = $_SESSION['wa_current_user']->user;
        $ced_msg = can_edit_document(ST_I_OWE_YOU_BATCH, $batch['project_id'], $batch['next_approval_group_id'] , $current_user_id, $batch['created_by'], $batch_no);
        if($ced_msg['success'] !== true){
            return array("success" => false, "focus_to" => '', "message" => $ced_msg['message']);
        }
    }
    
    return array("success" => true, "message" => "");      
}

 
function save_petty_cash_expenses_header(&$peh_id)
{    
    global $Refs;
    
    if($peh_id > 0){
       
        $n = update_petty_cash_expenses_header($peh_id, $_POST['reference'], $_POST['type_id'],
                                            $_POST['project_id'],  
                                            $_POST['group_company_code'], $_POST['employee_code'],
                                            $_POST['tran_date'], $_POST['header_comments']);
        
        if($n != 1){
            return array("success" => false, 'trans_no' => $peh_id, "message" => "Another user has updated Petty Cash Expense $peh_id.");
        }
        else{
            return array("success" => true, 'trans_no' => $peh_id, "message" => "Petty Cash Expense $peh_id has been updated.");
        }
    }
    else{
        $batch_no = get_iou_next_batch_no();

        add_i_owe_you_batch_header($batch_no, $_POST['project_id'], $_POST['float_id'], 0, 0, date2sql($_POST['tran_date'])); 
        
        update_iou_batch_tran_date($batch_no, date2sql($_POST['tran_date']));
        
        $peh_id = add_petty_cash_expenses_header($batch_no, $_POST['reference'], $_POST['type_id'], $_POST['project_id'], 
                                        $_POST['float_id'], $_POST['group_company_code'], $_POST['employee_code'],
                                        $_POST['tran_date'], $_POST['header_comments']);

                                                
        if($peh_id > 0){
            $Refs->save(ST_PETTY_CASH, $peh_id, $_POST['reference']);
            set_session_variable("ST_PETTY_CASH_EXPENSE_pce_no", $peh_id);
            return array("success" => true, 'trans_no' => $peh_id, "message" => "Petty Cash Expense $peh_id has been created.");
        }else{
            return array("success" => false, 'trans_no' => '', "message" => "Could not save Petty Cash Expense header.");
        }
    }
}


function save_petty_cash_expenses_line($selected_id, $peh_id, $batch_no)
{        
    if($selected_id > 0){
        
        $n = update_i_owe_you_expence($selected_id, $_POST['expense_type_id'], $_POST['batch_task'], $_POST['expence_date'], 
                                    $_POST['bill_no'], $_POST['expence_description'], input_num('amount'), EC_PETTY_CASH_EXPENSE, 0, 0);
         
        if($n == 1){
            return array("success" => true, 'trans_no' => $peh_id, "message" => "Selected petty cash expense record has been updated.");
        }
        else{
            return array("success" => false, 'trans_no' => $peh_id, "message" => "Another user has updated this petty cash expense.");
        }
       
    }else{    
        $k = add_i_owe_you_expence($batch_no, $_POST['expense_type_id'], $_POST['batch_task'], $_POST['expence_date'], 
                                $_POST['bill_no'], $_POST['expence_description'],
                                input_num('amount'), EC_PETTY_CASH_EXPENSE, 0, 0);
        
        if($k > 0){
            return array("success" => true, 'trans_no' => $peh_id, "message" => "A new Petty Cash expense has been added.");
        }
        else{
            return array("success" => false, 'trans_no' => $peh_id, "message" => "Could not add Petty Cash expense.");
        }

    }
  
}

function save_petty_cash_expense($selected_id, &$peh_id)
{
           
    $h_validate = can_process_pce_header($peh_id);
    if($h_validate["success"] !== true){
        return $h_validate;
    } 
    
    $line_msg = can_process_pce_line();
    if($line_msg["success"] !== true){
        return $line_msg;
    }
    
    begin_transaction();
    
    $h_msg = save_petty_cash_expenses_header($peh_id);
    if($h_msg['success'] !== true){
        cancel_transaction();
        return $h_msg;
    }
    
    $pceh = get_petty_cash_expenses_header($peh_id);
    $batch_no = $pceh['batch_no'];
    $iou_bh = get_i_owe_you_batch_header_record($batch_no);
    
    $l_msg = save_petty_cash_expenses_line($selected_id, $peh_id, $batch_no);
    if($l_msg['success'] !== true){
        cancel_transaction();
        return $l_msg;
    }
    
    
    $batch_expenses_total = get_i_owe_you_batch_expenses_total($batch_no, -999);
    $n = update_i_owe_you_batch_approved_total($batch_no, $batch_expenses_total, $iou_bh['row_state']);
    if($n != 1){
        cancel_transaction();
        return array("success" => false, 'trans_no' => $peh_id, "message" => "Another user has updated this expense batch.");
    }
    
    $k = update_petty_cash_expense_header_total($peh_id, $batch_expenses_total, $pceh['row_state']);
    if($k != 1){
        cancel_transaction();
        return array("success" => false, 'trans_no' => $peh_id, "message" => "Another user has updated this petty cash expense.");
    }
    
    commit_transaction();
    
    return array("success" => true, "focus_to" => "", "message" => $l_msg['message']);  
    
    
}


function display_petty_cash_expenses($peh_id)
{
    $pceh = get_petty_cash_expenses_header($peh_id);
    
    $expences_iou = get_batch_i_owe_you_expences($pceh['batch_no']);
    
    display_heading('Expenses');
    start_table(TABLESTYLE2, "width=90%");
    

    $th = array(_("ID"), _("Expense Type"),  _("Budget"), _("Date"),_("Invoice No"),_("Description"),_("Amount"), " "," ");
    table_header($th);
    
    $j = 1;
    $k = 0; 
    $total = 0;
    while($myrow = db_fetch($expences_iou))
    {
        alt_table_row_color($k);

        label_cell($myrow['id']);
        label_cell($myrow["expense_type_name"]);
        label_cell($myrow["task_description"]);
        label_cell(sql2date($myrow["expence_date"]));
        label_cell($myrow["bill_no"]);
        label_cell($myrow["expence_description"]);
        amount_decimal_cell($myrow["amount"]);  
 
        $total += $myrow["amount"]; 
              
        edit_button_cell("Edit".$myrow['id'], _("Edit"));
        delete_button_cell("Delete".$myrow['id'], _("Delete"));    

        end_row();
        $j++;  
    }
    
    start_row();
        label_cell(null, "colspan=5");
        label_cell("Total", "align=right");
        label_cell(number_format($total, 2), "align=right");
    end_row();

    end_table(1);

}

function delete_petty_cash_expense($selected_id, $peh_id)
{
    $recs = delete_i_owe_u_expence($selected_id);
    if($recs>0){
        $pceh = get_petty_cash_expenses_header($peh_id);
        $batch_no = $pceh['batch_no'];
        $iou_bh = get_i_owe_you_batch_header_record($batch_no);
        $batch_expenses_total = get_i_owe_you_batch_expenses_total($batch_no, -999);
        update_i_owe_you_batch_approved_total($batch_no, $batch_expenses_total, $iou_bh['row_state']);
        return array("success" => true, "message" => "Petty Cash Expense has been deleted.");
    }
    else{
        return array("success" => false, "message" => "Could not delete Petty Cash Expense.");
    }
}


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


if(isset($_POST['Release_Petty_Cash_Expenses'])){
    
    if(strlen($_POST['expence_description']) > 0 || strlen($_POST['bill_no']) > 0 || input_num('amount') > 0)
    {
        display_error( _("There is an unsaved expense. Please save it before releasing for approval."));
        set_focus('expence_description');
    }
    else{
        $pceh = get_petty_cash_expenses_header($peh_id);
        $batch_no = $pceh['batch_no'];
        $cae = can_approve_expense($batch_no);
        if($cae["success"] !== true){
            display_error($cae["message"]);
        }
        else{
            $rbea = release_batch_expenses_for_approval($batch_no, $_POST['group_company_code'], $_POST['employee_code']);
            if($rbea["success"] !== true){
                display_error($rbea["message"]);
            }
            else{
                set_session_variable('iou_batch_messages', $rbea["message"]);
                clear_session_variable("ST_PETTY_CASH_EXPENSE_pce_no");
                meta_forward($_SERVER['PHP_SELF'], "Released_ID=$batch_no");
            }
        }
    }
}


if(isset($_POST['Approve_Petty_Cash_Expense'])){
    approve_petty_cash_expense(get_post('iou_id'));
}
    

if(isset($_POST['Save_Petty_Cash_Expenses_Header'])){

    $h_validate = can_process_pce_header($peh_id);
    if($h_validate["success"] !== true){
        display_error($h_validate['message']); 
        set_focus($h_validate['focus_to']);
    } 
    else{
        begin_transaction();
        $speh_msg = save_petty_cash_expenses_header($peh_id);
        if($speh_msg["success"] !== true){
            cancel_transaction();
            display_error($h_validate['message']); 
        }
        else{
            commit_transaction();
            display_notification($speh_msg['message']); 
        }
    }
}


if(isset($_POST['Add_Petty_Cash_Expenses']) || isset($_POST['Update_Petty_Cash_Expenses'])){
           
    $spce_msg = save_petty_cash_expense($selected_id, $peh_id);
    if($spce_msg["success"] !== true){
        display_error($spce_msg['message']); 
        if(isset($spce_msg['focus_to'])){
            set_focus($spce_msg['focus_to']);
        }
    }
    else{
        display_notification($spce_msg['message']); 
        $Mode = 'RESET';
    } 
 
} 


if ($Mode == 'Delete')
{
        $dpce_msg = delete_petty_cash_expense($selected_id, $peh_id);
        if($dpce_msg["success"] !== true){
            display_error($dpce_msg['message']); 
        }
        else{
            display_notification($dpce_msg['message']); 
            $Mode = 'RESET';
        } 

}

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


if (isset($_POST['cancel'])){
    $Mode = 'RESET';
    $selected_id = -1;
    unset($_POST);
}  

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




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

echo "<br>";
div_start('expences_table');




div_end();

br();
   

display_petty_cash_expenses_header($peh_id);

br(1);

if(($peh_id > 0)){
    submit_center_first('Save_Petty_Cash_Expenses_Header', _("Save"), '', 'default'); 
    br(2);
    $pceh = get_petty_cash_expenses_header($peh_id);
    if(in_array($pceh['approval_status'], array(AS_NEW, AS_BACK_TO_ORIGINATOR, AS_REOPENED))){
        submit_center_first('Release_Petty_Cash_Expenses', "Release for Approval", '', 'default');
    }else{
        br(2);
        $msg = 'For releasing this petty cash expense for approval please go to "Approve I Owe You / Petty Cash Expenses".';
        display_note($msg);
    }
//    submit_center_last('Release_Petty_Cash_Expenses', "Release for Approval", '', 'default');	
}
br(2);

display_petty_cash_expenses($peh_id);

display_petty_cash_expenses_edit_controls($selected_id, $Mode);

//  submit_center_first('Release_Batch_Expenses', _("Release Expense Batch For Approval"), '', 'default');

if($selected_id > 0){
    submit_center_first('Update_Petty_Cash_Expenses', _("UPDATE"), '', 'default');
    hidden('selected_id', $selected_id);
    submit_center_last('cancel', _("Cancel"), _("Cancel Edition"), 'cancel');
}else{
    submit_center_first('Add_Petty_Cash_Expenses', _("ADD"), '', 'default');   
    submit_center_last('cancel', _("Cancel"), _("Cancel Edition"), 'cancel');
}
  
 


    
end_form();

end_page(@$_GET['popup'], false, false);






?>
