<?php
/**
 * handler for url params
 * 
 * @example
 * ?utm_campaign=Testkampagne&utm_source=Testquelle&utm_medium=Testmedium&utm_content=Testinhalt&utm_term=Testterm
 */
if( ! defined( 'ABSPATH' ) ) exit;

new url_handler();
class url_handler {
    
    function __construct() {
        // save url params as cookies
        add_action('parse_request', array($this, 'set_url_cookies'), 10);
    }
    
    // URL PARAMETER
    
    // Url & Cookie Vars
    public static $params = array(
        array(
            "nicename"  => "Google Campaign Name (utm_campaign)",
            "name"      => "utm_campaign",
            "url"       => "utm_campaign",
            "cookie"    => "greyd_tp_google_campaign_name"
        ),
        array(
            "nicename"  => "Google Campaign Source (utm_source)",
            "name"      => "utm_source",
            "url"       => "utm_source",
            "cookie"    => "greyd_tp_google_campaign_source"
        ),
        array(
            "nicename"  => "Google Campaign Medium (utm_medium)",
            "name"      => "utm_medium",
            "url"       => "utm_medium",
            "cookie"    => "greyd_tp_google_campaign_medium",
        ),
        array(
            "nicename"  => "Google Campaign Term (utm_term)",
            "name"      => "utm_term",
            "url"       => "utm_term",
            "cookie"    => "greyd_tp_google_campaign_term"
        ),
        array(
            "nicename"  => "Google Campaign Content (utm_content)",
            "name"      => "utm_content",
            "url"       => "utm_content",
            "cookie"    => "greyd_tp_google_campaign_content"
        )
    );
    
    // static var for saving cookies
    public static $cookies = array();
    public static $url_params = array();
    public static $all_url_params = array();
    public static $all_cookies = array();
    
    /**
     *  @filter 'greyd_add_url_params'
     *  
     *  added params are then used in all depending functions
     *  this way other plugins/functions can hook into this process and store url-params as cookies
     *  new cookies must be set with the following syntax:
     *  $add = array(
     *      array(
     *          "nicename"  => string (optional)    |   shown name, eg. in the vc-module „Conditional Content“
     *          "name"      => string (required)    |   key for saving it in arrays within this class
     *          "url"       => string (required)    |   the key of the url-parameter to look for
     *          "cookie"    => string (required)    |   unique name of the SESSION-cookie that will be saved
     *          ( + custom params )
     *      )
     *  )
     */
    public static function get_params() {
        $extra_params = apply_filters('greyd_add_url_params', array());
        self::$params = array_merge(self::$params, $extra_params);
        return self::$params;
    }
    
    
    // SET url params as cookies
    // & STORE default cookies in this class
    public function set_url_cookies() {
        
        if ( is_admin() ) return;
        
        $days   = 1; // after how many days the cookie expires
        $time   = time()+60*60*24*$days; // currenttime * sec * min * hours * days
        $params = self::get_params();
        //debug($params);
        
        if ( !isset($_SESSION) ){

			// close session to prevent session blocking
			session_write_close();

            session_set_cookie_params($time, '/');
            session_start();
        } else {
            setcookie(session_name(),session_id(),time()+$time);
        }
        
        foreach($params as $i => $param) {
            $name   = $param["name"];
            $url    = $param["url"];
            $cookie = $param["cookie"];
            
            // if URL param is set
            if (isset($_GET[$url])) {
                $value = $_GET[$url];
                
                /**
                 *  @filter 'greyd_set_url_param-{{param_name}}'
                 *  
                 *  manipulate value of url-param
                 */
                $value = apply_filters("greyd_set_url_param-".$name, $value);
                
                // check if session_param already exists
                if (isset($_SESSION[$cookie])) {
                    // is session_param still the same?
                    if ($_SESSION[$cookie] !== $value){
                        $_SESSION[$cookie] = $value;
                    }
                } else {
                    // else set session_param
                    $_SESSION[$cookie] = $value;
                }
                // save in cookies & url_params var
                self::$url_params[$name] = $value;
                self::$cookies[$name] = $value;
                
            } else {
                // save SESSION params in class
                if (isset($_SESSION[$cookie]))
                    self::$cookies[$name] = $_SESSION[$cookie];
            }
        }
        
        // save all session_params
        foreach ((array)$_SESSION as $key => $val) {
            self::$all_cookies[$key] = $val;
        }
        //debug(self::$all_cookies);
        
        // save all url_params
        foreach ($_GET as $key => $val) {
            self::$all_url_params[$key] = $val;
        }
        // debug(self::get_all_cookie_values());
    }
    
    // GET default values stored as cookies
    public static function get_cookie_values() {
        return self::$cookies;
    }
    
    // GET default url-param values
    public static function get_url_values() {
        return self::$url_params;
    }
    
    // GET all cookie values
    public static function get_all_cookie_values() {
        return self::$all_cookies;
    }
    
    // GET all url-param values
    public static function get_all_url_values() {
        return self::$all_url_params;
    }
}

