<?php

if (empty($_SERVER['HTTPS']) || $_SERVER['HTTPS'] == "off") {
	$redirect = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
	header('HTTP/1.1 301 Moved Permanently');
	header('Location: ' . $redirect);
	exit();
}


include 'vars.php';
include 'sql.php';
include 'functions.php';
include 'mobile_device_detect.php';

// get the task
$task = getVar('t','p');

// get supplied username & password
$u = getVar('u','');
$pw = getVar('pw','');

//get the scheme
$scheme = array();
$scheme['name'] = '';
$scheme['phone'] = '';
$scheme['url'] = '';
$scheme['address'] = '';
$scheme['conversion_html'] = '';

$sth = pg_query_params($db, $SQL_library['getScheme'], array($PREF_scheme));
if ($row = pg_fetch_array($sth, NULL, PGSQL_ASSOC)) {
	$scheme = $row;
} else {
	$smarty->assign('news_items', array());
	$smarty->assign('article_items', array());
	$smarty->assign('scheme', $PREF_scheme);
	$smarty->display('error.tpl');
	exit;
}

switch ($task) {
	case 'p': //page
		draw_page();
		break;
	case 'e': //page editor
		editor();
		break;
	case 'q': //enquiry handler (diverts to draw_page after)
		add_enquiry();
		break;
	case 'enquiry': //for solicitors to view/accept an enquiry emailed to them
		view_enquiry();
		break;
	case 'feedback': //for solicitors to view/accept an enquiry emailed to them
		feedback();
		break;
	case 'opportunity': //for solicitors to view/accept an enquiry emailed to them
		opportunity();
		break;
	case 'search': //for solicitors to view/accept an enquiry emailed to them
		search();
		break;
	case 'news':
		news();
		break;
	case 'articles':
		articles();
		break;
	case 'rss':
		rss();
		break;
	case 'newsletter': //for solicitors to view/accept an enquiry emailed to them
		newsletter();
		break;
	default:
}
exit;

function draw_page()
{
	global $db;
	global $SQL_library;
	global $smarty;
	global $scheme;

	$page_id = getVar('id',1);
	$quick = $page_id;
	if (!is_numeric($page_id)) {
		$page_id = -1;
	}

	$sth = pg_query_params($db, $SQL_library['getPage'], array($page_id, "$quick"));
	if ($row = pg_fetch_array($sth, NULL, PGSQL_ASSOC)) {
		$data = $row['data'];
		$title = $row['title'];
		$heading = $row['heading'];
		$date_created = date('d-M-Y', strtotime($row['date_created']));
		$news = ($row['news'] == 't');

		$data = str_replace('{scheme_name}', $scheme['name'], $data);
		$title = str_replace('{scheme_name}', $scheme['name'], $title);
		$heading = str_replace('{scheme_name}', $scheme['name'], $heading);
		$data = str_replace('{scheme_phone}', $scheme['phone'], $data);
		$title = str_replace('{scheme_phone}', $scheme['phone'], $title);
		$heading = str_replace('{scheme_phone}', $scheme['phone'], $heading);
		$data = str_replace('{scheme_url}', $scheme['url'], $data);
		$title = str_replace('{scheme_url}', $scheme['url'], $title);
		$heading = str_replace('{scheme_url}', $scheme['url'], $heading);
		$data = str_replace('{scheme_address}', $scheme['address'], $data);
		$title = str_replace('{scheme_address}', $scheme['address'], $title);
		$heading = str_replace('{scheme_address}', $scheme['address'], $heading);

		$data = str_replace('{scheme_conversion_html}', $scheme['conversion_html'], $data);
	} else {
		$smarty->assign('news_items', array());
		$smarty->assign('article_items', array());
		$smarty->assign('scheme', $scheme['id']);
		$smarty->display('error.tpl');
		exit;
	}

	$highlight = getVar('h','');
	if ($highlight != '') {
		$data = str_highlight($data, array($highlight, '<span class="highlight">' . $highlight . '</span>'));
	}

	$smarty->assign('title', $title);
	$smarty->assign('heading', $heading);
	$smarty->assign('data', $data);
	$smarty->assign('news', $news);
	$smarty->assign('date_created', $date_created);
	$smarty->assign('page_id', $page_id);
	$smarty->assign('quick', $quick);

	// Retrieve News Stories
	$sth = pg_query_params($db, $SQL_library['getNews'], array(3));
	$news_items = array();
	while ($row = pg_fetch_array($sth, NULL, PGSQL_ASSOC)) {
		$row['heading'] = str_replace('{scheme_name}', $scheme['name'], $row['heading']);
		$row['synopsis'] = str_replace('{scheme_name}', $scheme['name'], $row['synopsis']);
		$row['heading'] = str_replace('{scheme_phone}', $scheme['phone'], $row['heading']);
		$row['synopsis'] = str_replace('{scheme_phone}', $scheme['phone'], $row['synopsis']);
		$row['heading'] = str_replace('{scheme_url}', $scheme['url'], $row['heading']);
		$row['synopsis'] = str_replace('{scheme_url}', $scheme['url'], $row['synopsis']);
		$row['heading'] = str_replace('{scheme_address}', $scheme['address'], $row['heading']);
		$row['synopsis'] = str_replace('{scheme_address}', $scheme['address'], $row['synopsis']);
		$news_items[] = array(
			'id' => $row['id'],
			'heading' => $row['heading'],
			'quick' => $row['quick'],
			'date_created' => date('d-M-Y', strtotime($row['date_created'])),
			'synopsis' => $row['synopsis']
		);
	}
	$sth = null;
	$smarty->assign('news_items', $news_items);

	// Retrieve Articles
	$sth = pg_query_params($db, $SQL_library['getArticles'], array(3));
	$article_items = array();
	while ($row = pg_fetch_array($sth, NULL, PGSQL_ASSOC)) {
		$row['heading'] = str_replace('{scheme_name}', $scheme['name'], $row['heading']);
		$row['synopsis'] = str_replace('{scheme_name}', $scheme['name'], $row['synopsis']);
		$row['heading'] = str_replace('{scheme_phone}', $scheme['phone'], $row['heading']);
		$row['synopsis'] = str_replace('{scheme_phone}', $scheme['phone'], $row['synopsis']);
		$row['heading'] = str_replace('{scheme_url}', $scheme['url'], $row['heading']);
		$row['synopsis'] = str_replace('{scheme_url}', $scheme['url'], $row['synopsis']);
		$row['heading'] = str_replace('{scheme_address}', $scheme['address'], $row['heading']);
		$row['synopsis'] = str_replace('{scheme_address}', $scheme['address'], $row['synopsis']);
		$article_items[] = array(
			'id' => $row['id'],
			'heading' => $row['heading'],
			'quick' => $row['quick'],
			'date_created' => date('d-M-Y', strtotime($row['date_created'])),
			'synopsis' => $row['synopsis']
		);
	}
	$sth = null;
	$smarty->assign('article_items', $article_items);

	$smarty->assign('mobile', mobile_device_detect());
	if ($page_id != 1) {
		$smarty->display('page.tpl');
	} else {
		if (mobile_device_detect()) {
			$smarty->display('front_m.tpl');
		} else {
			$smarty->display('front.tpl');
		}
	}
}

