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

$page_security = 'SA_PETTY_CASH_DIRECT_PAYMENTS';
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/petty_cash_floats_db.inc");
include_once($path_to_root . "/petty_cash/includes/db/i_owe_you_db.inc");
include_once($path_to_root . "/petty_cash/includes/db/petty_cash_float_adjustments_db.inc");
include_once($path_to_root . "/petty_cash/includes/ui/petty_cash_ui.inc");
include_once($path_to_root . "/includes/approval_functions.inc");
include_once($path_to_root . "/reporting/includes/reporting.inc");
include_once($path_to_root . "/petty_cash/includes/db/petty_cash_payments_db.inc");
include_once($path_to_root . "/transport/includes/db/vehicle_running_chart_entry_db.inc");
include_once($path_to_root . "/transport/includes/db/vehicle_allocation_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 Direct Payments"));
//----------------------------------------------------------------------------------------
simple_page_mode(true);

if (isset($_GET['Added_ID'])) 
{
	//return;
        
    $trans_no = $_GET['Added_ID'];
	$trans_type = ST_PETTY_CASH_DIRECT_PAYMENTS;


	display_notification_centered("Petty cash Direct Payment $trans_no has been created.");
        
	display_note(print_document_link($trans_no, _("&Print this Direct Payment"), true, $trans_type), 0, 0);

	hyperlink_no_params("$path_to_root/petty_cash/petty_cash_direct_payments.php", _("Create another &Direct Payment"));

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

	display_footer_exit();
}


function check_data()
{        

    if(!($_POST['float_id'] > 0))
    {          
        display_error("Please select a Petty cash float.");
        set_focus("float_id");
        return false;
    }  
   
    $user_id = $_SESSION['wa_current_user']->user;
    $msg = check_petty_cash_float_access($_POST['float_id'], $user_id);
    if($msg['success'] !== true){
        display_error($msg['message']);
        set_focus("float_id");
        return false;
    }  

    if(!is_date($_POST['payment_date']))
    {        
        display_error("Entered date is not a valid date.");
        set_focus('payment_date');
        return false;
    }        
    
    if (!is_date_in_fiscalyear($_POST['payment_date'])) {
        display_error(_("The entered date is not in fiscal year.")); 
        set_focus('payment_date');
        return false;        
    }

    $msg = is_accounting_period_open($_POST['payment_date']);
    if ($msg['success'] !== true)
    {
        display_error($msg['message']); 
        set_focus('payment_date');
        return false;        
    }
    
    if (!($_POST['expense_source_type'] > 0)) 
    {
        display_error(_('Please select an  source.'));
        set_focus('expense_source_type');
        return false;
    } 
    

    if($_POST['expense_source_type'] == ST_VEHICLE_ALLOCATION){
        if (!($_POST['vehicle_allocation_id'] > 0)) 
        {
            display_error(_('Please select a vehicle allocation.'));
            set_focus('vehicle_allocation_id');
            return false;
        }
        
        if (!(check_num('payment_amount', 0.001))) 
        {
            display_error(_('Payment amount should be numeric and positive.'));
            set_focus('payment_amount');
            return false;
        }
        
        $vehicle_allocation = get_vehicle_allocation($_POST['vehicle_allocation_id']);
        if ($vehicle_allocation['payment_source_no'] > 0) 
        {
            display_error(_("An advance payment of Rs. ".$vehicle_allocation['paid_amount']." has been already done for the selected vehicle allocation."));
            set_focus('vehicle_allocation_id');
            return false;
        }        
    }
    
    if($_POST['expense_source_type'] == ST_VEHICLE_RUNNING_CHART ){
        if (!($_POST['supplier_id'] > 0)) 
        {
            display_error(_('Please select a Supplier.'));
            set_focus('supplier_id');
            return false;
        }
        
        if (!($_POST['running_chart_entry_no'] > 0)) 
        {
            display_error(_('Please select a running chart entry.'));
            set_focus('running_chart_entry_no');
            return false;
        }
        
        if (!(check_num('due_amount', 0.001))) 
        {
            display_error(_('Payment amount should be numeric and positive.'));
            set_focus('due_amount');
            return false;
        }
        
        $vrc_entry = get_vehicle_running_chart_entry($_POST['running_chart_entry_no']);
        if ($vrc_entry['payment_source_no'] > 0) 
        {
            display_error(_('A payment has ben already made for the selected Running Chart Entry.'));
            set_focus('running_chart_entry_no');
            return false;
        }
        
        if ($vrc_entry['inv_no'] > 0) 
        {
            display_error(_('Selected Running Chart Entry has been added in the Supplier Transport Invoice '.$vrc_entry['inv_no']));
            set_focus('running_chart_entry_no');
            return false;
        }
    }
    
    if(!(strlen($_POST['receiver_name']) > 0)){
        display_error(_("Please enter receiver's name."));
        set_focus('receiver_name');
        return false;        
    }
    
    return true;
}


