<?php
/**********************************************************************
***********************************************************************/
$page_security = 'SA_I_OWE_YOU_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/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/i_owe_you_expenses_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/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 . "/petty_cash/includes/db/project_floats_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 . "/petty_cash/includes/db/remove_i_owe_you_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 . "/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();
}

page(_($help_context = "I Owe You Batch Expenses Entry"), false, false, "", $js);
//----------------------------------------------------------------------------------------
simple_page_mode(true);

$batch_no = 0;

if (isset($_GET['IouBatchNo']))
{
    $_POST['IouBatchNo'] = $_GET['IouBatchNo'];
}
if(isset($_POST['IouBatchNo']))
{
    $batch_no=$_POST['IouBatchNo'] ;
}
elseif(isset($_POST['iou_id']))
{    
   $batch_no=$_POST['iou_id'] ; 
}

if (isset($_GET['Deleted_ID'])) {
    $trans_no = $_GET['Deleted_ID'];
    $message = get_session_variable('iou_batch_delete_messages');
    clear_session_variable('iou_batch_delete_messages');
    
    display_notification_centered($message);
    hyperlink_no_params("$path_to_root/petty_cash/inquiry/i_owe_you_batch_expenses_inquiry.php", _("Process Another &I Owe You Batch"));
    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);
        
        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/petty_cash/i_owe_you_payments_entry_select.php", _("Make a payment / Complete this batch"), "batch_no=$trans_no");
        
	display_note(print_document_link($trans_no, _("&Print this I Owe You  batch"), true, $trans_type), 0, 0);

	

//	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 check_data($batch_no, $selected_id='-1')
{	

    $batch = get_i_owe_you_batch_header_record($batch_no);
    if(!(in_array($batch['approval_status'], array(AS_NEW, AS_WITH_THE_APPROVER, AS_AWAITING_APPROVAL, AS_BACK_TO_ORIGINATOR))))
    {
        display_error( _("This I Owe You batch status does not allow any changes to its expences."));
        set_focus('batch_task');
        return false;
    }    
    
    if(!is_date($_POST['iou_batch_tran_date']))
    {
        display_error( _("IOU Batch Date entered is not a valid date."));
        set_focus('iou_batch_tran_date');
        return false;
    }
    
    if (!is_date_in_fiscalyear($_POST['iou_batch_tran_date'])) {
        display_error(_("IOU Batch Date entered is not in fiscal year."));         
        set_focus('iou_batch_tran_date');
        return false;        
    }

    $msg = is_accounting_period_open($_POST['iou_batch_tran_date']);
    if ($msg['success'] !== true)
    {
        display_error($msg['message']);  
        set_focus('iou_batch_tran_date');
        return false;        
    }
    
    // ========Fix for unrelated users coming into the expenses entry page and editability checking for the unrelated user 
    // check batch editable only if the batch has expenses
    
    $result = get_batch_i_owe_you_expences($batch_no);
    if(db_num_rows($result) > 0){
        // Validate editability only if batch has any expenses. 
        // First expenses updates the batch creator to its user.
        $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){
            display_error($ced_msg['message']);
            set_focus('batch_task');
            return false;
        }
    }
    