function login()
{
	global $PREF_username;
	global $PREF_password;
	global $smarty;
	global $task;
	$u = getVar('u','');
	$pw = getVar('pw','');
	if (($u != $PREF_username) || ($pw != $PREF_password)) {

		$smarty->assign('task', $task);
		$smarty->display('login.tpl');
		exit;
	}
}

function add_enquiry()
{
    global $db;
    global $smarty;
    global $SQL_library;
    global $scheme;

    // Check for "bulk" variable in the body
    $bulk = json_decode(getVar('bulk', ''), true); // Decode JSON if the "bulk" variable exists
    if ($bulk) {
        // Process multiple enquiries from the "bulk" array
        foreach ($bulk as $enquiry) {
            // Map the enquiry array to variables (like the current method)
            $title = $enquiry['title'] ?? '';
            $first_name = $enquiry['first_name'] ?? '';
            $last_name = $enquiry['last_name'] ?? '';
            $address = $enquiry['address'] ?? '';
            $home_phone = $enquiry['home_phone'] ?? '';
            $work_phone = $enquiry['work_phone'] ?? '';
            $mobile_phone = $enquiry['mobile_phone'] ?? '';
            $email = $enquiry['email'] ?? '';
            $availability = $enquiry['availability'] ?? '';
            $dob = $enquiry['dob'] ?? '';

            $guardian = $enquiry['guardian'] ?? '';
            $incident_type = $enquiry['incident_type'] ?? '';
            $incident_date = $enquiry['incident_date'] ?? '';
            $incident_time = $enquiry['incident_time'] ?? '';
            $police = $enquiry['police'] ?? '';
            $details = $enquiry['details'] ?? '';
            $witnesses = $enquiry['witnesses'] ?? '';
            $losses = $enquiry['losses'] ?? '';
            $fault = $enquiry['fault'] ?? '';
            $legal = $enquiry['legal'] ?? '';
            $marketing = $enquiry['marketing'] ?? '';

            // Reuse existing logic for adding an individual enquiry
            $sth = pg_query_params($db, $SQL_library['getEnquiryId'], array());
            if ($row = pg_fetch_array($sth, NULL, PGSQL_ASSOC)) {
                $enquiry_id = $row['id'];
            } else {
                $smarty->display('error.tpl');
                exit;
            }

            $sth = pg_query_params($db, $SQL_library['addEnquiry'], array(
                $enquiry_id, $title, $first_name, $last_name, $address,
                $home_phone, $work_phone, $mobile_phone, $email, $availability,
                $dob, $guardian, $incident_type, $incident_date, $incident_time,
                $police, $details, $witnesses, $losses, $fault, $legal,
                $marketing, $_SERVER['REMOTE_ADDR'], $scheme['id']
            ));
        }
    } else {
        // Original logic for single enquiry
        $title = getVar('title', '');
        $first_name = getVar('first_name', '');
        $last_name = getVar('last_name', '');
        $address = getVar('address', '');
        $home_phone = getVar('home_phone', '');
        $work_phone = getVar('work_phone', '');
        $mobile_phone = getVar('mobile_phone', '');
        $email = getVar('email', '');
        $availability = getVar('availability', '');
        $dob = getVar('dob', '');
        $guardian = getVar('guardian', '');
        $incident_type = getVar('incident_type', '');
        $incident_date = getVar('incident_date', '');
        $incident_time = getVar('incident_time', '');
        $police = getVar('police', '');
        $details = getVar('details', '');
        $witnesses = getVar('witnesses', '');
        $losses = getVar('losses', '');
        $fault = getVar('fault', '');
        $legal = getVar('legal', '');
        $marketing = getVar('marketing', '');

        $sth = pg_query_params($db, 'SELECT ipaddress FROM blocked_ip_address WHERE ipaddress=$1', array($_SERVER['REMOTE_ADDR']));
        if ($row = pg_fetch_array($sth, NULL, PGSQL_ASSOC)) {
            $ip_blocked = true;
            $ip_blocked = false;
        } else {
            $ip__blocked = false;
        }

        if ((0 == preg_match('/http/', $address)) && (0 == preg_match('/href/', $address))) {
            $sth = pg_query_params($db, $SQL_library['getEnquiryId'], array());
            if ($row = pg_fetch_array($sth, NULL, PGSQL_ASSOC)) {
                $enquiry_id = $row['id'];
            } else {
                $smarty->display('error.tpl');
                exit;
            }
            $sth = pg_query_params($db, $SQL_library['addEnquiry'], array(
                $enquiry_id, $title, $first_name, $last_name, $address,
                $home_phone, $work_phone, $mobile_phone, $email, $availability,
                $dob, $guardian, $incident_type, $incident_date, $incident_time,
                $police, $details, $witnesses, $losses, $fault, $legal,
                $marketing, $_SERVER['REMOTE_ADDR'], $scheme['id']
            ));
        }
    }
    draw_page();
}

