<?php
class ControllerCommonHeader extends Controller {

    private function setcookieSameSite($name, $value, $expire, $path, $domain, $secure, $httponly) {

        if (PHP_VERSION_ID < 70300) {
            @setcookie($name, $value, $expire, "$path; samesite=None", $domain, $secure, $httponly);
        }
        else {
            @setcookie($name, $value, [
                'expires' => $expire,
                'path' => $path,
                'domain' => $domain,
                'samesite' => 'None',
                'secure' => $secure,
                'httponly' => $httponly,
            ]);
        }
    }

    public function campaignControl()
    {

        $json = array();

        //https://www.deercase.com/?campaign=4al2ode
        //unset($this->session->data['campaign']); die();

            if($this->request->get['localstorage'] == 'true'){
                $json['status'] = false;
            }else if(isset($this->session->data['campaign'])){
                $calc_kill_time = $this->session->data['campaign']['k_date'] - $this->session->data['campaign']['c_date'];
                if($calc_kill_time == 0){
                    $this->session->data['campaign']['status'] = false;
                    $json['set_localstorage'] = true;
                }
                $json = $this->session->data['campaign'];
            }else if(isset($this->request->get['campaign']) AND $this->request->get['campaign'] == '4al2ode'){
                //echo 3;
                $this->session->data['campaign'] = array(
                    'status' => true,
                    'name' => '4al2ode',
                    'title' => '4 Al 2 Öde',
                    'description' => '4 al 2 öde kampanyası için yapılan session işlemi',
                    'create_date' => @date('Y-m-d H:i:s'),
                    'kill_date' => date("F j ") . date('Y H:i:s', strtotime('+20 minutes')),
                    'c_date' => strtotime('now'),
                    'k_date' => strtotime('+20 minutes'),
                    'used_total' => 0,
                );
                $json = $this->session->data['campaign'];
            }


        $this->response->addHeader('Content-Type: application/json');
        $this->response->setOutput(json_encode($json));



    }

    public function campaignControlCheck()
    {

        $json = array();

        if(isset($this->session->data['campaign'])){
            if($this->session->data['campaign']['status']){
                //var_dump($this->session->data['campaign']['status']);
                $json['status'] = true;
            }else{
                $json['status'] = false;
            }
        }


        $this->response->addHeader('Content-Type: application/json');
        $this->response->setOutput(json_encode($json));



    }

