<?php
/**********************************************************************
***********************************************************************/
$page_security = 'SA_GENERATE_SALARY_BANK_FILE';

$path_to_root="..";
include_once($path_to_root . "/includes/session.inc");
include_once($path_to_root . "/includes/common_functions.inc");
include_once($path_to_root . "/includes/ui.inc");
include_once($path_to_root . "/payroll/includes/db/bank_file_db.inc");
include_once($path_to_root . "/payroll/includes/db/payroll_inquiry_db.inc");
//include_once($path_to_root . "/payroll/includes/db/employees_db.inc");


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


$bank_file_path = $path_to_root.'/company/'.user_company()."/bank_files/";

if (!file_exists($bank_file_path))
{
    create_folder_index_file($bank_file_path);
}

$account_info = array();
$account_info['account_name'] = "SAW Engineering";
$account_info['account_number'] = "56010011888";
$account_info['bank_code'] = "7083";
$account_info['branch_code'] = "056";
$account_info['tran_code'] = "223";

if (isset($_GET['AddedID'])) 
{
	$trans_no = $_GET['AddedID'];
	$file_name = 'hnb.txt';

	display_notification_centered(_("Bank data file ".$file_name." has been downloaded"));
}
    
if (get_post('download')) {
	if (get_post('backups')) {
		//download_file(BACKUP_PATH . clean_file_name(get_post('backups')));
        
        $bank_file_path_name = $bank_file_path . clean_file_name(get_post('backups'));
        download_file($bank_file_path_name);
        //sleep(30);
        unlink($bank_file_path_name);
        //Header('Location: '.$_SERVER['PHP_SELF']);
//Exit();
//        meta_forward($_SERVER['PHP_SELF'], "AddedID=hnb.txt");
        exit;
        
        
		
	} else
		display_error(_("Select the bank file first."));
}

page(_($help_context = "Generate Bank File"), false, false, '', '');

//check_paths($bank_file_path);
//
//function check_paths($bank_file_path)
//{
//	if (!file_exists($bank_file_path)) {
//		display_error (_("Backup paths have not been set correctly.") 
//			._("Please contact System Administrator.")."<br>" 
//			. _("cannot find backup directory") . " - " . $bank_file_path . "<br>");
//		end_page();
//		exit;
//	}
//}

function generate_bank_file($bank_file_path, $payroll_run_id, $basic_salary_component, $incentive_salary_component,
                                    $main_bank_tran_date, $other_bank_tran_Date, $account_info,
                                    $valid_salaries, $released_salaries, $line_reference, $field_separator)
{
	$filename = db_bank_file($bank_file_path, $payroll_run_id, $basic_salary_component, $incentive_salary_component,
                                    $main_bank_tran_date, $other_bank_tran_Date, $account_info,
                                    $valid_salaries, $released_salaries, $line_reference, $field_separator);
    
	if ($filename){
		display_notification(_("Bank file").' '. _("Filename") . ": " . $filename." generated.");
    }
    else{
		display_error(_("Bank file generation was not successful."));
    }
	
	return $filename;
}

//function generate_backup($conn, $ext='no', $comm='')
//{
//	$filename = db_backup($conn, $ext, $comm);
//    
//	if ($filename)
//		display_notification(_("Backup successfully generated."). ' '
//			. _("Filename") . ": " . $filename);
//	else
//		display_error(_("Database backup failed."));
//	
//	return $filename;
//}


function get_backup_file_combo($bank_file_path)
{
	global $path_to_root, $Ajax;
	
	$ar_files = array();
    default_focus('backups');
    $dh = opendir($bank_file_path);
	while (($file = readdir($dh)) !== false)
		$ar_files[] = $file;
	closedir($dh);

    rsort($ar_files);
	$opt_files = "";
    foreach ($ar_files as $file){
		//if (preg_match("/.sql(.zip|.gz)?$/", $file)){
        if (preg_match("/.txt(.zip|.gz)?$/", $file)){
    		$opt_files .= "<option value='$file'>$file</option>";
        }
    }

	$selector = "<select name='backups' size=2 style='height:160px;min-width:230px'>$opt_files</select>";

	$Ajax->addUpdate('backups', "_backups_sel", $selector);
	$selector = "<span id='_backups_sel'>".$selector."</span>\n";

	return $selector;
}

//function compress_list_row($label, $name, $value=null)
//{
//	$ar_comps = array('no'=>_("No"));
//
//    if (function_exists("gzcompress"))
//    	$ar_comps['zip'] = "zip";
//    if (function_exists("gzopen"))
//    	$ar_comps['gzip'] = "gzip";
//
//	echo "<tr><td class='label'>$label</td><td>";
//	echo array_selector('comp', $value, $ar_comps);
//	echo "</td></tr>";
//}