//function add_i_owe_you_payment($selected_id)
//{   
//    global $Refs;
//    
//    $cd = check_data($selected_id);
//    if($cd["success"] !== true) 
//    {
//        display_error($cd["message"]);
//        return false;
//    }
//
//    $amount = input_num('amount');
//    if($_POST['is_return'])
//    {        
//      $amount *= -1;
//    }    
//       
//    begin_transaction();
//    $rec_id = add_petty_cash_float_adjustment($_POST['reference'], $_POST['is_return'],$_POST['float_id'], $_POST['payment_date'], $amount, $_POST['comment'] );
//    if($rec_id > 0){
//        add_to_petty_cash_float(ST_PETTY_CASH_FLOAT_ADJ, $rec_id,$_POST['float_id'], $amount, $_POST['payment_date']);
//        $Refs->save(ST_PETTY_CASH_FLOAT_ADJ, $rec_id, $_POST['reference']);
//        commit_transaction();
//        meta_forward($_SERVER['PHP_SELF'], "Added_ID=$rec_id");
//        return true;
//    }
//    else{
//        cancel_transaction();
//        display_error("Petty Cash Float Adjustment could not be added.");
//        return false;
//    }
//}


function save_petty_cash_direct_payment()
{
    if($_POST['expense_source_type'] == ST_VEHICLE_ALLOCATION){
       $expense_source = ST_VEHICLE_ALLOCATION;
       $payment_amount = input_num('payment_amount');
    }else{
       $expense_source = ST_VEHICLE_RUNNING_CHART;
       $payment_amount = input_num('due_amount');
    }
         
    
    $payment_id = add_i_owe_you_payment(0, $_POST['payment_date'], $payment_amount, $_POST['comment'], 
                                        0, $_POST['float_id'], $expense_source,
                                        $_POST['receiver_name'], $_POST['receiver_nic'], $_POST['receiver_contact_nos']);
    
    $n1 = release_i_owe_you_payment(0, '', $payment_id );
    if(!($n1==1)){
        return array("success"=>false, "message" => "Another user has updated the Payment.");
    }
    
    add_to_petty_cash_float(ST_PETTY_CASH_DIRECT_PAYMENTS, $payment_id, $_POST['float_id'], -$payment_amount, $_POST['payment_date']);
    
     
    switch ($_POST['expense_source_type']) {
        case ST_VEHICLE_RUNNING_CHART:
            $n2 = update_vehicle_running_chart_payment_source($_POST['running_chart_entry_no'], ST_PETTY_CASH_DIRECT_PAYMENTS, $payment_id, input_num('supplier_charge'));
            if(!($n2===1)){
                return array("success"=>false, "message" => "Another user has updated the Vehicle Running Chart Entry.");
            }
            if($_POST['advance_paid_vehicle_allocation_id'] > 0){
                $n3 = update_vehicle_allocation_settled_vrc_entry_no($_POST['advance_paid_vehicle_allocation_id'], $_POST['running_chart_entry_no']);
                if(!($n3===1)){
                    return array("success"=>false, "message" => "Another user has updated the Vehicle Allocation record.");
                }
            }
            break;
        case ST_VEHICLE_ALLOCATION:
            $n2 = update_vehicle_allocation_payment_source($_POST['vehicle_allocation_id'], ST_PETTY_CASH_DIRECT_PAYMENTS, $payment_id, $payment_amount);
            if(!($n2==1)){
                return array("success"=>false, "message" => "Another user has updated the Vehicle Allocation.");
            }
            break;

        default:
            break;
    }
    return array("success"=>true, "trans_no"=> $payment_id, "message" => "Petty cash direct payment $payment_id has been created.");        
}


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

