<?php
/**********************************************************************
***********************************************************************/
$page_security = 'SA_PETTY_CASH_EXPENSES_APPROVE';
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_expenses_db.inc");
include_once($path_to_root . "/petty_cash/includes/db/i_owe_you_db.inc");
include_once($path_to_root . "/petty_cash/includes/ui/petty_cash_ui.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/petty_cash_payments_db.inc");
include_once($path_to_root . "/petty_cash/includes/petty_cash_functions.inc");
include_once($path_to_root . "/petty_cash/includes/db/project_floats_db.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/i_owe_you_advances_inquiry_db.inc");
include_once($path_to_root . "/transport/includes/db/vehicles_db.inc");
include_once($path_to_root . "/assets/includes/db/assets_db.inc");
include_once($path_to_root . "/inventory/includes/db/petty_cash_item_receive_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 . "/includes/db/group_companies_db.inc");
include_once($path_to_root . "/reporting/includes/reporting.inc");

$js = '';

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

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


simple_page_mode(true);

page(_($help_context = "Approve I Owe You Expenses"), false, false, "", $js);


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

if (isset($_GET['Updated_ID'])) 
{
	//return;
        
    $trans_no = $_GET['Updated_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();
}

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();
}

if (isset($_GET['BackTo_ID'])) 
{
	//return;
        
    $trans_no = $_GET['BackTo_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();
}

if (isset($_GET['Rejected_ID'])) 
{
	//return;
        
    $trans_no = $_GET['Rejected_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_no = 0;

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

function display_unapproved_expense_batch_ious($batch_no)
{

//    $Ajax->activate('leaves1');
//
//    div_start('leaves1');

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

    $th = array(_("Id"),"Project",_("Employee Name"), _("Type"),
            _("Date"),_("Amount"), "Comment", "Batch No");
    table_header($th);

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


    $q = get_batch_i_owe_yous($batch_no);

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

            //label_cells('',$myrow["id"]);
            label_cells('',$iou_line["id"]);
            label_cells('',$iou_line["project_description"]);
//            label_cells('',$iou_line["task_description"]);
            label_cells('',get_group_company_employee_formatted_long_name($iou_line["company_code"], $iou_line["employee_code"]));
            label_cells('',$iou_line["type_name"]);
            label_cells('',sql2date($iou_line["tran_date"]));
            qty_cell($iou_line["amount"], false, 2);

            label_cells('',$iou_line["comments"]);
            label_cells('',$iou_line["batch_no"],'', "align=center");

//            check_cells('', 'selected_'.$iou_line["id"],0);

        end_row();
        $j++;
        If ($j == 12)
        {
            $j = 1;
            table_header($th);
        }
    }

    end_table(1);
//    div_end();


}

function display_unapproved_expense_batch($batch_no)
{
    global $expense_categories;

    display_heading('Batch #'.$batch_no.' Expenses Details');

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

//    $q = get_unapproved_i_owe_you_batch_expences($batch_no);
    $q = get_batch_i_owe_you_expences($batch_no);

    $th = array("Id", "Expense Category", "Expense Item", "Budget", _("Date"), _("Invoice No"),_("Expense Description"),_
                    ("Req. Amt."), "Document Status", _("Approved Amt."));
    table_header($th);
    
    $j = 1;
    $k=0; 
    $req_total = 0;
    $approved_total = 0;
    while ($myrow = db_fetch($q))
    {

            alt_table_row_color($k);
            
            label_cell($myrow["id"]);
            
            if($myrow["expense_category_id"] > 0){
                label_cell($expense_categories[$myrow["expense_category_id"]]);
            }
            else{
                label_cell('');
            }
            
            $expense_item_name = '';
            switch ($myrow['expense_category_id']) {
                case EC_PETTY_CASH_EXPENSE:
                    $expense_item_name = '';
                    break;
                case EC_STOCK_ITEM_RECEIPT:
                    $link = get_petty_cash_item_receive_str(ST_PETTY_CASH_ITEM_RECEIPT, $batch_no, $myrow["id"], "Receive items");
                    $expense_item_name = $link;
                    break;
                case EC_VEHICLE_MAINTENANCE:
                    $expense_item_name = get_vehicle_formatted_name($myrow["expense_item_id"]);
                    break;
                case EC_UTILITY_ITEM:
                    $utility_item = get_listvalue_by_id($myrow["expense_item_id"]);
                    $expense_item_name = $utility_item['value_name'];
                    break;
                case EC_ASSET_MAINTENANCE:
                    $expense_item_name = get_asset_formatted_name($myrow["expense_item_id"]);
                    break;

                default:
                    break;
            }
//            label_cell($myrow["expense_item_id"]);
            label_cell($expense_item_name);       

            label_cell($myrow["task_description"]);
            label_cell(sql2date($myrow["expence_date"]));
            label_cell($myrow["bill_no"]);
            label_cell($myrow["expence_description"]);
            amount_cell($myrow["amount"]);  
            $req_total += $myrow["amount"];
            
            value_list_cells(null, "document_status_id_".$myrow["id"], "IOU_DOCUMENT_STATUSES", $myrow["document_status_id"], "");
            if($myrow["appr_amt_updated_by"] > 0){
                $approved_amount = $myrow["approved_amount"];
            }
            else{
                $approved_amount = $myrow["amount"];
            }

            amount_cells(null,"approved_amount".$myrow["id"], $approved_amount);  
            
            
//            if($myrow["status_code"] == "A"){
//                amount_cell($myrow["approved_amount"]);
//                label_cell($myrow["status_name"]);
//                label_cell('');
//                $approved_total += $myrow["approved_amount"];
//            }
//            elseif($myrow["status_code"] == "J"){
//                amount_cell($myrow["approved_amount"]);
//                label_cell($myrow["status_name"]);
//                label_cell('');
//            }
//            else{
//                amount_cells(null,"approved_amount".$myrow["id"], $myrow["approved_amount"]);  
//                value_list_code_cells(null, 'expense_approval_status'.$myrow["id"], "RECORD_APPROVAL_STATUS", $myrow["status_code"]);
//                check_cells('', 'selected_'.$myrow["id"],0);
//                $approved_total += $myrow["approved_amount"];
//            }
            
            $approved_total += $approved_amount;

            

	end_row();
	$j++;
//	If ($j == 12)
//	{
//		$j = 1;
//		table_header($th);
//	}
    }
    start_row();
    label_cell("", "colspan=3");
    label_cell("Total", "align=right");
    label_cell(number_format($req_total,2), "align=right");
    label_cell("");
    label_cell(number_format($approved_total,2), "align=right");
    end_row();

    end_table(1);

//    br();


//    div_end();
}

function display_unapproved_expense_iou_batches($batch_no){ 
    global $Ajax;
    
    $Ajax->activate('leaves1');

    div_start('leaves1');
    
//    $q = get_unapproved_i_owe_you_expense_batch_nos();
//    while ($myrow = db_fetch($q))
//    {
//        display_heading2("I Owe You Batch No:".$myrow['batch_no']);
//        br();
//        display_unapproved_expense_batch_ious($myrow['batch_no']);
//        
//        display_unapproved_expense_batch($myrow['batch_no']);
////        br();
//    }
    
        display_heading2("Expenses Batch No:".$batch_no);
        br();
        
        $total_paid = display_batch_i_owe_yous($batch_no, 0);
        
//        display_expense_batch_summary($batch_no);
        
//        display_i_owe_you_batch_expences($batch_no, $total_paid);
        
//        display_unapproved_expense_batch_ious($batch_no);
        display_i_owe_you_batch_header($batch_no, $total_paid);
        br();
        display_unapproved_expense_batch($batch_no);
//        br();
    
        hidden('BatchNo', $batch_no);
        
    div_end();
}




function update_i_owe_you_expences($batch_no, $release_for_approval=false)
{
    $iou_bh = get_i_owe_you_batch_header_record($batch_no);
    $row_state = $iou_bh['row_state'];
    $cae = can_approve_expense($batch_no, $row_state, $release_for_approval);
    if($cae["success"] !== true){
        return $cae;
    }
    
    begin_transaction();
    
    $batch_q = get_batch_i_owe_you_expences($batch_no);

    while ($ex = db_fetch($batch_q))
    {
        $n = update_i_owe_you_expence_approved_amount($ex["id"], $_POST['document_status_id_'.$ex["id"]], input_num('approved_amount'.$ex["id"]));
        if($n !== 1){
            cancel_transaction();
            return array("success" => false, "message" => "Another user has updated  ".$ex["amount"]." or it has been already approved or rejected.");
        }

    }
    //Update batch expense header with approved total
    $approved_total = get_i_owe_you_batch_expenses_approved_total($batch_no);
    $n2 = update_i_owe_you_batch_approved_total($batch_no, $approved_total, $row_state);
    if($n2 !== 1){
        cancel_transaction();
        return array("success" => false, "message" => "Another user has updated this expenses batch.");
    }
    
    commit_transaction();
    
    return array("success" => true, "message" => "Expenses of batch no $batch_no have been updated.");
}


function update_batch_expences_and_release_for_approval($batch_no){

    $iou_msg = update_i_owe_you_expences($batch_no, true);
    if($iou_msg["success"] !== true){
        return $iou_msg;
    }

    $pceh = get_petty_cash_expenses_header_by_batch_no($batch_no);
    if(isset($pceh['id']) && $pceh['id'] > 0){
        $company_code = $pceh['company_code'];
        $employee_code = $pceh['employee_code'];
    }
    else{
        $ioub_result = get_batch_i_owe_yous($batch_no);
        $ioub = db_fetch($ioub_result);
        $company_code = $ioub['company_code'];
        $employee_code = $ioub['employee_code'];
    }
    $iou_apr_msg = release_batch_expenses_for_approval($batch_no, $company_code, $employee_code);
    return $iou_apr_msg; 
    
}


function send_batch_back_to_originator($batch_no)
{
    $cae = can_approve_expense($batch_no);
    if($cae["success"] !== true){
        return $cae;
    }
    
    $batch = get_i_owe_you_batch_header($batch_no);
    $current_user_id = $_SESSION['wa_current_user']->user;
    
    $rd_msg = send_back_to_document_originator(ST_I_OWE_YOU_BATCH, $batch_no, $batch['project_id'],
                                    $batch['next_approval_group_id'], $current_user_id, $batch['row_state'], 
                                    $batch['created_by']);
    
    return $rd_msg;
}

function reject_batch($batch_no)
{
    $cae = can_approve_expense($batch_no);
    if($cae["success"] !== true){
        return $cae;
    }
        
    $batch = get_i_owe_you_batch_header($batch_no);
    $current_user_id = $_SESSION['wa_current_user']->user;
    
    begin_transaction();
    $rd_msg = reject_document(ST_I_OWE_YOU_BATCH, $batch_no, $batch['project_id'],
                    $batch['next_approval_group_id'], $current_user_id, $batch['row_state']);
    
    if($rd_msg['success'] !== true){
        cancel_transaction();
        return $rd_msg;
    }
    
    update_batch_expences_approved($batch_no);
    
    $rbta_msg = remove_iou_batch_iou_task_allocations($batch_no, $current_user_id);
    
    if($rbta_msg['success'] !== true)
    {
        cancel_transaction();
        return array("success" => $rbta_msg['success'], "tran_no" => $batch_no, "message" => $rbta_msg['message']);
    }
        
        
    commit_transaction();
    return $rd_msg;

}


//if (isset($_POST['UpdateData']))
//{
//    update_selected_i_owe_you_expenses();
//    
//    display_notification(_("Insurance claim has been confirmed."));
//}

if(isset($_POST['Update_Batch_Expences'])){
    $uiou = update_i_owe_you_expences($batch_no);
    if($uiou["success"] !== true){
        if(isset($uiou["focus_to"])){
            set_focus($uiou["focus_to"]);
        }
        display_error($uiou["message"]);
    }
    else{
        set_session_variable('iou_batch_messages', $uiou["message"]);
        meta_forward($_SERVER['PHP_SELF'], "Updated_ID=$batch_no");
    }

}

if(isset($_POST['Update_Batch_Expences_Release'])){
    $ubera = update_batch_expences_and_release_for_approval($batch_no);
    if($ubera["success"] !== true){
        display_error($ubera["message"]);
    }
    else{
        set_session_variable('iou_batch_messages', $ubera["message"]);
        meta_forward($_SERVER['PHP_SELF'], "Released_ID=$batch_no");
    }
}


if(isset($_POST['Back_To_Batch_Originator'])){
    $bo = send_batch_back_to_originator($batch_no);
    if($bo["success"] !== true){
        display_error($bo["message"]);
    }
    else{
        set_session_variable('iou_batch_messages', $bo["message"]);
        meta_forward($_SERVER['PHP_SELF'], "BackTo_ID=$batch_no");
    }
}


if (isset($_POST['Reject_Batch_Expences'])){
    $rb = reject_batch($batch_no);
    if($rb["success"] !== true){
        display_error($rb["message"]);
    }
    else{
        set_session_variable('iou_batch_messages', $rb["message"]);
        meta_forward($_SERVER['PHP_SELF'], "Rejected_ID=$batch_no");
    }
}


start_form();

br(2);

display_unapproved_expense_iou_batches($batch_no);

$pceh = get_petty_cash_expenses_header_by_batch_no($batch_no);
if(isset($pceh['id']) && $pceh['id'] > 0){
    $project_id = $pceh['project_id'];
    $company_code = $pceh['company_code'];
    $employee_code = $pceh['employee_code'];
}
else{
    $ioub_result = get_batch_i_owe_yous($batch_no);
    $ioub = db_fetch($ioub_result);
    $project_id = $ioub['project_id'];
    $company_code = $ioub['company_code'];
    $employee_code = $ioub['employee_code'];
}
display_project_float_message($project_id, $company_code, $employee_code);

br(1);
//submit_center('UpdateData', _("Update"), true, false, 'default');

submit_center_first('Update_Batch_Expences', _("Update"), '', 'default');
submit('Update_Batch_Expences_Release', 'Update and Release for Approval', true, '', 'default');
submit_center_last('cancel', _("Cancel"), _("Cancel Edition"), 'cancel');

br();
submit_center_first('Back_To_Batch_Originator', "Back To Originator", '', 'default');
submit_center_last('Reject_Batch_Expences', "Reject", '', 'default');

br();

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