function view_enquiry()
{
	global $db;
	global $smarty;
	global $SQL_library;
	global $PREF_exchange_rate;
	global $PREF_vat_rate;
	global $scheme;

	$key = getVar('key','');

	if (strlen($key) == 64) {
		$sth = pg_query_params($db, $SQL_library['updateReferral'], array($key));
		$sth = pg_query_params($db, $SQL_library['getEnquiryByKey'], array($key));
		if ($row = pg_fetch_array($sth, NULL, PGSQL_ASSOC)) {

			if (($row['winning_solicitor_id'] == '') || ($row['winning_solicitor_id'] == $row['solicitor_id'])) {
				if (getVar('accept', null) !== null || getVar('resend', null) !== null) {

					// ok, first we mark that this solicitor has won the case
					if (getVar('accept', null) !== null) {
						$sth1 = pg_query_params($db, $SQL_library['setEnquiryWin'], array($row['solicitor_id'], $PREF_exchange_rate, $PREF_vat_rate, $row['id']));
						$row['winning_date'] = 'now';
						$row['winning_solicitor_id'] = $row['solicitor_id'];
						$row['exchange_rate'] = $PREF_exchange_rate;
					}

					// now, prepare the enquiry report
					require('pdf/enquiry.php');

					$pdf = new ENQUIRY('P', 'mm', 'A4');
					$pdf->Open();
					$pdf->AddPage();
					$pdf->top_bar($row['solicitor_name'], $scheme['name'] . " Enquiry Ref: 00" . $row['id']);
					$pdf->addContactDetails(
						$row['title'],
						$row['first_name'],
						$row['last_name'],
						$row['home_phone'],
						$row['work_phone'],
						$row['mobile_phone'],
						$row['availability']
					);
					$pdf->addAddress($row['email'], $row['address']);

					$pdf->addMisc($row['dob'], $row['guardian'], $row['incident_type'], $row['incident_date'], $row['incident_time'], $row['police']);

					$pdf->addDetails($row['details']);
					$pdf->addWitnesses($row['witnesses']);
					$pdf->addLosses($row['losses']);
					$pdf->addFault($row['fault']);

					$pdf->bottom_bar($scheme['name'] . ' ' . chr(149) . " www." . $scheme['url']);

					$enquiry = $pdf->Output('', 'S');

					// prepare the invoice
					require('pdf/invoice.php');
					$pdf = new INVOICE('P', 'mm', 'A4');
					$pdf->Open();
					$pdf->AddPage();
					$pdf->addAddress(
						"Rockstown Limited",
						"22 Rockstown Road\n" .
							"Mowhan\n" .
							"ARMAGH\n" .
							"County Armagh\n" .
							"BT60 2HF\n" .
							"\n" .
							"w: www.rockstown.com\n" .
							"e: info@rockstown.com"
					);
					$pdf->doc_type("INVOICE", "0" . $row['id']);
					$pdf->addDate(date('d-M-Y', strtotime($row['winning_date'])));

					$pdf->addClient("SOL00" . $row['solicitor_id']);
					$pdf->addPageNumber("1");

					$pdf->addClientAddress($row['solicitor_name'] . "\n" .
						$row['solicitor_address1'] . "\n" .
						$row['solicitor_address2'] . "\n" .
						$row['solicitor_address3'] . "\n" .
						$row['solicitor_address4'] . "\n" .
						$row['solicitor_postcode']);
					$pdf->addRemarkTop("Please make cheques payable to ROCKSTOWN LIMITED");
					$pdf->addRemarkA("As we are a small organisation we would greatly appreciate payment within 14 days.");
					$pdf->addRemarkB("All figures are in pounds sterling unless indicated otherwise.");
					$pdf->addExchangeRateRemark("Exchange rate GBP" . chr(163) . "1=EUR" . chr(128) . $row['exchange_rate']);

					$pdf->addVATNum("GB933123355", ($row['solicitor_vatreg'] == '') ? 'N/A' : $row['solicitor_vatreg']);
					$cols = array(
						"ITEM REF"	 => 23,
						"DESCRIPTION"  => 78,
						"QUANTITY"	  => 22,
						"UNIT COST"	=> 26,
						"TOTAL" => 30,
						"VAT"	 => 11
					);
					$pdf->addCols($cols);
					$cols = array(
						"ITEM REF"	 => "L",
						"DESCRIPTION"  => "L",
						"QUANTITY"	  => "C",
						"UNIT COST"	=> "R",
						"TOTAL" => "R",
						"VAT"	 => "C"
					);
					$pdf->addLineFormat($cols);
					$pdf->addLineFormat($cols);

					$y	 = 109;
					$line = array(
						"ITEM REF"	 => "ADV",
						"DESCRIPTION"  => "Advertising Charges",
						"QUANTITY"	  => "1",
						"UNIT COST"	=> $row['fee'],
						"TOTAL" => $row['fee'],
						"VAT"	 => (($row['solicitor_vatreg'] == '') ? '1' : 'Z')
					);
					$size = $pdf->addLine($y, $line);
					$y	+= $size + 2;

					$pdf->addVATBox();

					$tot_prods = array(array("unit_price" => $row['fee'], "quantity" => 1, "vat" => (($row['solicitor_vatreg'] == '') ? '1' : 'Z')));
					$tab_vat = array(
						"1"	 => 20,
						"2"	 => 5,
						"Z"	 => 0
					);
					$pdf->addInvoiceTotals($tab_vat, $tot_prods, $row['exchange_rate']);
					$pdf->addTotalBox();
					$invoice = $pdf->Output('', 'S');

					//email the two documents
					require 'sendEmail.php';
					// prepare and send the email to this solicitor
					$sender = 'enquiries@' . $scheme['url'];
					$subject = $scheme['name'] . ' - Enquiry 00' . $row['id'] . ' Details';
					$body = '';
					$body .= "FAO " . $row['solicitor_key_contact'] . "<br />\r\n";
					$body .= "<br />\r\n";
					$body .= "Dear " . $row['solicitor_salutation'] . "<br />\r\n";
					$body .= "<br />\r\n";
					$body .= "Thank you for your order.<br />\r\n";
					$body .= "<br />\r\n";
					$body .= "Please find attached complete enquiry sheet and invoice.<br />\r\n";
					$body .= "<br />\r\n";
					$body .= "Please remember that invoices are due within 14 days.<br />\r\n";
					$body .= "<br />\r\n";
					$body .= "This enquiry has now been blocked.  No other solicitors will be able to review/accept it.<br />\r\n";
					$body .= "<br />\r\n";
					$body .= "Many thanks<br />\r\n";
					$body .= $scheme['name'];

					$attach = array();
					$attach[] = array(
						'data' => $invoice,
						'filename' => 'invoice.pdf',
						'content_type' => 'application/pdf'
					);
					$attach[] = array(
						'data' => $enquiry,
						'filename' => 'enquiry.pdf',
						'content_type' => 'application/pdf'
					);
					send_mail($row['solicitor_email'], $sender, $subject, $body, $scheme['name'], $attach);
					send_mail('conor@clanrye.com', $sender, "$subject (CONOR COPY)", $body, $scheme['name'], $attach);
					$smarty->assign('mobile', mobile_device_detect());
					$smarty->assign('heading', "Enquiry Sent (Ref: 00" . $row['id'] . ")");
					$smarty->assign('no_menu', true);
					$smarty->display('enquiry_sent.tpl');

					exit;
				}
			}
			// solicitor fields
			$smarty->assign('solicitor_id', $row['solicitor_id']);
			$smarty->assign('solicitor_salutation', $row['solicitor_salutation']);
			$smarty->assign('solicitor_key_contact', $row['solicitor_key_contact']);
			$smarty->assign('solicitor_name', $row['solicitor_name']);
			$smarty->assign('solicitor_address1', $row['solicitor_address1']);
			$smarty->assign('solicitor_address2', $row['solicitor_address2']);
			$smarty->assign('solicitor_address3', $row['solicitor_address3']);
			$smarty->assign('solicitor_address4', $row['solicitor_address4']);
			$smarty->assign('solicitor_postcode', $row['solicitor_postcode']);
			$smarty->assign('solicitor_email', $row['solicitor_email']);
			$smarty->assign('solicitor_vatreg', $row['solicitor_vatreg']);

			// enquiry fields
			$smarty->assign('id', $row['id']);
			$smarty->assign('fee', $row['fee']);
			$smarty->assign('winning_solicitor_id', $row['winning_solicitor_id']);
			$smarty->assign('title', $row['title']);
			$smarty->assign('title_teaser', $row['title_teaser']);
			$smarty->assign('first_name', $row['first_name']);
			$smarty->assign('last_name', $row['last_name']);
			$smarty->assign('address', $row['address']);
			$smarty->assign('home_phone', $row['home_phone']);
			$smarty->assign('work_phone', $row['work_phone']);
			$smarty->assign('mobile_phone', $row['mobile_phone']);
			$smarty->assign('email', $row['email']);
			$smarty->assign('availability', $row['availability']);
			$smarty->assign('dob', $row['dob']);
			$smarty->assign('guardian', $row['guardian']);
			$smarty->assign('incident_type', $row['incident_type']);
			$smarty->assign('incident_date', $row['incident_date']);
			$smarty->assign('incident_time', $row['incident_time']);
			$smarty->assign('police', $row['police']);
			$smarty->assign('details', $row['details']);
			$smarty->assign('witnesses', $row['witnesses']);
			$smarty->assign('losses', $row['losses']);
			$smarty->assign('fault', $row['fault']);
			$smarty->assign('legal', $row['legal']);
			$smarty->assign('marketing', $row['marketing']);
			$smarty->assign('first_name_teaser', $row['first_name_teaser']);
			$smarty->assign('last_name_teaser', $row['last_name_teaser']);
			$smarty->assign('address_teaser', $row['address_teaser']);
			$smarty->assign('home_phone_teaser', $row['home_phone_teaser']);
			$smarty->assign('work_phone_teaser', $row['work_phone_teaser']);
			$smarty->assign('mobile_phone_teaser', $row['mobile_phone_teaser']);
			$smarty->assign('email_teaser', $row['email_teaser']);
			$smarty->assign('availability_teaser', $row['availability_teaser']);
			$smarty->assign('dob_teaser', $row['dob_teaser']);
			$smarty->assign('guardian_teaser', $row['guardian_teaser']);
			$smarty->assign('incident_type_teaser', $row['incident_type_teaser']);
			$smarty->assign('incident_date_teaser', $row['incident_date_teaser']);
			$smarty->assign('incident_time_teaser', $row['incident_time_teaser']);
			$smarty->assign('police_teaser', $row['police_teaser']);
			$smarty->assign('details_teaser', $row['details_teaser']);
			$smarty->assign('witnesses_teaser', $row['witnesses_teaser']);
			$smarty->assign('losses_teaser', $row['losses_teaser']);
			$smarty->assign('fault_teaser', $row['fault_teaser']);
			$smarty->assign('legal_teaser', $row['legal_teaser']);
			$smarty->assign('enquiry_date', $row['enquiry_date']);
			$row['winning_date'] = date('d-M-Y g.ia', strtotime($row['winning_date']));
			$smarty->assign('winning_date', $row['winning_date']);
			$smarty->assign('vatrate', (($row['solicitor_vatreg'] == '') ? sprintf('%.2f', ($PREF_vat_rate - 1) * 100) : '0'));
			$smarty->assign('totamt', (($row['solicitor_vatreg'] == '') ? round_currency($row['fee'] * $PREF_vat_rate) : $row['fee']));

			$smarty->assign('key', $key);
			$smarty->assign('mobile', mobile_device_detect());
			$smarty->assign('heading', "Enquiry Details (Ref: 00" . $row['id'] . ")");
			$smarty->assign('no_menu', true);
			$smarty->display('view_enquiry.tpl');

			require 'sendEmail.php';
			// notify conor that viewed
			$sender = 'enquiries@' . $scheme['url'];
			$subject = $scheme['name'] . " - Viewed - Ref:00" . $row['id'];
			$body = '';
			$body .= "Hi Conor<br />\r\n";
			$body .= "<br />\r\n";
			$body .= $row['solicitor_name'] . " has viewed enquiry 00" . $row['id'] . " from the IP address " . $_SERVER['REMOTE_ADDR'] . ".<br />\r\n";
			$body .= "<br />\r\n";
			$body .= "Regards<br />\r\n";
			$body .= $scheme['name'];

			send_mail('conor@clanrye.com', $sender, $subject, $body, $scheme['name'], array());
		} else {
			$smarty->assign('mobile', mobile_device_detect());
			$smarty->display('enquiry_unknown.tpl');
			exit;
		}
	}
}

