
<?php
/**********************************************************************
    Copyright (C) FrontAccounting, LLC.
	Released under the terms of the GNU General Public License, GPL, 
	as published by the Free Software Foundation, either version 3 
	of the License, or (at your option) any later version.
    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  
    See the License here <http://www.gnu.org/licenses/gpl-3.0.html>.
***********************************************************************/
$page_security = 'SA_BANKACCOUNT';
$path_to_root = "../../..";
include_once($path_to_root . "/includes/session.inc");
add_access_extensions();
page(_($help_context = "Bank transaction types"));

include_once($path_to_root . "/includes/ui.inc");
include_once($path_to_root . "/modules/Kvcodes_importexport/includes/kvcodes.inc");

global $payment_person_types;
if(!defined('PT_BKTRANS'))
		define('PT_BKTRANS',count_array($payment_person_types)+1);

simple_page_mode(true);
//----------------------------------------------------------------------------------------------------
global $banks_list_array;
function banks_list_array(){
	global $path_to_root,$banks_list_array;
    $banks_list_array =array();
    $dir=$path_to_root . "/modules/Kvcodes_importexport/includes/bank_templates";
    $bank_templates = scandir($dir);
    

    foreach ($bank_templates as $key => $bank_template) {
        if($bank_template =="."|| $bank_template == "..")
            continue;
        $file =fopen($dir."/".$bank_template, "r");
        $line =0;
        $counter=1;
        while(! feof($file)){
            if($counter >5){
                break;
            }
            $line =fgets($file);
            if(strpos($line,'$bank_name') !== false){
                
                $string_array = explode('"',$line);     
                $banks_list_array[pathinfo($bank_template, PATHINFO_FILENAME)]=$string_array[1];
                break;
            }
            $counter ++;
        }

       fclose($file);
    }
}

function banks_list_row($label,$name, $selected_id=null, $all_option=false){
	global $banks_list_array;
    
    if($banks_list_array){
        $options =array('spec_option'=> $all_option?_($all_option):$all_option,
        'spec_id' => -1,
    	'selected_id'=>$selected_id);
        array_selector_row($label,$name, null, $banks_list_array,$options);
    }else{
        display_error("There is no bank template available !");
    }
    
}

function kv_payment_person_types_list($name, $selected_id=null, $submit_on_change=false)
{
	global $payment_person_types;
	$items = array();
	$new_payment_person_types=$payment_person_types;

	$new_payment_person_types[PT_BKTRANS]="Bank Transfer";
	foreach ($new_payment_person_types as $key=>$type)
	{
		if ($key == PT_MISC ||$key == PT_CUSTOMER||$key == PT_SUPPLIER||$key == PT_BKTRANS)
			$items[$key] = $type;
	}		
	return array_selector($name, $selected_id, $items, 
		array( 'select_submit'=> $submit_on_change ) );
}

function kv_payment_person_types_list_cells($label, $name, $selected_id=null, $related=null)
{
	if ($label != null)
		echo "<td>$label</td>\n";
	echo "<td>";
	echo kv_payment_person_types_list($name, $selected_id, $related);
	echo "</td>\n";
}

function kv_payment_person_types_list_row($label, $name, $selected_id=null, $related=null)
{
	echo "<tr><td class='label'>$label</td>";
	kv_payment_person_types_list_cells(null, $name, $selected_id, $related);
	echo "</tr>\n";
}

banks_list_array();
function can_process()
{
	if (strlen($_POST['keyword']) == 0)
	{
		display_error(_("The Key cannot be empty."));
		set_focus('sales_type');
		return false;
	}
	if ($_POST['bank_name'] == -1)
	{
		$_POST['bank_name']=null;
	}

	if($_POST['pay_type'] !=-1){
		if($_POST['pay_type'] ==PT_CUSTOMER && ($_POST['person_id'] ==-1 || $_POST['person_id'] =='')){
			display_error(_("Please select the customer!"));
			return false;
		}
		if($_POST['pay_type'] ==PT_SUPPLIER && ($_POST['person_id'] ==-1 || $_POST['person_id'] =='')){
			display_error(_("Please select the supplier!"));
			return false;
		}

		if($_POST['pay_type'] ==PT_MISC)
			$_POST['person_id']=0;
		if(!isset($_POST['person_id']))
			$_POST['person_id']=0;
		if($_POST['person_id'] <0  || $_POST['person_id'] ==''){
			$_POST['person_id']=0;
		}
	}else{
		$_POST['pay_type']=-1;
		$_POST['person_id']=0;
	}
	return true;
}

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

if ($Mode=='ADD_ITEM' && can_process())
{
	Insert('kv_bank_trans_settings',array('bank_name'=>$_POST['bank_name'],'keyword'=>$_POST['keyword'],'min_price'=>input_num('min_price'),'max_price'=>input_num('max_price'),'negative_only'=>check_value('negative_only'),'pay_type'=>$_POST['pay_type'],'person_id'=>$_POST['person_id']));
	display_notification(_('New bank transaction type has been added'));
	$Mode = 'RESET';
}

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

if ($Mode=='UPDATE_ITEM' && can_process())
{
	Update('kv_bank_trans_settings',array('id'=>$selected_id),array('bank_name'=>$_POST['bank_name'],'keyword'=>$_POST['keyword'],'min_price'=>input_num('min_price'),'max_price'=>input_num('max_price'),'negative_only'=>check_value('negative_only'),'pay_type'=>$_POST['pay_type'],'person_id'=>$_POST['person_id']));
	display_notification(_('Selected bank transaction type has been updated'));
	$Mode = 'RESET';
}

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

