<?php
//error_reporting(ALL);
//echo phpinfo();
//exit();
//ini_set('display_errors', 1);
//ini_set('display_startup_errors', 1);
error_reporting(0);
header('X-Powered-By:');
header_remove("X-Powered-By");
require_once 'Lib/DotEnv.php';
require_once 'Lib/CommonHelper.php';
require_once 'Lib/RequestHelper.php';
use Lib\DotEnv as DotEnv;
use Lib\CommonHelper as CommonHelper;
use Lib\RequestHelper as RequestHelper;

$commonhelper = new CommonHelper();


# Handle Cookie accept or deny
if(file_exists('curlCookieInfo.php')){
    require_once('curlCookieInfo.php');
}

#Load Env file for get the Config Details from .env file
(new DotEnv(__DIR__ . '/.env'))->load();

    try{
        #-------------------------------------------------------------------------------------
            #Minify Output
        #-------------------------------------------------------------------------------------
        function minify_output($buffer){
            $search = array(
                '/\>[^\S ]+/s',
                '/[^\S ]+\</s',
                '/(\s)+/s'
            );
            $replace = array(
                '>',
                '<',
                '\\1'
            );
            if (preg_match("/\<html/i",$buffer) == 1 && preg_match("/\<\/html\>/i",$buffer) == 1) {
                $buffer = preg_replace($search, $replace, $buffer);
            }
            return $buffer;
        }
        ob_start("minify_output");
        #-------------------------------------------------------------------------------------
            #Minify Output End
        #-------------------------------------------------------------------------------------

        #-------------------------------------------------------------------------------------
            #Variable Declaration
        #-------------------------------------------------------------------------------------
        $store_url = '';
        #store locator default url
        $folderName = $commonhelper->folderName;
        $store_locator_url = $commonhelper->prepareStoreLocatorUrl($folderName);

        #define config settings for error files

        #define config settings for error files
        $error_files_array =  CommonHelper::getErrorFiles();
        #define array for error files ends
        #-------------------------------------------------------------------------------------
            #Variable Declaration End
        #-------------------------------------------------------------------------------------
        

        #-------------------------------------------------------------------------------------
            #Sanetize input request
        #-------------------------------------------------------------------------------------
        $sanetizedRequest = RequestHelper::sanitizeRequest($_REQUEST);
        #-------------------------------------------------------------------------------------
            #Sanetize input request End
        #-------------------------------------------------------------------------------------

        #-------------------------------------------------------------------------------------
            #CREATE URL (prepare Store Url)
        #-------------------------------------------------------------------------------------
        $store_url .= RequestHelper::prepareStoreUrlByRequest($commonhelper->si_domain,$folderName,$store_locator_url,$sanetizedRequest);
        // print_r($store_url); exit;
        #-------------------------------------------------------------------------------------
            #CREATE URL (prepare Store Url) End
        #-------------------------------------------------------------------------------------

        
        #-------------------------------------------------------------------------------------
            #DEFINE VARIABLES DEPENDING ON THE REQUEST
        #-------------------------------------------------------------------------------------
        if(isset($sanetizedRequest['store_locator_id'])) {
            #store locator
            $state = $city = $locality = $latitude = $longitude = $search = $location_url = $state_name = $city_name = $locality_name = $circle_name = $crs = $radius = $shared = '';
            if(in_array($sanetizedRequest['page_type'], array('storelocator')) && !empty($sanetizedRequest['store_locator_id'])) {
                #if pagination is there on store locator
                $store_url_page_option_with_ampersand = $store_url_page_option_without_ampersand = $url_received = '';
                if(isset($sanetizedRequest['page'])) {
                    if($sanetizedRequest['page'] > 0) {
                        $store_url_page_option_with_ampersand = '&page='.$sanetizedRequest['page'];
                        $store_url_page_option_without_ampersand = '?page='.$sanetizedRequest['page'];
                    }
                }
                #if pagination is there on store locator ends
                
                if(isset($sanetizedRequest['lat'])) {
                    $store_url = $commonhelper->prepareStoreUrlWithLatLong($sanetizedRequest,$store_url_page_option_with_ampersand);
                    //print_r($store_url); exit;
                    $url_received = 1;
                }
                
                if(isset($sanetizedRequest['search'])) {
                    $store_url = $commonhelper->prepareStoreUrlWithSearch($sanetizedRequest,$store_url_page_option_with_ampersand);
                    $url_received = 1;
                }
                
                if(isset($sanetizedRequest['state'])) {
                    $store_url = $commonhelper->prepareStoreUrlWithStateCityLocality($sanetizedRequest,$store_url_page_option_with_ampersand);
                    $url_received = 1;
                }
                
                if(isset($sanetizedRequest['state_name']) or isset($sanetizedRequest['circle_name']) or isset($sanetizedRequest['crs'])) {
                    $store_url = $commonhelper->prepareStoreUrlWithStateNameCityNameCircleNameEtc($sanetizedRequest,$store_url_page_option_with_ampersand);
                    $url_received = 1;
                }
                
                if(isset($sanetizedRequest['state_alias'])) {
                    $location_url_alias = $commonhelper->prepareStoreUrlWithStateCityLocationAlias($sanetizedRequest,$store_url_page_option_with_ampersand);
                    
                    if(!empty($location_url_alias)) {
                        $store_url = $commonhelper->si_domain.$sanetizedRequest['page_type'].'/'.$sanetizedRequest['store_locator_id'].'/location/'.$location_url_alias .'?no_redirect=1'.$store_url_page_option_with_ampersand;
                        $url_received = 1;
                    }
                }
                
                #this is for map view
                $view_option = '';
                if(isset($sanetizedRequest['view']) && !empty($sanetizedRequest['view']) && in_array($sanetizedRequest['view'], array('map'))) {
                    $view_option = '';
                    $store_url = $commonhelper->prepareStoreUrlForMapView($sanetizedRequest,$store_url_page_option_with_ampersand);
                    $url_received = 1;
                }
                
                if(isset($sanetizedRequest['location_url'])) {
                    if(!empty($sanetizedRequest['location_url'])) {
                        $location_url = filter_var(urlencode($sanetizedRequest['location_url']), FILTER_UNSAFE_RAW);
                    }
                    $store_url = $commonhelper->si_domain.$sanetizedRequest['page_type'].'/'.$sanetizedRequest['store_locator_id'].'/'.$location_url .'?no_redirect=1'.$store_url_page_option_with_ampersand;
                    $url_received = 1;
                }
                if(empty($url_received)) {
                    $store_url = $store_locator_url.$store_url_page_option_with_ampersand;
                }
            } 
        }
        if(isset($sanetizedRequest['page_type']) && $sanetizedRequest['page_type'] == 'storelocator') {
            //Explode
            $urlToModify = explode('?', $store_url);
            #if pagination is there on store locator
            $store_url_page_option_with_ampersand = $store_url_page_option_without_ampersand = $url_received = '';
            if(isset($sanetizedRequest['page'])) {
                if($sanetizedRequest['page'] > 0) {
                    $store_url_page_option_with_ampersand = '&page='.$sanetizedRequest['page'];
                    $store_url_page_option_without_ampersand = '?page='.$sanetizedRequest['page'];
                }
            }
            #if pagination is there on store locator ends
            #store locator
            if(isset($sanetizedRequest['state_alias'])) {
                $location_url_alias = $commonhelper->prepareStoreUrlWithStateCityLocationAlias($sanetizedRequest,$store_url_page_option_with_ampersand);
                if(!empty($location_url_alias)) {
                    $store_url = $urlToModify[0].'/location/'.$location_url_alias .'?no_redirect=1'.$store_url_page_option_with_ampersand;
                    $url_received = 1;
                }
            }

            if(isset($sanetizedRequest['location_url'])) {
                if(!empty($sanetizedRequest['location_url'])) {
                    $location_url = filter_var(urlencode($sanetizedRequest['location_url']), FILTER_UNSAFE_RAW);
                }
                $store_url = $urlToModify[0].'/'.$location_url .'?no_redirect=1'.$store_url_page_option_with_ampersand;
                $url_received = 1;
            }
            if(isset($sanetizedRequest['search'])) {
                $store_url = $commonhelper->prepareStoreUrlWithSearch($sanetizedRequest,$store_url_page_option_with_ampersand);
                $url_received = 1;
            }
            if(isset($sanetizedRequest['lat'])) {
                $store_url = $commonhelper->prepareStoreUrlWithLatLong($sanetizedRequest,$store_url_page_option_with_ampersand);
                $url_received = 1;
            }
            if(empty($url_received)) {
                $store_url = $store_locator_url.$store_url_page_option_with_ampersand;
            }
        }
        #-------------------------------------------------------------------------------------
            #DEFINE VARIABLES DEPENDING ON THE REQUEST ENDS
        #-------------------------------------------------------------------------------------
        
        if(empty($store_url)) {
            $store_url = $store_locator_url.$store_url_page_option_with_ampersand;
        }
        
        
        #-------------------------------------------------------------------------------------
            #fetch any other requests like JUMPIDS
        #-------------------------------------------------------------------------------------
        if(isset($_REQUEST)) {
            $store_url = $commonhelper->prepareStoreUrlWithJumpIdsEtc($sanetizedRequest,$store_url);
        }
        #-------------------------------------------------------------------------------------
            #fetch any other requests like JUMPIDS ends
        #-------------------------------------------------------------------------------------

        $ip = CommonHelper::getRealIpAddr();
        $cladipvalue = $ip;
        $cladipkey = CommonHelper::generateMdId($ip);
        if($cladipvalue) {
            $store_url .= '&cladipvalue='.filter_var(urlencode($cladipvalue), FILTER_UNSAFE_RAW).'&cladipkey='.filter_var(urlencode($cladipkey), FILTER_UNSAFE_RAW);
        }
        #get IP ends

        #-------------------------------------------------------------------------------------
            #Pass Master outlet id as well along with URL for authentication of URL ALias
        #-------------------------------------------------------------------------------------
        $kryKey = md5($commonhelper->common_outlet_id.'UYy66545100Ajjfhyr67731110ojne').'lOpa98';
        $store_url .= '&master_outlet_id='.$commonhelper->common_outlet_id."&krykey=".$kryKey."&check_client=1";
        #-------------------------------------------------------------------------------------
            #Pass Master outlet id as well along with URL for authentication of URL ALias ends
        #-------------------------------------------------------------------------------------
        

        #-------------------------------------------------------------------------------------
            #ANY ADDITIONAL PARAMS ADDED NEEDS TO BE IGNORED FOR STORE LOCATOR JS
            #Process some URLs with Cloudfront
        #-------------------------------------------------------------------------------------
        $store_url = $commonhelper->manageCloudFrontSetting($sanetizedRequest,$store_url);
        #-------------------------------------------------------------------------------------
            #Ends Process some URLs with Cloudfront
        #-------------------------------------------------------------------------------------

        // print_r($store_url); exit;
        #-------------------------------------------------------------------------------------
            #GET WEBPAGE START
        #-------------------------------------------------------------------------------------
        // print_r($store_url); exit;
        $result = CommonHelper::get_web_page( $store_url );
        #-------------------------------------------------------------------------------------
            #GET WEBPAGE ENDS
        #-------------------------------------------------------------------------------------


        #-------------------------------------------------------------------------------------
            #Handle SERVICE IS DOWN
            #hit html files in case services are down
        #-------------------------------------------------------------------------------------
        if(isset($_REQUEST['down'])) {
            $result['http_code'] = 400;
        }
        if(strpos($result['content'], 'have our <span class="blueUnder">engineers</span> fix it. </p>')) {
            $result['http_code'] = 400;
        }
        if(strpos($result['content'], 'Requested URL is not valid')) {
            $result['http_code'] = 400;
        }
        if(strpos($result['content'], 'Request not recognised')) {
            $result['http_code'] = 400;
        }
        if ( $result['errno'] != 0 ) {
            //echo $client_domain. ' is Coming soon.';exit;
            header("Location: ".$commonhelper->client_domain."error.html");
        }
        if ( $result['http_code'] != 200 ) {
            ///echo $client_domain.' is Coming soon.';exit;
            header("Location: ".$commonhelper->client_domain."error.html");///this could be a different url too for errors
        }
        #-------------------------------------------------------------------------------------
            #SERVICE IS DOWN ENDS
        #-------------------------------------------------------------------------------------
        

        #-------------------------------------------------------------------------------------
            #check for redirecting to client website if applicable
        #-------------------------------------------------------------------------------------
        if(substr_count($result['content'], "REDIRECT-TO-CLIENT-WEBSITE")) {
            $page = str_replace('REDIRECT-TO-CLIENT-WEBSITE:','',$result['content']);
            if(!empty($page)) {
                header("Location: ".$page);
            }
        }
        #-------------------------------------------------------------------------------------
            #check for redirecting to client website if applicable ends
        #-------------------------------------------------------------------------------------



        #-------------------------------------------------------------------------------------
            #REPLACE DATA WE ARE GETTING AFTER HITTING SINGLEINTERFACE
        #-------------------------------------------------------------------------------------
        $page = $result['content'];
        $page = $commonhelper->manuplateResponseString($page,$sanetizedRequest);
        #-------------------------------------------------------------------------------------
            #REPLACE DATA WE ARE GETTING AFTER HITTING SINGLEINTERFACE END
        #-------------------------------------------------------------------------------------


        #-------------------------------------------------------------------------------------
            #Cookie accepted flag removed from query param
        #-------------------------------------------------------------------------------------
        if(file_exists('curlCookieInfo.php') && function_exists('removeCookieFlagFromQueryParam')){
            // $page = removeCookieFlagFromQueryParam($page);
        }
        #-------------------------------------------------------------------------------------
            #Cookie accepted flag removed from query param end
        #-------------------------------------------------------------------------------------
        

        #-------------------------------------------------------------------------------------
            #migration changes
        #-------------------------------------------------------------------------------------
        $page = $commonhelper->migrationChanges($page,$sanetizedRequest);
        #-------------------------------------------------------------------------------------
            #migration changes end
        #-------------------------------------------------------------------------------------
        print_r($page);
    }catch(Exception $ex){
        print_r($ex->getMessage());
    }    
    ob_end_flush();
?>