function round_currency($amount)
{
	return ((intval($amount * 100)) / 100);
}

function feedback()
{
	global $scheme;
	$recipient = 'feedback@' . $scheme['url'];
	$sender = 'feedback@' . $scheme['url'];
	$subject = $scheme['name'] . ' - WWW Submission (Feedback Page)';
	$name = getVar('name', '');
	$email = getVar('email', '');
	$telephone = getVar('telephone', '');
	$siterating = getVar('siterating', '');
	$how_found_site = getVar('how_found_site', '');
	$why_come_to_site = getVar('why_come_to_site', '');


	$body = '';
	$body = $body . "From: $name <br />\r\n";
	$body = $body . "Email: $email <br />\r\n";
	$body = $body . "<br />\r\n";
	$body = $body . "Tel Number: $telephone <br />\r\n";
	$body = $body . "<br />\r\n";
	$body = $body . "Site Rating: $siterating <br />\r\n";
	$body = $body . "<br />\r\n";
	$body = $body . "How found site: $how_found_site <br />\r\n";
	$body = $body . "<br />\r\n";
	$body = $body . "Why come to site: $why_come_to_site <br />\r\n";
	$body = $body . "<br />\r\n";
	$body = $body . "Time of Enquiry: " . date('r') . " <br />\r\n";
	$body = $body . "<br />\r\n";
	require 'sendEmail.php';
	send_mail($recipient, $sender, $subject, $body, $scheme['name'], array());
	draw_page();
}