if (isset($_POST['Add_Make_Payment']) && check_data($selected_id)) 
{ 
    begin_transaction();
    $spcdp_msg = save_petty_cash_direct_payment();
    if($spcdp_msg['success'] !== true){
        cancel_transaction();
        display_error($spcdp_msg['message']);
    }
    else{
        commit_transaction();
        //display_notification($spcdp_msg['message']);
        $Mode = 'RESET';
        meta_forward($_SERVER['PHP_SELF'], "Added_ID=".$spcdp_msg['trans_no']);
    }
}

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

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

//$i_owe_you = display_i_owe_you_header($iou_id);
br();

//display_petty_cash_float_adjustments();
//-----------------------------------------------------------------------------------------------

function display_petty_cash_direct_payment_edit_controls()
{
//    $_POST['id'] = 0;
//    $_POST['reference'] = "";
//    $_POST['float_id'] = "";
//    $_POST['is_return'] = ""; 
//    $_POST['payment_date'] ="";
//    $_POST['amount'] = "";
//    $_POST['comment'] ="";  
         

    start_table(TABLESTYLE2);
    

    petty_cash_floats_list_row('Petty Cash Float:', 'float_id', null, 'Select Float', false);
    date_row("Date:", "payment_date");        
    direct_petty_cash_payment_expense_sources_list_row("Expense Source:", 'expense_source_type', null, false, true);
    
       
    if($_POST['expense_source_type'] == ST_VEHICLE_ALLOCATION){
        unpaid_vehicle_allocations_list_row("Vehicle Allocation:", 'vehicle_allocation_id', null, false, true);
        $v_allo = get_vehicle_allocation($_POST['vehicle_allocation_id']);
            $v_allo_amount = 0;
            if (isset($v_allo['id']) && $v_allo['id'] > 0) {
                $v_allo_amount = $v_allo['amount'];
            }
        
        label_row("Amount:", number_format($v_allo_amount, 2));
        amount_row("Payment Amount:", 'payment_amount');
       
    }

    if($_POST['expense_source_type'] == ST_VEHICLE_RUNNING_CHART){
        supplier_list_row("Supplier:", "supplier_id", null, false, true);
        unpaid_vehicle_running_chart_entries_list_row("Running Chart Entry:", 'running_chart_entry_no', $_POST['supplier_id'], null, false, true);
        
        $estimated_amount = '';
        $vrc_entry = get_vehicle_running_chart_entry($_POST['running_chart_entry_no']);    
            if (isset($vrc_entry['id']) && $vrc_entry['id'] > 0) {
                $estimated_amount = number_format($vrc_entry['cost'],2);
            }
        label_row('Estimated Amount:', $estimated_amount);
        amount_row("Supplier Charge:", 'supplier_charge');
        
        advance_paid_vehicle_allocations_list_row("Advance Paid Vehcle Allocation:", 'advance_paid_vehicle_allocation_id', null, '', true);
        $advance_paid_va = get_vehicle_allocation($_POST['advance_paid_vehicle_allocation_id']);  
        $advance_amount = 0;
        if($advance_paid_va){
            $advance_amount = $advance_paid_va['paid_amount'];
        }
        label_row('Advance Payment Amount:', number_format($advance_amount,2));
        
        $due_amount = input_num('supplier_charge') - $advance_amount;
        label_row('Due Amount:', number_format($due_amount,2));
        hidden("due_amount", $due_amount);
    }
    

    text_row("Receiver's Name:", 'receiver_name', null, 45, 200);
    text_row("Receiver's NIC:", 'receiver_nic', null, 10, 15);
    text_row("Receiver's Contact Nos:", 'receiver_contact_nos', null, 25, 50);
    
    textarea_row("Comment:", "comment", null, 30,3);
    end_table(1);

    br();
//    submit_add_or_update_center($selected_id == -1, '', 'both');
//    br();
    
    submit_center_first('Calculate', _("Calculate"), '', 'default');
    submit_center_last('Add_Make_Payment', _("Make Payment"), '', 'default');
    
}


display_petty_cash_direct_payment_edit_controls();


br();

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


?>