if ($Mode == 'Delete')
{
	Delete('kv_bank_trans_settings',array('id'=>$selected_id));
	display_notification(_('Selected bank transaction type has been deleted'));

	$Mode = 'RESET';
}

if ($Mode == 'RESET')
{
	$selected_id = -1;
	unset($_POST);
}
//----------------------------------------------------------------------------------------------------
if(list_updated('pay_type')){
	$_POST['person_id']=-1;
	$Ajax->activate('form');
}
div_start('form');
start_form();
start_table(TABLESTYLE, "width='80%'");

$th = array (_('Bank name'),_("Pay type"),_("From"),_('Keyword'), _('Minimum price'), _('Maximum price'), _('In/Out'), '','');
table_header($th);
$k = 0;
$result= GetALL("kv_bank_trans_settings");
if(!empty($result)){
	foreach ($result as $myrow){
		if($myrow['bank_name']){
			if($myrow['pay_type'] ==PT_BKTRANS){
				$action =$myrow["negative_only"] ? _('From')." :- ":_('To')." :- ";
				label_cell($action.$banks_list_array[$myrow["bank_name"]]);
			}else{
				label_cell($banks_list_array[$myrow["bank_name"]]);
			}
		}
		else
			label_cell("");

		if($myrow['pay_type'] ==PT_MISC)
			label_cell("Miscellaneous");
		elseif($myrow['pay_type'] ==PT_SUPPLIER)
			label_cell("Supplier");
		elseif($myrow['pay_type'] ==PT_CUSTOMER)
			label_cell("Customer");
		elseif($myrow['pay_type'] ==PT_QUICKENTRY)
			label_cell("Quick Entry");
		elseif($myrow['pay_type'] ==PT_BKTRANS)
			label_cell("Bank Transfer");
		else
			label_cell("");

		if($myrow['pay_type'] ==PT_SUPPLIER)
			label_cell(GetSingleValue('suppliers',"supp_ref",array('supplier_id'=>$myrow['person_id'])));
		elseif($myrow['pay_type'] ==PT_CUSTOMER)
			label_cell(GetSingleValue('debtors_master',"debtor_ref",array('debtor_no'=>$myrow['person_id'])));
		elseif($myrow['pay_type'] ==PT_QUICKENTRY)
			label_cell(GetSingleValue('quick_entries',"description",array('id'=>$myrow['person_id'])));
		elseif($myrow['pay_type'] ==PT_BKTRANS){
			$action =$myrow["negative_only"] ? _('To')." :- ":_('From')." :- ";
			label_cell($action.GetSingleValue('bank_accounts',"bank_account_name" ,array('id' => $myrow['person_id'])));
		}
		else
			label_cell("");

		label_cell($myrow["keyword"]);
		if($myrow["min_price"] !=0)
			label_cell($myrow["min_price"]);
		else
			label_cell("");
		if($myrow["max_price"] !=0)
			label_cell($myrow["max_price"]);
		else
			label_cell("");
		label_cell($myrow["negative_only"] ? _('Out'):_('In'), 'align=center');
	 	edit_button_cell("Edit".$myrow['id'], _("Edit"));
	 	delete_button_cell("Delete".$myrow['id'], _("Delete"));
		end_row();
	}
}
end_table();

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

 if (!isset($_POST['tax_included']))
	$_POST['tax_included'] = 0;
 if (!isset($_POST['base']))
	$_POST['base'] = 0;

start_table(TABLESTYLE2);

if ($selected_id != -1)
{

 	if ($Mode == 'Edit') {
		$myrow = GetRow('kv_bank_trans_settings',array('id'=>$selected_id));

		$_POST['bank_name']  = $myrow["bank_name"];
		$_POST['keyword']  = $myrow["keyword"];
		$_POST['pay_type']  = $myrow["pay_type"];
		$_POST['person_id']  = $myrow["person_id"];
		$_POST['min_price']  = number_format2($myrow["min_price"],4);
		$_POST['max_price']  = number_format2($myrow["max_price"],4);
		$_POST['negative_only']  =$myrow["negative_only"];
	}
	hidden('selected_id', $selected_id);
}

banks_list_row('Select bank','bank_name',isset($_POST['bank_name'])?$_POST['bank_name']:null,"Select a bank");
kv_payment_person_types_list_row(_("From:"),
		 'pay_type', get_post('pay_type'), true,_("Select Pay type"));
switch ($_POST['pay_type']){
	case PT_SUPPLIER :
		supplier_list_row(_("Supplier:"), 'person_id', null, _("Select supplier"), true, false, true);
		break;
	case PT_CUSTOMER :
		customer_list_row(_("Customer:"), 'person_id', null, _("Select customer"), true, false, true);
		break;

	case PT_QUICKENTRY :
		quick_entries_list_row(_("Type").":", 'person_id', null, QE_DEPOSIT, true);
		break;
	case PT_BKTRANS :
		 bank_accounts_list_row(_("From/To Account:"), 'person_id', null, true);
		break;	
}
text_row_ex(_("Keyword").':', 'keyword', 30);
amount_row(_("Minimum price").':', 'min_price', null, null, null, 4);
amount_row(_("Maximum price").':', 'max_price', null, null, null, 4);
check_row(_("Negative only").':', 'negative_only', get_post('negative_only'));

end_table(1);

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

end_form();
div_end();
end_page();



?>