function opportunity()
{
	global $scheme;
	$recipient = 'conor@clanrye.com';
	$sender = 'info@' . $scheme['url'];
	$subject = $scheme['name'] . ' - WWW Submission (Opportunities Page)';
	$firmname = getVar('firmname', '');
	$firmaddress = getVar('firmaddress', '');
	$firmemail = getVar('firmemail', '');
	$firmcontact = getVar('firmcontact', '');
	$firmphone = getVar('firmphone', '');
	$area = getVar('area', '');
	$firmsize = getVar('firmsize', '');
	$otherinfo = getVar('otherinfo', '');

	$body = '';
	$body = $body . "From: $firmname <br />\r\n";
	$body = $body . "Address: $firmaddress <br />\r\n";
	$body = $body . "Email: $firmemail <br />\r\n";
	$body = $body . "Contact: $firmcontact <br />\r\n";
	$body = $body . "Phone: $firmphone <br />\r\n";
	$body = $body . "<br />\r\n";
	$body = $body . "Areas: $area <br />\r\n";
	$body = $body . "Firm Size: $firmsize <br />\r\n";
	$body = $body . "<br />\r\n";
	$body = $body . "Other Info: $otherinfo <br />\r\n";
	$body = $body . "<br />\r\n";
	$body = $body . "Time of Enquiry: " . date('r') . " <br />\r\n";
	require 'sendEmail.php';
	send_mail($recipient, $sender, $subject, $body, $scheme['name'], array());
	draw_page();
}