    public function index() {
        
         //open_graphs
        $data['open_graphs'] = $this->load->controller('extension/module/pinta_open_graph');
        // Security Headers
		$this->load->model('setting/setting');
		$get_security_headers_settings = $this->model_setting_setting->getSetting('security_headers', (int)$this->config->get('config_store_id'));
		$security_headers_settings = isset($get_security_headers_settings['security_headers_settings']) ? $get_security_headers_settings['security_headers_settings'] : false;

		if ($security_headers_settings and $security_headers_settings['status']) {

		        if (isset($security_headers_settings['forward']) && $security_headers_settings['forward']) {
		        $forward_headers = array(       'CLIENT_IP','FORWARDED','FORWARDED_FOR',
		                                        'FORWARDED_FOR_IP','VIA','X_FORWARDED',
		                                        'X_FORWARDED_FOR','HTTP_CLIENT_IP',
		                                        'HTTP_FORWARDED','HTTP_FORWARDED_FOR',
                                                        'HTTP_FORWARDED_FOR_IP','HTTP_PROXY_CONNECTION',
                                                        'HTTP_VIA','HTTP_X_FORWARDED','HTTP_X_FORWARDED_FOR'
                                                );
		                foreach ($forward_headers as $key => $header) {
		                                $this->response->delHeader($header);
		                }
		        }

		        if (isset($security_headers_settings['ranges']) && $security_headers_settings['ranges']) {
		        $range_headers = array('Accept-Ranges','Content-Range','Range','If-Range');
		                foreach ($range_headers as $key => $header) {
                                                $this->response->delHeader($header);
		                }
		            $this->response->addHeader("Accept-Ranges: none");
		        }

		        if (isset($security_headers_settings['proxy']) && $security_headers_settings['proxy']) {
		                $this->response->delHeader('Proxy');
                        }

		        if (isset($security_headers_settings['X_HTTP_Method_Override']) && $security_headers_settings['X_HTTP_Method_Override']) {
                                $this->response->delHeader('X-HTTP-Method-Override');
                        }

		        if (isset($security_headers_settings['X_Powered_By']) && $security_headers_settings['X_Powered_By']) {
		                $this->response->delHeader('X-Powered-By');
                        }

		        if (!empty($security_headers_settings['X_XSS_Protection'])) {
		                $this->response->delHeader('X-XSS-Protection');
		                $this->response->addHeader('X-XSS-Protection: '.$security_headers_settings['X_XSS_Protection']);
		        }

		        if (!empty($security_headers_settings['X_Frame_Options'])) {
		                $this->response->delHeader('X-Frame-Options');
		                $this->response->addHeader('X-Frame-Options: '.$security_headers_settings['X_Frame_Options']);
                        }

		        if (!empty($security_headers_settings['X_Content_Type_Options'])) {
		                $this->response->delHeader('X-Content-Type-Options');
		                $this->response->addHeader('X-Content-Type-Options: '.$security_headers_settings['X_Content_Type_Options']);
		        }

		        if (!empty($security_headers_settings['Referrer_Policy'])) {
		                $this->response->delHeader('Referrer-Policy');
		                $this->response->addHeader('Referrer-Policy: '.$security_headers_settings['Referrer_Policy']);
		        }

		        $isSSL = $this->model_setting_setting->getSetting('config', (int)$this->config->get('config_store_id'))['config_secure'];
		        if ((int)$isSSL > 0) {
        		        if (!empty($security_headers_settings['CSP'])) {
        		                $this->response->delHeader('Content-Security-Policy');
        		                $this->response->addHeader('Content-Security-Policy: '.$security_headers_settings['CSP']);
        		        }

        		        if (!empty($security_headers_settings['Strict_Transport_Security'])) {
        		                $this->response->delHeader('Strict-Transport-Security');
                                        $this->response->addHeader('Strict-Transport-Security: max-age='.$security_headers_settings['Strict_Transport_Security'].';');
                                }
                        }
                        if (!empty($security_headers_settings['Expect_CT'])) {
                                $this->response->delHeader('Expect-CT');
                                if (!empty($security_headers_settings['Expect_CT']['max_age'])) {
                                        if (!empty($security_headers_settings['Expect_CT']['report_uri'])) {
                                                $this->response->addHeader('Expect-CT: max-age='.$security_headers_settings['Expect_CT']['max_age'].'; '.$security_headers_settings['Expect_CT']['report_uri']);
                                        }
                                }
                        }
                        $fp_header = '';
                        $this->response->delHeader('Feature-Policy');
                        foreach ($security_headers_settings['Feature_Policy'] as $key => $value) {
                                if (!empty($value)) {
                                        $fp_header .= $key." ".$value."; ";
                                }
                        }
                        $fp_header = str_replace('_','-',$fp_header);
                        !empty($fp_header) ? $this->response->addHeader('Feature-Policy: '.$fp_header) : false;
		}
		// Security Headers


        #Google Ads
        $data['gaecmadwconv_module'] = $this->load->controller('extension/gaecmadwconv');
        $data['gaecmadwconvfootjs_module'] = $this->load->controller('extension/gaecmadwconv/footjs');
        #Google Ads


        #FaceBook Conversion
        $facebook_events = $this->load->controller('extension/module/facebook_events');

        #FaceBook Pixel
        $data['facebook_pixel_id_FAE'] = $this->fbevents['facebook_pixel_id_FAE'];
        $data['facebook_pixel_pii_FAE'] = $this->fbevents['facebook_pixel_pii_FAE'];
        $data['facebook_pixel_params_FAE'] = $this->fbevents['facebook_pixel_params_FAE'];
        $data['facebook_pixel_event_params_FAE'] = $this->fbevents['facebook_pixel_event_params_FAE'];
        $data['facebook_enable_cookie_bar'] = $this->fbevents['facebook_enable_cookie_bar'];
        unset($this->session->data['facebook_pixel_event_params_FAE']);
        #FaceBook Pixel


        if ($this->request->server['HTTPS']) {
            $server = $this->config->get('config_ssl');
        } else {
            $server = $this->config->get('config_url');
        }

        if (is_file(DIR_IMAGE . $this->config->get('config_icon'))) {
            $this->document->addLink($server . 'image/' . $this->config->get('config_icon'), 'icon');
        }

        if (!isset($this->request->get['route'])) {
            $titles = $this->document->getTitle();
            if (isset($titles[(int) $this->config->get('config_language_id')])) {
                $data['title'] = $titles[(int) $this->config->get('config_language_id')];
            } else {
                $data['title'] = $this->document->getTitle();
            }
        } elseif ($this->request->get['route'] == 'common/home') {
            $titles = $this->document->getTitle();
            if (isset($titles[(int) $this->config->get('config_language_id')])) {
                $data['title'] = $titles[(int) $this->config->get('config_language_id')];
            } else {
                $data['title'] = $this->document->getTitle();
            }
        } else {
            $data['title'] = $this->document->getTitle();
        }

        $data['title'] = $this->document->getTitle();
        $data['alternate'] = '';
        
        $data['store_name'] = $this->config->get('config_name');
        if ( $this->config->get('config_support') ) {
        $data['support'] = trim($this->config->get('config_support'));
        } else {
        $data['support'] = '';
        }
        if ($this->config->get('config_social')) {
        $social = preg_replace('/\s+/', '', $this->config->get('config_social'));
        $social = explode(',', $social);
        $social_jsarr = '';
        foreach ($social as $k => $v) {
          $social_jsarr .= '"' . $v . '",';
        }
        $data['social'] = rtrim($social_jsarr, ",");
        } else {
        $data['social'] = '';
        }
        
        $this->load->language('common/header');
        $data['base'] = $server;
        $data['description'] = $this->document->getDescription();
        $data['keywords'] = $this->document->getKeywords();
        $data['links'] = $this->document->getLinks();
        $data['styles'] = $this->document->getStyles();
        $data['metaProperties'] = $this->document->getMetaProperties();
        $data['metaTags'] = $this->document->getMetaTags();
        $data['scripts'] = $this->document->getScripts();
        $data['lang'] = $this->language->get('code');
        $data['direction'] = $this->language->get('direction');
        $data['name'] = $this->config->get('config_name');
        $data['button_cart'] = $this->language->get('button_cart');
        $data['text_customcase'] = $this->language->get('text_customcase');
        $data['customcase_href'] = $this->url->link('piyerSoft/cases/customcase', '&brand=Apple&model=1180', true);

        $data['config_email'] = $this->config->get('config_email');


        //Sipariş sorgulama #Bilal 16/04/2019
        $data['guest_order'] = $this->url->link('account/guestorder', '', true);
        $data['guest_order_view'] = $this->language->get('auto_logo');
        //Sipariş sorgulama #Bilal 16/04/2019

        if (is_file(DIR_IMAGE . $this->config->get('config_logo'))) {
            $data['logo'] = $server . 'image/' . $this->config->get('config_logo');
        } else {
            $data['logo'] = '';
        }

        $this->document->setFBog($data['logo']);
        $data['fbogimg'] = $this->document->getFBog();

        $is_logged = $this->customer->isLogged();


        // Wishlist
        if ($is_logged) {
            $this->load->model('account/wishlist');
            $data['text_wishlist'] = sprintf($this->language->get('text_wishlist'), $this->model_account_wishlist->getTotalWishlist());

        } else {
            $data['text_wishlist'] = sprintf($this->language->get('text_wishlist'), (isset($this->session->data['wishlist']) ? count($this->session->data['wishlist']) : 0));
        }

        $data['text_shopping_cart'] = $this->language->get('text_shopping_cart');
        $data['text_logged'] = sprintf($this->language->get('text_logged'), $this->url->link('account/account', '', true), $this->customer->getFirstName(), $this->url->link('account/logout', '', true));

        $data['text_account'] = $this->language->get('text_account');
        $data['text_register'] = $this->language->get('text_register');
        $data['text_login'] = $this->language->get('text_login');
        $data['text_order'] = $this->language->get('text_order');
        $data['text_logout'] = $this->language->get('text_logout');
        $data['text_checkout'] = $this->language->get('text_checkout');
        $data['text_category'] = $this->language->get('text_category');
        $data['heading_title'] = $this->language->get('heading_title');

        $data['home'] = $this->url->link('common/home', '', true);
        $data['wishlist'] = $this->url->link('account/wishlist', '', true);
        $data['logged'] = $this->customer->isLogged();
        $data['account'] = $this->url->link('account/account', '', true);
        $data['register'] = $this->url->link('account/register', '', true);
        $data['login'] = $this->url->link('account/login', '', true);
        $data['order'] = $this->url->link('account/order', '', true);
        $data['logout'] = $this->url->link('account/logout', '', true);
        $data['shopping_cart'] = $this->url->link('checkout/cart', '', true);

        $data['cart_item'] = 0;

        $data['checkout'] = $this->url->link('checkout/checkout', '', true);
        $data['contact'] = $this->url->link('information/contact', '', true);
        $data['mytemplate'] = $this->config->get('theme_default_directory');

        $data['contact'] = $this->url->link('information/contact');
        $data['return'] = $this->url->link('account/return/add', '', true);
        $data['sitemap'] = $this->url->link('information/sitemap');
        $data['affiliate'] = $this->url->link('affiliate/account', '', true);
        $data['voucher'] = $this->url->link('account/voucher', '', true);
        $data['manufacturer'] = $this->url->link('product/manufacturer');
        $data['entry_email'] = $this->language->get('entry_email');
        $data['entry_password'] = $this->language->get('entry_password');
        $data['button_login'] = $this->language->get('button_login');
        $data['text_forgotten'] = $this->language->get('text_forgotten');


	


        //$this->load->model('catalog/category');

        // CACHE CATEGORY JSON BİLAL 26/02/2019
        //$data['categories'] = $this->model_catalog_category->getJsonCategory();
        // CACHE CATEGORY JSON BİLAL 26/02/2019

        $data['search'] = $this->load->controller('common/search');
        $data['currency'] = $this->load->controller('common/currency');
        $data['cart'] = $this->load->controller('common/cart');
        $data['column_login'] = $this->load->controller('common/column_login');

        // For page specific css
        if (isset($this->request->get['route'])) {
            if (isset($this->request->get['product_id'])) {
                $class = '-' . $this->request->get['product_id'];
            } elseif (isset($this->request->get['path'])) {
                $class = '-' . $this->request->get['path'];
            } elseif (isset($this->request->get['manufacturer_id'])) {
                $class = '-' . $this->request->get['manufacturer_id'];
            } elseif (isset($this->request->get['information_id'])) {
                $class = '-' . $this->request->get['information_id'];
            } else {
                $class = '';
            }

            $data['class'] = str_replace('/', '-', $this->request->get['route']) . $class;
        } else {
            $data['class'] = 'common-home';
        }

        $data['headertop'] = $this->load->controller('common/headertop');

        return $this->load->view(DIR_LOCAL_TEMPLATE . $this->config->get('theme_default_directory') . '/template/common/header', $data);

    }

