<?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/epf_file_db.inc");
include_once($path_to_root . "/payroll/includes/db/payroll_inquiry_db.inc");
include_once($path_to_root . "/payroll/includes/db/payroll_run_db.inc");
include_once($path_to_root . "/admin/db/list_values_db.inc");
include_once($path_to_root . "/payroll/includes/db/bank_branches_db.inc");
include_once($path_to_root . "/payroll/includes/db/leaves_db.inc");
include_once($path_to_root . "/includes/db/module_settings_db.inc");


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


$epf_file_path = $path_to_root.'/company/'.user_company()."/epf_files/";

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

$info = array();
$info['account_name'] = "SAW Engineering";
$info['account_number'] = "56010011888";
$info['bank_code'] = "7083";
$info['branch_code'] = "056";
$info['tran_code'] = "223";
$info['zone_code'] = "I";
$info['employer_number'] = get_module_parameter_value('payroll', 'epf_reg_no');
$info['submission_number'] = "1";
$info['do_code'] = "35";


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

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

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

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

function generate_epf_file($epf_file_path, $info)
{
    $year_month = "";
    $payroll_run = null;
    if(get_post('payroll_run_id') > 0){
        $payroll_run = get_payroll_run_details(get_post('payroll_run_id'));
        $year_month = substr($payroll_run['period_end_date'], 0, 4);
        $year_month .= substr($payroll_run['period_end_date'], 5, 2);
    }
    $info['year_month'] = $year_month;
    
    if(strlen(get_post('epf_salary_component')) > 2){
        $info['epf_salary_component'] = get_post('epf_salary_component');
    }
    else{
        $info['epf_salary_component'] = "";
    }
    $payment_date = get_post('payment_date');
    $payment_date = date2sql($payment_date);
    $payment_date = date("Ymd", strtotime($payment_date));
    $info['payment_date'] = $payment_date;
    
    $info['valid_salaries'] = get_post('valid_salaries');
    $info['released_salaries'] = get_post('released_salaries');
    $info['no_of_working_days'] = get_post('no_of_working_days');
    
    $info['field_separator'] = get_post('field_separator');
    
    $info['payment_mode'] = get_post('payment_mode');
    
    $bank = get_list_value(get_post('bank_id'));
    $bank_branch = get_branch_details(get_post('bank_branch_id'));
    $pay_ref = get_post('payment_reference');
    $payment_reference = $bank['value_code'].$bank_branch['branch_code'].$pay_ref;
    $info['payment_reference'] = $payment_reference;
    
    
	$r = db_epf_file($epf_file_path, $payroll_run, $info);
    
	if($r['success'] === true){
		display_notification($r['message']);
    }
    else{
		display_error($r['message'] );
    }

}

//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($epf_file_path)
{
	global $path_to_root, $Ajax;
	
	$ar_files = array();
    default_focus('backups');
    $dh = opendir($epf_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;
}


if (get_post('Create_EPF_File')) {

    generate_epf_file($epf_file_path, $info);
	
	$Ajax->activate('backups');
}


//-------------------------------------------------------------------------------
start_form(true, true);
start_outer_table(TABLESTYLE2);
table_section(1);
table_section_title(_("EPF File Parameters"));

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

    value_list_code_row('EPF Salary', 'epf_salary_component', 'SALARY_TOTALS');
   
    yesno_list_row('Print Valid Salaries', 'valid_salaries', 0);
    
    yesno_list_row('Print Released Salaries', 'released_salaries', 0);
    
    amount_row("No of Company Working Days :", 'no_of_working_days', null, null, null, 0);
    
//    $payment_modes_array[1] = "Cheque";
//    $payment_modes_array[2] = "Cash";
//    $payment_modes_array[3] = "Money Order";
//    $payment_modes_array[4] = "Direct Debit";    
//    custom_values_list_row("Payment Mode :", "payment_mode", $payment_modes_array);
//    
//    value_list_row("Bank :", "bank_id", "BANKS", null, false, true);
//    
//    bank_branch_list_row("Branch :", "bank_branch_id", get_post('bank_id'));
//
//    text_row("Payment Reference:", 'payment_reference', null, 13, 13);
//    
//    date_row('Payment Date', 'payment_date');

    
    
    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_EPF_File',_("Create EPF File"), false, "colspan=2 align='center'", '', 'process');
    vertical_space("height='20px'");
    
//table_section(2);
table_section_title(_("EPF Files"));

	start_row();
	echo "<td style='padding-left:20px' align='left'>".get_backup_file_combo($epf_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_EPF_File',_("Download EPF 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();
?>