//    $myrow = get_i_owe_you_expence_line($selected_id);
//    if(($myrow['appr_amt_updated_by'] > 0))
//    {
//        display_error( _("Approved amount of this detail has been updated by an authorizer. It can not be updated."));
//        set_focus('batch_task');
//        return false;
//    }
            
    if(!($_POST['expense_category_id'] > 0))
    {
        display_error( _("Please select an expense category."));
        set_focus('expense_category_id');
        return false;
    }
    
    switch ($_POST['expense_category_id']) {
        case EC_VEHICLE_MAINTENANCE:
            if(!($_POST['expense_item_id'] > 0))
            {
                display_error( _("Please select a vehicle."));
                set_focus('expense_item_id');
                return false;
            }
        case EC_ASSET_MAINTENANCE:
            if(!($_POST['expense_item_id'] > 0))
            {    
                display_error( _("Please select an asset."));
                set_focus('amount');
                return false;
            }
        case EC_UTILITY_ITEM:
            if(!($_POST['expense_item_id'] > 0))
            {    
                display_error( _("Please select an utility item."));
                set_focus('amount');
                return false;
            }

        default:
            break;
    }

    if (isset($_POST['expense_category_id']) &&  $_POST['expense_category_id'] == EC_ASSET_MAINTENANCE) {
            $asset_row = get_asset($_POST['expense_item_id']);
            if ($asset_row['type'] == AT_VEHICLE) {
                $message = "Selected asset is a Vehicle. Only the assets of types Fixed Asset and Tool are allowed under this Expense Category.";
                display_error($message);
                set_focus('expense_item_id');
                return false;  
            }
    }
    
    if(!($_POST['expense_type_id'] > 0))
    {
        display_error( _("Please select an expense type."));
        set_focus('expense_type_id');
        return false;
    }
    
    if(!($_POST['batch_task'] > 0))
    {
        display_error( _("Please select a budget."));
        set_focus('batch_task');
        return false;
    }
    
    if(strlen($_POST['bill_no'])==0)
    {
        display_error( _("Invoice number is mandatory."));
        set_focus('bill_no');
        return false;
    }
    
    if(strlen($_POST['expence_description'])==0)
    {
        display_error( _("Expense description is mandatory."));
        set_focus('expence_description');
        return false;
    }
        
    if(!check_num('amount',0))
    {
        display_error( _("Amount entered is not numeric or negative."));
        set_focus('amount');
        return false;
    }        
           
    if(!is_date($_POST['expence_date']))
    {
        display_error( _("Date entered is not a valid date."));
        set_focus('tran_date');
        return false;
    }

    if(input_num('amount') <= 0)
    {        
        display_error( _("The amount should be a positive."));
        set_focus('amount');
        return false;
    }  
  
    $btotal = 0;
    $batch_expenses_total = get_i_owe_you_batch_expenses_total($batch_no, $selected_id);
    $batch_totals = get_i_owe_you_batch_totals($batch_no);
    if(isset($batch_totals['iou_batch_total']) && $batch_totals['iou_batch_total'] > 0){
        $btotal = $batch_totals['iou_batch_total'];
    }
    
    if($batch_expenses_total + input_num('amount') > $btotal)
    {     
        display_error("Expenses total can not be more than I owe You batch total.");
        set_focus('amount');
        return false;
    }
                        
    switch ($_POST['expense_category_id']) {

        case EC_STOCK_ITEM_RECEIPT:
            $items_total = (float)get_petty_cash_stock_items_total_cost_by_source(ST_PETTY_CASH_ITEM_RECEIPT, $batch_no, $selected_id);
            if(input_num('amount') < $items_total)
            {     
                display_error("This line value can not be less than the total value of entered stock items Rs.". number_format($items_total,2).".");
                set_focus('amount');
                return false;
            }

        default:
            break;
    }
                        
    return true;
    
}

//function approve_petty_cash_expense($iou_id)
//{
//    approve_i_owe_you($iou_id, "A");
//}

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

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


