<?php
	include 'client/minifier.php';
    ob_start();
?>

<?php
    require_once 'client/bingc.lib.php';
    include 'config.php';

    global $CFG;

    $request_type = ""; // used in decide on the include page
    $page_title = $CFG->site_meta_title;
    $page_desc = $CFG->site_meta_desc;
    $page_keywords = $CFG->site_meta_keywords;
    $page_desc = $CFG->site_meta_desc;

    $content_title = '';
    $content_html = '';
    $response = '';

    $history = '';

    // add to history
    $bclient = new bingc\client();
    
    //*** Jan 12th 2019
	// this code is for getting geo info (country) for a given client ip (used for displaying sb ads)
	// IMPORTANT - this code does not return data for local IP (local testing)
	$geo_info = $bclient->get_geoip_info($_SERVER['REMOTE_ADDR'], $CFG->site_type, $_SERVER['HTTP_HOST']);

	// for testing
	//$geo_info = $bclient->get_geoip_info('43.224.158.176', 'cp', $_SERVER['HTTP_HOST']);

	//echo $geo_info['data']['log'];
	//debug_to_console($geo_info['data']);
	// Jan 12th 2019 ***//

    if (isset($_GET[$CFG->old_search_param]) && trim($_GET[$CFG->old_search_param] != '')) { // make sure there is no html or echo before 301 redirect

        debug_to_console("client - keyword is " . $_GET[$CFG->old_search_param]);
        // check if keyword is valid and also get slug to use in the url
        $response = $bclient->check_keyword($_GET[$CFG->old_search_param], $CFG->site_type, $_SERVER['HTTP_HOST']);

        //echo 'log ' . $response['data']['log'];
        debug_to_console($response['data']);

        // check if it is authorised request (query/keyword will be set)
        if(isset($response['data']['query'])) {

            if (!$response['data']['query']['keyword']['is_valid']) {

                debug_to_console('client - keyword is not valid');
                header("Location: $CFG->invalid_search_url");

            } else {

                $url = $CFG->site_search_uri . $response['data']['query']['keyword']['slug'];
                debug_to_console('client - redirect to ' . $url);
                header("HTTP/1.1 301 Moved Permanently");
                header("Location: $url");
            }
        }
        else {
                debug_to_console('client - unauthorised request');
                header("Location: $CFG->unauth_search_url");
        }
    }
    else if (isset($_GET['s'])) {  // this param is set in .htaccess file as part of url rewrite

        $request_type = 'search'; // include
        //echo '[s-condition]keyword: ' . $_GET['s']."<br>";

        $response = $bclient->get($_GET['s'], $CFG->site_type, $_SERVER['HTTP_HOST'], $geo_info);

        //echo $response['data']['log'];
		debug_to_console('client - logging entire response');
		debug_to_console($response);

        if (isset($response['data']['results'])) {
            debug_to_console($response['data']['results']);
        }
		debug_to_console('client - 1');

        // check if it is authorised request (query/keyword will be set)
        if(isset($response['data']['query'])) {

            if (!$response['data']['query']['keyword']['is_valid']) {
                debug_to_console('client - keyword is not valid');
                header("Location: $CFG->invalid_search_url");

            } else {
				debug_to_console('client - 2 else');
                $page_title = $response['data']['query']['keyword']['title_text'].' Worksheets';
				$content_title = $response['data']['query']['keyword']['title_text'];

				// this is to show related related search results
				if ($CFG->show_related_ws) {
					// used in related search
					$content_slug = $response['data']['query']['keyword']['slug'];
					$ascga_rs_json = file_get_contents($CFG->asc_ga_related_search_service_url . 'search_in=file&key=' . $content_slug);
					$ascga_rs_a = json_decode($ascga_rs_json, true);
				}

				// new page desc code improve seo
				$clean_piped_titles = $bclient->clean_result_titles($response);
				//$page_desc_str = 'Displaying ' . count($response['data']['results']).' worksheets for ' . $content_title . '. ';
				$page_desc_str = $content_title . ' Worksheets - there are ' . count($response['data']['results']).' printable worksheets for this topic. ';
				$page_desc_str .= 'Worksheets are ' .  str_replace('|', ', ', $clean_piped_titles) . '.';
				$page_desc = substr($page_desc_str, 0, strpos($page_desc_str, ' ', 160)) . '...';

                $page_keywords = $response['data']['query']['keyword']['clean_text'];

				debug_to_console('client - 3 else before add history');
                $bclient->add_to_history($response['data']['query']['keyword']['title_text'].'|'.$response['data']['query']['keyword']['slug']);
				debug_to_console('client - 4 else end');
            }
        }
        else {
            debug_to_console('client - unauthorised request');
            header("Location: $CFG->unauth_search_url");
        }

    }
    else if (isset($_GET['p'])) { // this param is set in .htaccess file as part of url rewrite
        $request_type = 'page'; // include content.php
        //echo 'page: ' . $_GET['p'];

        $content = file_get_contents($CFG->site_content_json);
        $cname = $_GET['p'];
        $json_a = json_decode($content, true);
        //var_dump(json_decode($content, true));
        //echo "<script> console.log('".$json_a."');</script>";
        //echo "request name: " . $cname;
        if (isset($json_a['categories'][$cname])) {
            //echo "content name: " . $json_a['categories'][$cname]['title'];
            $page_title = $json_a['categories'][$cname]['title'];
            $page_desc = $json_a['categories'][$cname]['title'];
            $page_keywords = $json_a['categories'][$cname]['title'];

            $content_title = $json_a['categories'][$cname]['title'];
            $content_html = $json_a['categories'][$cname]['html'];
        }
        else {
            //echo "<script> console.log('client - content data not found');</script>";
            debug_to_console('client - unauthorised request');
            header("Location: $CFG->unauth_search_url");

        }
    }
	else if (isset($_GET['nc_p'])) {

		$request_type = 'nc';

		$nc_p = $_GET['nc_p'];
		$nc_l = $_GET['nc_l'];
		$nc_k = $_GET['nc_k'];
		$nc_y = $_GET['nc_y'];
		$nc_s = $_GET['nc_s'];

		//$nc_p = 'home';
		$page_title = 'National Curriculum ' . ucfirst($nc_l) . ' ' . str_replace('-', ' ', ucfirst($nc_k)) . ' ' . str_replace('-', ' ', ucfirst($nc_y)) . ' ' . ucfirst(str_replace('-', ' ', $nc_s));
		$content_title = $page_title;
		$page_desc = $page_title;
		$page_keywords = 'national curriculum, ' . $nc_l . ', ' . $nc_k . ', ' . $nc_y . ', ' . $nc_s;
	}
    else {
        $request_type = '';
    }