function search()
{
	global $db;
	global $smarty;
	global $SQL_library;

	$q = getVar('q', '');
	$sth = pg_query_params($db, $SQL_library['pageSearch'], array($q));

	$results = array();
	while ($row = pg_fetch_array($sth, NULL, PGSQL_ASSOC)) {
		$results[] = array('id' => $row['id'], 'title' => $row['title']);
	}
	$smarty->assign('results', $results);
	$smarty->assign('q', $q);


	// side news
	$sth = pg_query_params($db, $SQL_library['getNews'], array(3));
	$news_items = array();
	while ($row = pg_fetch_array($sth, NULL, PGSQL_ASSOC)) {
		$news_items[] = array(
			'id' => $row['id'],
			'heading' => $row['heading'],
			'quick' => $row['quick'],
			'date_created' => date('d-M-Y', strtotime($row['date_created'])),
			'synopsis' => $row['synopsis']
		);
	}
	$sth = null;
	$smarty->assign('news_items', $news_items);
	// Retrieve Articles
	$sth = pg_query_params($db, $SQL_library['getArticles'], array(3));
	$article_items = array();
	while ($row = pg_fetch_array($sth, NULL, PGSQL_ASSOC)) {
		$row['heading'] = str_replace('{scheme_name}', $scheme['name'], $row['heading']);
		$row['synopsis'] = str_replace('{scheme_name}', $scheme['name'], $row['synopsis']);
		$row['heading'] = str_replace('{scheme_phone}', $scheme['phone'], $row['heading']);
		$row['synopsis'] = str_replace('{scheme_phone}', $scheme['phone'], $row['synopsis']);
		$row['heading'] = str_replace('{scheme_url}', $scheme['url'], $row['heading']);
		$row['synopsis'] = str_replace('{scheme_url}', $scheme['url'], $row['synopsis']);
		$row['heading'] = str_replace('{scheme_address}', $scheme['address'], $row['heading']);
		$row['synopsis'] = str_replace('{scheme_address}', $scheme['address'], $row['synopsis']);
		$article_items[] = array(
			'id' => $row['id'],
			'heading' => $row['heading'],
			'quick' => $row['quick'],
			'date_created' => date('d-M-Y', strtotime($row['date_created'])),
			'synopsis' => $row['synopsis']
		);
	}
	$sth = null;
	$smarty->assign('article_items', $article_items);
	$smarty->assign('mobile', mobile_device_detect());
	$smarty->display('search_results.tpl');
	$sth = null;
	exit;
}