if(isset($_POST['Release_Batch_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{
        $cae = can_approve_expense($batch_no);
        if($cae["success"] !== true){
            display_error($cae["message"]);
        }
        else{                    
            $iou_result = get_batch_i_owe_yous($batch_no);
            $iou = db_fetch($iou_result); // Get the first IOU
        
            $rbea = release_batch_expenses_for_approval($batch_no, $iou['company_code'], $iou['employee_code']);
            if($rbea["success"] !== true){
                display_error($rbea["message"]);
            }
            else{
                set_session_variable('iou_batch_messages', $rbea["message"]);
                meta_forward($_SERVER['PHP_SELF'], "Released_ID=$batch_no");
            }
        }
    }
}


if (isset($_POST['Batch_Expenses_Remove'])) {
    $msg = handle_delete_i_owe_you_batch($batch_no);
        if ($msg["success"] !== true) {
            display_error($msg["message"]);
        } else {                    
            set_session_variable('iou_batch_delete_messages', $msg["message"]);
            meta_forward($_SERVER['PHP_SELF'], "Deleted_ID=$batch_no");
        }
}



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

    $iou_bh = get_i_owe_you_batch_header_record($batch_no);
    
    if ($Mode == 'ADD_ITEM')
    {
            begin_transaction();
            $rec_id = 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'), $_POST['expense_category_id'],
                                            $_POST['expense_item_id'], $_POST['project_site_id']);

            update_iou_batch_tran_date($batch_no, date2sql($_POST['iou_batch_tran_date']));
            
            $expense_batchapproved_total = get_i_owe_you_batch_expenses_approved_total($batch_no);

            $n2 = update_i_owe_you_batch_approved_total($batch_no, $expense_batchapproved_total, $iou_bh['row_state']);
            if($n2 !== 1){
                cancel_transaction();
                return array("success" => false, "message" => "Another user has updated this expenses batch.");
            }
            
            
            
            if($rec_id > 0){
                commit_transaction();
                display_notification(_("I owe you expense has been added."));
            }
            else{
                cancel_transaction();
                display_error(_("I owe you  could not be added."));
            }
    } 
    if ($Mode == 'UPDATE_ITEM') 
    {
            begin_transaction();
            $recs = 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'), $_POST['expense_category_id'],
                                            $_POST['expense_item_id'], $_POST['project_site_id']);
            
            update_iou_batch_tran_date($batch_no, date2sql($_POST['iou_batch_tran_date']));
            
            $expense_batchapproved_total = get_i_owe_you_batch_expenses_approved_total($batch_no);

            $n2 = update_i_owe_you_batch_approved_total($batch_no, $expense_batchapproved_total, $iou_bh['row_state']);
            if($n2 !== 1){
                cancel_transaction();
                return array("success" => false, "message" => "Another user has updated this expenses batch.");
            }

            $selected_id = -1;
            
            if($recs == 1){
                commit_transaction();
                display_notification(_("I owe you expense has been updated."));
            }
            else{
                cancel_transaction();
                display_error(_("This I owe you detail has been updated by another user."));
            }
    }
    $Mode = 'RESET';

}

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

if ($Mode == 'Delete')
{
        begin_transaction();
        $del_msg = can_delete_iou_expense($selected_id);
        if($del_msg["success"] !== true){
            display_error($del_msg["message"]);
        }
        else{
            $recs = delete_i_owe_u_expence($selected_id);
            update_iou_batch_tran_date($batch_no);
            if($recs == 1){
                commit_transaction();
                display_notification(_("I Owe You expense has been deleted."));
            }
            else{
                cancel_transaction();
                display_error(_("I Owe You expense could not be deleted."));
            }

            $Mode = 'RESET';
        }
}

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

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

//if(isset($_POST['Approve_Petty_Cash_Expense'])){
//    approve_petty_cash_payment(get_post('iou_id'));
//    approve_i_owe_you_expense($row_id, $approved_amount, $status_code);
//}

    

//if (list_updated('employee_code')) 
	$Ajax->activate('_page_body');
//--------------------------------------------------------------------------------------------------
        
if (!@$_GET['popup'])
	start_form();
 
    global $expense_categories, $Ajax;
//-------------------------------------------------------------------------------------

display_selected_iou_details_for_expenses($batch_no);

display_iou_payments_for_expenses($batch_no);
//-----------------------------------------------------------------------------------------------

div_start('expences_table');


//br();

div_end();

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

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


display_i_owe_you_batch_header($batch_no);

br();

display_heading('Batch '.$batch_no.' Common Expenses');
start_table(TABLESTYLE2, "width=90%");
$expences_iou = get_batch_i_owe_you_expences($batch_no);

$th = array("Expense Category", "Expense Item", "Expense Type", "Budget", _("Date"),_("Invoice No"),_("Description"),_("Job"),_("Amount"), " "," ");
table_header($th);
    
    $j = 1;
    $k = 0; 
    $total = 0;
    while ($myrow = db_fetch($expences_iou))
    {
            alt_table_row_color($k); 
            
            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_I_OWE_YOU_BATCH, $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["expense_type_name"]);
            
            label_cell($myrow["task_description"]);
            label_cell(sql2date($myrow["expence_date"]));
            label_cell($myrow["bill_no"]);
            label_cell($myrow["expence_description"]);
            label_cell($myrow["project_site_description"]);
            amount_decimal_cell($myrow["amount"]);
  
            
//            if($myrow["status_code"] == ""){
//                $status_name = "New";
//            }
//            else{
//                $status_name = $myrow["status_name"];
//            }
//            label_cell($status_name, "align=center");
//            
//            amount_cell($myrow["approved_amount"]);  
            $total += $myrow["amount"];
            