    public function clearCache() {
        if (!$this->request->post) {
            die;
        }
        $dir = DIR_CACHE;
        $cachefiles = $this->request->post['cachefiles'];

        foreach ($cachefiles as $file) {
            $this->DeleteFiles($dir . $file);
        }
        echo '1';

        /* if (is_dir($dir)) {
          if ($handle = opendir($dir)) {
          while (($file = readdir($handle)) !== false) {
          if ($file != "." && $file != ".." && $file != "Thumbs.db") {
          unlink($dir . $file);
          }
          }
          closedir($handle);
          }
          }
         */
    }

    public function DeleteFiles($target) {
        if (is_dir($target)) {
            $target = $target . '/';
            $files = glob($target . '*', GLOB_MARK); //GLOB_MARK adds a slash to directories returned
            foreach ($files as $file) {
                $this->DeleteFiles($file);
            }
            rmdir($target);
        } elseif (is_file($target)) {
            unlink($target);
        }
    }

    public function getCacheData() {
        $dir = DIR_CACHE;
        if (is_dir($dir)) {
            $all_files = scandir($dir, '0');
            if ($all_files)
                for ($i = 0; $i < count($all_files); $i++) {
                    if ($all_files[$i] != "." && $all_files[$i] != ".." && $all_files[$i] != "Thumbs.db") {
                        echo '<div class="col-md-6 checkbox">
                     <label> <input type="checkbox" name="cache_files[]" value="' . $all_files[$i] . '"> ' . $all_files[$i] . '</label>
                    </div>';
                    }
                }
        }
    }

    public function getLoginData()
    {

        $is_logged = $this->customer->isLogged();

        if ($is_logged) {
            $this->load->language('common/header');
            
            $account = $this->url->link('account/account', '', true);
            $logout = $this->url->link('account/logout', '', true);

            $text_account = $this->language->get('text_account');
            $text_logout = $this->language->get('text_logout');

            $data = '<li class="AccountDD__Item"><a class="AccountDD__ItemLink" href="'.$account.'">'.$text_account.'</a></li>'.
                '<li class="AccountDD__Item"><a class="AccountDD__ItemLink" href="'.$logout.'">'.$text_logout.'</a></li>';

            echo $data;
        }
        else {
            echo '';
        }

        return true;
    }

    public function getCartData()
    {
        $cart = $this->load->controller('common/cart');
        // dd($cart);

        echo $cart;
        return true;

    }

}