function news()
{
	global $db;
	global $smarty;
	global $SQL_library;
	global $scheme;

	$sth = pg_query_params($db, $SQL_library['getNews'], array(9999));

	$news_items = array();
	while ($row = pg_fetch_array($sth, NULL, PGSQL_ASSOC)) {
		$news_items[] = array(
			'id' => $row['id'],
			'heading' => $row['heading'],
			'quick' => $row['quick'],
			'date_created' => date('d-M-Y', strtotime($row['date_created'])),
			'synopsis' => $row['synopsis']
		);
	}
	$sth = null;
	$smarty->assign('all_news_items', $news_items);
	$smarty->assign('page_id', 'news');


	// side news
	$sth = pg_query_params($db, $SQL_library['getNews'], array(3));
	$news_items = array();
	while ($row = pg_fetch_array($sth, NULL, PGSQL_ASSOC)) {
		$news_items[] = array(
			'id' => $row['id'],
			'heading' => $row['heading'],
			'quick' => $row['quick'],
			'date_created' => date('d-M-Y', strtotime($row['date_created'])),
			'synopsis' => $row['synopsis']
		);
	}
	$sth = null;
	$smarty->assign('news_items', $news_items);
	// Retrieve Articles
	$sth = pg_query_params($db, $SQL_library['getArticles'], array(3));
	$article_items = array();
	while ($row = pg_fetch_array($sth, NULL, PGSQL_ASSOC)) {
		$row['heading'] = str_replace('{scheme_name}', $scheme['name'], $row['heading']);
		$row['synopsis'] = str_replace('{scheme_name}', $scheme['name'], $row['synopsis']);
		$row['heading'] = str_replace('{scheme_phone}', $scheme['phone'], $row['heading']);
		$row['synopsis'] = str_replace('{scheme_phone}', $scheme['phone'], $row['synopsis']);
		$row['heading'] = str_replace('{scheme_url}', $scheme['url'], $row['heading']);
		$row['synopsis'] = str_replace('{scheme_url}', $scheme['url'], $row['synopsis']);
		$row['heading'] = str_replace('{scheme_address}', $scheme['address'], $row['heading']);
		$row['synopsis'] = str_replace('{scheme_address}', $scheme['address'], $row['synopsis']);
		$article_items[] = array(
			'id' => $row['id'],
			'heading' => $row['heading'],
			'quick' => $row['quick'],
			'date_created' => date('d-M-Y', strtotime($row['date_created'])),
			'synopsis' => $row['synopsis']
		);
	}
	$sth = null;
	$smarty->assign('article_items', $article_items);
	$smarty->assign('heading', 'Other News Items');
	$sth = null;
	$smarty->assign('mobile', mobile_device_detect());
	$smarty->assign('quick', 'news');
	$smarty->assign('title', '');

	$smarty->display('news_list.tpl');
	$sth = null;
	exit;
}

function articles()
{
	global $db;
	global $smarty;
	global $SQL_library;
	global $scheme;

	$sth = pg_query_params($db, $SQL_library['getArticles'], array(9999));

	$article_items = array();
	while ($row = pg_fetch_array($sth, NULL, PGSQL_ASSOC)) {
		$article_items[] = array(
			'id' => $row['id'],
			'heading' => $row['heading'],
			'quick' => $row['quick'],
			'date_created' => date('d-M-Y', strtotime($row['date_created'])),
			'synopsis' => $row['synopsis']
		);
	}
	$sth = null;
	$smarty->assign('all_article_items', $article_items);
	$smarty->assign('page_id', 'article');


	// side news
	$sth = pg_query_params($db, $SQL_library['getNews'], array(3));
	$news_items = array();
	while ($row = pg_fetch_array($sth, NULL, PGSQL_ASSOC)) {
		$news_items[] = array(
			'id' => $row['id'],
			'heading' => $row['heading'],
			'quick' => $row['quick'],
			'date_created' => date('d-M-Y', strtotime($row['date_created'])),
			'synopsis' => $row['synopsis']
		);
	}
	$sth = null;
	$smarty->assign('news_items', $news_items);
	// Retrieve Articles
	$sth = pg_query_params($db, $SQL_library['getArticles'], array(3));
	$article_items = array();
	while ($row = pg_fetch_array($sth, NULL, PGSQL_ASSOC)) {
		$row['heading'] = str_replace('{scheme_name}', $scheme['name'], $row['heading']);
		$row['synopsis'] = str_replace('{scheme_name}', $scheme['name'], $row['synopsis']);
		$row['heading'] = str_replace('{scheme_phone}', $scheme['phone'], $row['heading']);
		$row['synopsis'] = str_replace('{scheme_phone}', $scheme['phone'], $row['synopsis']);
		$row['heading'] = str_replace('{scheme_url}', $scheme['url'], $row['heading']);
		$row['synopsis'] = str_replace('{scheme_url}', $scheme['url'], $row['synopsis']);
		$row['heading'] = str_replace('{scheme_address}', $scheme['address'], $row['heading']);
		$row['synopsis'] = str_replace('{scheme_address}', $scheme['address'], $row['synopsis']);
		$article_items[] = array(
			'id' => $row['id'],
			'heading' => $row['heading'],
			'quick' => $row['quick'],
			'date_created' => date('d-M-Y', strtotime($row['date_created'])),
			'synopsis' => $row['synopsis']
		);
	}
	$sth = null;
	$smarty->assign('article_items', $article_items);
	$smarty->assign('heading', 'Other Articles');
	$sth = null;
	$smarty->assign('mobile', mobile_device_detect());

	$smarty->display('article_list.tpl');
	$sth = null;
	exit;
}