function download_file($filename)
{
    if (empty($filename) || !file_exists($filename))
    {
		display_error(_('Select backup file first.'));
        return false;
    }
    $saveasname = basename($filename);
    header('Content-type: application/octet-stream');
   	header('Content-Length: '.filesize($filename));
   	header('Content-Disposition: attachment; filename="'.$saveasname.'"');
    readfile($filename);

    return true;
}

//$db_name = $_SESSION["wa_current_user"]->company;
//$conn = $db_connections[$db_name];
//$backup_name = clean_file_name(get_post('backups'));
//$backup_path = $bank_file_path . $backup_name;
//


if (get_post('create')) {
	//generate_backup($conn, get_post('comp'), get_post('comments'));
//    generate_backup($bank_file_path, $payroll_run_id, $salary_total_code, 
//                                    $main_bank_tran_date, $other_bank_tran_Date, $account_info);
    generate_bank_file($bank_file_path, get_post('payroll_run_id'), get_post('basic_salary_component'), get_post('incentive_salary_component'),
                        get_post('main_bank_tran_date'), get_post('other_bank_tran_date'), $account_info,
                        get_post('valid_salaries'), get_post('released_salaries'), get_post('line_reference'), get_post('field_separator'));
	
	$Ajax->activate('backups');
};

//if (get_post('restore')) {
//	if ($backup_name) {
//		if (db_import($backup_path, $conn))
//			display_notification(_("Restore backup completed."));
//		refresh_sys_prefs(); // re-read system setup
//	} else
//		display_error(_("Select backup file first."));
//}

//if (get_post('deldump')) {
//	if ($backup_name) {
//		if (unlink($backup_path)) {
//			display_notification(_("File successfully deleted.")." "
//					. _("Filename") . ": " . $backup_name);
//			$Ajax->activate('backups');
//		}
//		else
//			display_error(_("Can't delete backup file."));
//	} else
//		display_error(_("Select backup file first."));
//}

//if (get_post('upload'))
//{
//	$tmpname = $_FILES['uploadfile']['tmp_name'];
//	$fname = trim(basename($_FILES['uploadfile']['name']));
//
//	if ($fname) {
//		if (!preg_match("/\.sql(\.zip|\.gz)?$/", $fname))
//			display_error(_("You can only upload *.sql backup files"));
//		elseif (is_uploaded_file($tmpname)) {
//			rename($tmpname, $bank_file_path . $fname);
//			display_notification(_("File uploaded to backup directory"));
//			$Ajax->activate('backups');
//		} else
//			display_error(_("File was not uploaded into the system."));
//	} else
//		display_error(_("Select backup file first."));
//
//}
//-------------------------------------------------------------------------------
start_form(true, true);
start_outer_table(TABLESTYLE2);
table_section(1);
table_section_title(_("Bank File Parameters"));

    payroll_run_list_row('Payroll Run:', 'payroll_run_id');

    value_list_code_row('Basic Salary', 'basic_salary_component', 'SALARY_TOTALS', null, '');
    
    value_list_code_row('Incentive Salary', 'incentive_salary_component', 'SALARY_TOTALS', null, '');
     
    yesno_list_row('Print Valid Salaries', 'valid_salaries', 0);
    
    yesno_list_row('Print Released Salaries', 'released_salaries', 0);

    date_row('Main Bank Transaction Date', 'main_bank_tran_date');
    
    date_row('Other Banks Transaction Date', 'other_bank_tran_date');
    
    text_row("Line Reference:", 'line_reference', null, 13, 13);
    
    yesno_list_row('Field Separator', 'field_separator', 1);
    
//    compress_list_row(_("Compression:"),'comp');
//    
//	textarea_row(_("Comments:"), 'comments', null, 30, 8);
//	compress_list_row(_("Compression:"),'comp');
	vertical_space("height='20px'");
	submit_row('create',_("Create Bank File"), false, "colspan=2 align='center'", '', 'process');
    vertical_space("height='20px'");
    
//table_section(2);
table_section_title(_("Bank Files"));

	start_row();
	echo "<td style='padding-left:20px' align='left'>".get_backup_file_combo($bank_file_path)."</td>";
	echo "<td style='padding-left:20px' valign='top'>";
	start_table();
    //submit_row('create',_("Create Backup"), false, false, '', 'process');
	//submit_row('view',_("View Backup"), false, '', '', false);
	submit_row('download',_("Download Bank File"), false, '', '', false);
	//submit_row('restore',_("Restore Backup"), false, '','', 'process');
	//submit_js_confirm('restore',_("You are about to restore database from backup file.\nDo you want to continue?"));

	//submit_row('deldump', _("Delete Backup"), false, '','', true);
	// don't use 'delete' name or IE js errors appear
	//submit_js_confirm('deldump', sprintf(_("You are about to remove selected backup file.\nDo you want to continue ?")));
	end_table();
	echo "</td>";
	end_row();

end_outer_table();

br(2);

end_form();

end_page();
?>