?>

<!DOCTYPE html>
<html lang="en">
	<head><meta http-equiv="Content-Type" content="text/html; charset=utf-8">
		
		<meta http-equiv="X-UA-Compatible" content="IE=edge">
		<meta name="google-site-verification" content="bEZIk0EIKt_AIMcHhIyOPb70_Rhf0MS15QMA01mg1_A" />
		<meta name="viewport" content="width=device-width, initial-scale=1">
		<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->

		<title><?php echo $page_title.' - '. $CFG->site_meta_title_suffix; ?></title>
		<base href="<?php echo $CFG->site_url; ?>" />
		<meta name="keywords" content="<?php echo $page_keywords; ?>" />
		<meta name="author" content="PrintableWorksheets" />
		<meta name="description" content="<?php echo $page_desc; ?>" />
		<link href="<?php echo $CFG->cdn_domain; ?>/favicon.ico" rel="shortcut icon" type="image/vnd.microsoft.icon" />

		<link rel="stylesheet" href="<?php echo $CFG->cdn_domain; ?>/css/uknc.css">
		<!-- Bootstrap 4 CSS. -->
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha256-eSi1q2PG6J7g7ib17yAaWMcrr5GrtohYChqibrV7PBE=" crossorigin="anonymous" />

		<?php	// <link rel="stylesheet" type="text/css" href="/css/jquery.floating-social-share.min.css" />
		// <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/jquery-floating-social-share@2.3.0/dist/jquery.floating-social-share.min.css" integrity="sha256-xR2B+zQtr48HjVHVPIK6Z+JEX7AVis62UqZe74T1CcE=" crossorigin="anonymous">
		?>
		<!-- Custom CSS: You can use this stylesheet to override any Bootstrap styles and/or apply your own styles -->
		<link href="<?php echo $CFG->cdn_domain; ?>/css/custom.css" rel="stylesheet">

		<!-- For icons -->
		<?php //<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous"> ?>
		<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" integrity="sha256-eZrrJcwDc/3uDhsdt61sL2oOBY362qM3lon1gyExkL0=" crossorigin="anonymous" />

		<?php echo $CFG->g_analytics_script; ?>
		<?php echo $CFG->g_page_ad_script; ?>

		<?php /*
  			<link href="/css/pandalocker.2.3.1.min.css" rel="stylesheet">
			<script type="text/javascript" src="js/pandalocker.2.3.1.min.js"></script>
		*/ ?>

		<?php /*
			// added mar 8th 2017. hide social locker for US & other high cpc countries
			if (!(in_array($geo_info['data']['country_iso'], $CFG->slocker_hide_countries))) {
		//?>
			<script>
				jQuery(document).ready(function ($) {
					$('.to-lock').sociallocker({
						theme: 'dandyish',
						overlap:{
							mode: 'blurring',
							intensity: '5'
						},
						buttons:{
							order: ["facebook-like","google-plus"],
							counters: true,
							lazy: false
						},
						facebook: { like: { url: "https://teacherworksheets.co.uk" } },
						google: { plus: { url: "https://teacherworksheets.co.uk" } },
						url: 'https://teacherworksheets.co.uk',
						text: {
							header: 'Like us to view worksheets',
							message: 'Like us once on facebook or google plus to access free worksheets..thank you.<br/>*In case you don\'t see some worksheets after liking us, please refresh the page.<br/>'
						}
					});
				});
			</script>
		//<?php
			}
 			*/
		?>
	</head>
	<body>

		<div class="container pt-5 border border-light">
		    <?php include 'includes/navbar.php' ?>
			<div class="row mt-4">
				<div class="col-sm-12"><!-- Adv Column -->
					<div class="card border-0">
						<?php echo $CFG->g_ad_search_right; ?>
						<?php //<img src="images/ad-300x250.jpg" class="rounded mx-auto d-block"> ?>
					</div>
				</div><!--/Adv Column -->
			</div>
			<!-- Search Row -->
			<div class="row mt-1 border-bottom border-primary">
				<div class="col-sm-12"><!-- Search Column -->
					<!-- Form -->
					<div class="card border border-light">
						<div class="card-header bg-light border-0">
							<form method="post" action="/client/search">
								<div class="input-group input-group-lg">
									<input type="text" class="form-control input-lg mr-1" id="s" name="s" placeholder="<?php echo $CFG->search_box_placeholder; ?>">
								    <span class="input-group-btn">
								        <button type="submit" class="btn btn-lg btn-ukblue"><span class="fa fa-search"></span></button>
								    </span>
								</div>
							</form>
						</div>
						<div class="card-body bg-white" style="height:202px; overflow-y: auto;">
							<?php
							$hlinks = $bclient->get_history_links();
							$hlinks = str_replace($CFG->site_url, '', $hlinks);
							$hlinks = str_replace('<p>', '<div class="d-flex flex-wrap">', $hlinks);
							$hlinks = str_replace('<a ', '<a class="btn btn-sm border-bottom p-0 mb-1 mr-2" ', $hlinks);
							$hlinks = str_replace('</p>', '</div>', $hlinks);
							$hlinks = str_replace('|', '', $hlinks);
							//$hlinks = str_replace('">', '" class="border rounded px-1 mx-1 mb-4">', $hlinks);
							//$hlinks = str_replace('|', '', $hlinks);
							//debug_to_console($hlinks);
							echo $hlinks;
							?>
						</div>
					</div>
				</div><!--/Search Column -->
			</div><!--/search row -->
			<!-- includes -->
			<?php
			if($request_type === 'search') {
				include 'includes/sresults.php';
			}
			else if($request_type === 'page') {
				include 'includes/content.php';
			}
			else if($request_type === 'nc') {
				include 'includes/nc_content.php';
			}
			else {
				//echo "redirecting to home";
				include 'includes/home.php';
			}
			?>
		</div><!--/container-fluid-->
		<?php include 'includes/footer.php' ?>
		<!-- Bootstrap core JavaScript
		================================================== -->
		<!-- Placed at the end of the document so the pages load faster -->

		<!-- jQuery library -->
		<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
 	    <script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.0/jquery-ui.min.js" integrity="sha256-eGE6blurk5sHj+rmkfsGYeKyZx3M4bG+ZlFyA7Kns7E=" crossorigin="anonymous"></script>
		<!-- jquery lazy library -->
		<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.lazy/1.7.10/jquery.lazy.min.js" integrity="sha256-ZPvH+DBiXs1v8yk7lmZa6+wqm+kzbwL9R1COtZ9+wjo=" crossorigin="anonymous"></script>
		<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.lazy/1.7.10/jquery.lazy.plugins.min.js" integrity="sha256-VYuzzxzkmIY1LtJUW3CU83sP845Dy2h2Otbvh4ecIEA=" crossorigin="anonymous"></script>
		<!-- Popper -->
		<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
		<!-- Bootstrap 4 JavaScript. -->
        <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha256-VsEqElsCHSGmnmHXGQzvoWjWwoznFSZc6hs7ARLRacQ=" crossorigin="anonymous"></script>
		
		<!-- Initialize Bootstrap functionality -->
		<script>
			// Initialize Lazy load component
			$(function() {
				$('.lazy').lazy();
			});
		
			// Initialize tooltip component
			$(function () {
				$('[data-toggle="tooltip"]').tooltip()
			})

			// Initialize popover component
			$(function () {
				$('[data-toggle="popover"]').popover()
			})
		</script>
		<?php //<script src="/js/jquery.floating-social-share.min.js"></script>
		     //<script src="https://cdn.jsdelivr.net/npm/jquery-floating-social-share@2.3.0/dist/jquery.floating-social-share.min.js" integrity="sha256-Wh9v88l3JPpn5UbDL1VDcxuAmd/SWzbt4jH/DT94anc=" crossorigin="anonymous"></script>
		?>
		<script>
			<?php /*
			$("body").floatingSocialShare({
				buttons: ["facebook", "twitter", "google-plus"],
				text: "share with:"
			});
			 

			$(".container").floatingSocialShare({
				buttons: [
					"facebook", "twitter", "pinterest", "reddit", "whatsapp"
				],
				text: {'default': 'share with: ', 'facebook': 'share with facebook'},
				text_title_case: true,
				twitter_counter: false,
				popup: false,
				place: "content-left"
			});
			*/ ?>
		</script>
		<?php // search suggestions
        if(isset($CFG->show_search_suggestion) && $CFG->show_search_suggestion == true) {
            ?>
            <script>
                $(function() {
                    var sugg_url = "/client/suggest?q=";
                    $("#s").autocomplete({
                        source : function(request, response) {
                            var skey = $("#s").val();
                            var URL = sugg_url + skey;
                            $.ajax({
                                url : URL,
                                success : function(data) {
                                    response($.map(data, function(value, key) {
                                        return {
                                            label : value.term
                                        }
                                    })); // end response
                                },
                                dataType : 'jsonp',
                                jsonp : 'json.wrf'
                            }); // end ajax
                        }, // end source
                        minLength : 1
                    }) // end autocompte
                });
            </script>
            <?php
        } // end search suggestions
        ?>
		<?php
			if(isset($geo_info['data']['country_iso']) && in_array($geo_info['data']['country_iso'], $CFG->eu_countries)) {
		?>
				<link rel="stylesheet" type="text/css" href="//cdnjs.cloudflare.com/ajax/libs/cookieconsent2/3.0.3/cookieconsent.min.css" />
				<script src="//cdnjs.cloudflare.com/ajax/libs/cookieconsent2/3.0.3/cookieconsent.min.js"></script>
				<script>
					window.addEventListener("load", function(){
						window.cookieconsent.initialise({
							"palette": {
								"popup": {
									"background": "#efefef",
									"text": "#404040"
								},
								"button": {
									"background": "#8ec760",
									"text": "#ffffff"
								}
							},
							"theme": "classic",
							"content": {
								"message": "This website uses <a href='https://cookiesandyou.com' target='_blank'>cookies</a> as explained in our <a href='/privacy-policy' target='_blank'>privacy policy</a> notice to offer you a better browsing experience. ",
								"link": "Learn more...",
								"dismiss": "Got it!",
								"href": "https://cookiesandyou.com"
							}
						})});
				</script>
		<?php
			}
		?>
	</body>
</html>

<?php
$content = minify_html( ob_get_clean() );
echo $content;
?>