function newsletter()
{
	global $scheme;
	$recipient = 'conor@clanrye.com';
	$sender = 'info@' . $scheme['url'];
	$subject = $scheme['name'] . ' - Newsletter Request';
	$email = getVar('email', '');
	if ($email != '') {
		$body = '';
		$body = $body . "Email: $email <br />\r\n";
		$body = $body . "<br />\r\n";
		$body = $body . "Time of Enquiry: " . date('r') . " <br />\r\n";
		require 'sendEmail.php';
		send_mail($recipient, $sender, $subject, $body, $scheme['name'], array());
	}
	draw_page();
}

function rss()
{
	global $db;
	global $smarty;
	global $SQL_library;

	$sth = pg_query_params($db, $SQL_library['getNews'], array(9999));

	$news_items = array();
	while ($row = pg_fetch_array($sth, NULL, PGSQL_ASSOC)) {
		$news_items[] = array(
			'id' => $row['id'],
			'heading' => $row['heading'],
			'quick' => $row['quick'],
			'date_created' => date('d-M-Y', strtotime($row['date_created'])),
			'synopsis' => $row['synopsis']
		);
	}
	$sth = null;
	$smarty->assign('all_news_items', $news_items);


	// side news
	$sth = pg_query_params($db, $SQL_library['getNews'], array(3));
	$news_items = array();
	while ($row = pg_fetch_array($sth, NULL, PGSQL_ASSOC)) {
		$news_items[] = array(
			'id' => $row['id'],
			'heading' => $row['heading'],
			'quick' => $row['quick'],
			'date_created' => date('d-M-Y', strtotime($row['date_created'])),
			'synopsis' => $row['synopsis']
		);
	}
	$sth = null;
	$smarty->assign('news_items', $news_items);
	$sth = null;

	$smarty->display('rss.tpl');
	$sth = null;
	exit;
}

/**
 * Perform a simple text replace
 * This should be used when the string does not contain HTML
 * (off by default)
 */
define('STR_HIGHLIGHT_SIMPLE', 1);
define('STR_HIGHLIGHT_WHOLEWD', 2);
define('STR_HIGHLIGHT_CASESENS', 4);
define('STR_HIGHLIGHT_STRIPLINKS', 8);
function str_highlight($text, $needle, $options = null, $highlight = null)
{
	// Default highlighting
	if ($highlight === null) {
		$highlight = '<strong>\1</strong>';
	}

	// Select pattern to use
	if ($options & STR_HIGHLIGHT_SIMPLE) {
		$pattern = '#(%s)#';
		$sl_pattern = '#(%s)#';
	} else {
		$pattern = '#(?!<.*?)(%s)(?![^<>]*?>)#';
		$sl_pattern = '#<a\s(?:.*?)>(%s)</a>#';
	}

	// Case sensitivity
	if (!($options & STR_HIGHLIGHT_CASESENS)) {
		$pattern .= 'i';
		$sl_pattern .= 'i';
	}

	$needle = (array) $needle;
	foreach ($needle as $needle_s) {
		$needle_s = preg_quote($needle_s);

		// Escape needle with optional whole word check
		if ($options & STR_HIGHLIGHT_WHOLEWD) {
			$needle_s = '\b' . $needle_s . '\b';
		}

		// Strip links
		if ($options & STR_HIGHLIGHT_STRIPLINKS) {
			$sl_regex = sprintf($sl_pattern, $needle_s);
			$text = preg_replace($sl_regex, '\1', $text);
		}

		$regex = sprintf($pattern, $needle_s);
		$text = preg_replace($regex, $highlight, $text);
	}

	return $text;
}