//            if($myrow["status_code"] == "A" || $myrow["status_code"] == "J"){
//                label_cell("");
//                label_cell("");
//            }
//            else{
//            if($myrow["appr_amt_updated_by"] > 0){
//                label_cell("");
//            }
//            else{
//                edit_button_cell("Edit".$myrow['id'], _("Edit"));
//            }
                
            edit_button_cell("Edit".$myrow['id'], _("Edit"));
            
            delete_button_cell("Delete".$myrow['id'], _("Delete"));    
//            }

            end_row();
            $j++;
  
    }
    start_row();
    label_cell(text_bold("Total"), "align=right colspan=8");
    amount_cell($total,true);
    label_cell("", "colspan=2");
    end_row();
    
    

end_table(1);

//br();

div_end();

$batch_header = get_i_owe_you_batch_header($batch_no);
if(is_array($batch_header)){
    if(in_array($batch_header['approval_status'], array(AS_NEW, AS_AWAITING_APPROVAL, AS_WITH_THE_APPROVER, AS_REOPENED, AS_BACK_TO_ORIGINATOR))){
        submit_center_first('Release_Batch_Expenses', _("Release Expense Batch For Approval"), '', 'default');
        submit_center_last('Batch_Expenses_Remove', _("Delete Expense Batch"), false, false, ICON_ESCAPE);
    }
    else{
        br(2);
        $msg = 'For releasing this expense batch for approval, please go to "Approve I Owe You / Petty Cash Expenses".';
        display_note($msg);
    }
}


br(2);

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


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


    isset($_POST['id']) ? $_POST['id'] : 0;
    isset($_POST['expence_date']) ? $_POST['expence_date'] : "";
    isset($_POST['bill_no']) ? $_POST['bill_no'] : "";
    isset($_POST['expence_description']) ? $_POST['expence_description'] : "";   
    isset($_POST['amount']) ? $_POST['amount'] : 0;  
    
    
    if ($Mode =='Edit')
    {
        $myrow = get_i_owe_you_expence_line($selected_id);

        $_POST['id'] = $myrow["id"];  
        $_POST['expense_category_id'] = $myrow["expense_category_id"];  
        $_POST['expense_item_id'] = $myrow["expense_item_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"];

        hidden('id', $_POST['id']); 
        
    }

//    br();

    hidden('selected_id', $selected_id);
    hidden('IouBatchNo', $batch_no);
    //------------------------------------------------------------------------------------
    
    $Ajax->activate('expense_item_id');        
    
    set_post_not_set_date('iou_batch_tran_date', sql2date($batch_header['tran_date']));
    start_table(TABLESTYLE2);
    date_row("IOU Batch Date:", "iou_batch_tran_date");
    end_table(1);
    
    
    start_table(TABLESTYLE2);
    
    $available_expense_categories = $expense_categories; 
//    unset($available_expense_categories[EC_ASSET_MAINTENANCE]); 
    
    custom_values_list_row("Expense Category:", "expense_category_id", $available_expense_categories, null, "Select Expense Category", true);
    
    switch ($_POST['expense_category_id']) {
        case EC_PETTY_CASH_EXPENSE:
            hidden('expense_item_id', 0);
            break;
        case EC_STOCK_ITEM_RECEIPT:
            label_row('','(Save this record first and then open the items receiving screen)');
            hidden('expense_item_id', 0);
            break;
        case EC_VEHICLE_MAINTENANCE:
            vehicles_list_row("Vehicle", 'expense_item_id', null, '');
            break;
        case EC_UTILITY_ITEM:
            value_list_row("Utility Item", 'expense_item_id', "UTILITY_ITEMS", null, '');
            break;
        case EC_ASSET_MAINTENANCE:
            start_row();
            label_cell('Issuing Tool'); 
            echo "<td>";
                echo asset_list('expense_item_id', null, false, true);
            echo "</td>";   
            break;

        default:
            break;
}
    value_list_row("Expense Type:", "expense_type_id", "PETTY_CASH_EXPENSE_TYPES", null, 'Select an expense type');
//    tasks_list_row("Task:", "batch_task", $_POST['project_id'] , null, "Select a task");
    tasks_list_row("Budget:", "batch_task", $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);
    project_sites_list_row("Job:", 'project_site_id', $project_id, null,'');

    end_table(1);

    submit_add_or_update_center($selected_id == -1, '', 'both');

    br();
    
    
    


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