<?php

if (!defined('ABSPATH')) {
    die('-1');
}

include_once "lib/CptCampaign.php";

if (!class_exists('CampaignController')) {

    define("kCampaignPath", dirname(__FILE__));
    define("kPLUGIN_DIR_URL", plugin_dir_url(__FILE__));
    define("kPLUGIN_DIR_PATH", plugin_dir_path(__FILE__));

    class CampaignController {
        const DEFAULT_PHONE_NUMBER = '800-800-2537';
        const DEFAULT_CAMPAIGN_ID = '7011I000000dDwA';
        const DEFAULT_FIVE9 = 'Web Form Submissions H';

        const kREST_ACTION = "GetWebCampaigns";
        const kCOOKIE_ID = "SESScampaignid";
        const kCOOKIE_CAMPAIGN_NAME = "SESScampaignname";
        const kCOOKIE_ID_FIVE9 = "SESSfive9";
        const kCOOKIE_WEB_PROMOTION_TEXT = "SESSpromotion";
        const kCOOKIE_PHONE = "SESScampaignphone";

        protected static $instance;

        public function __construct() {
            add_action('init', array($this, 'start_session'), 1);

            add_action('plugins_loaded', array($this, 'plugins_loaded'));
            add_action('admin_enqueue_scripts', array($this, 'load_campaign_script'));
            add_filter('option_cta_tel', array($this, 'check_campaign_active_tel'));
            add_filter('option_assistance_phone', array($this, 'check_campaign_active_ass_phone'));
            add_shortcode('phone_number', array($this, 'get_phone_number'));
            add_shortcode('campaign_phone', array($this, 'check_campaign_active_tel'));
            add_shortcode('campaign_id', array($this, 'getCampaignID'));
            add_shortcode('campaign_five9', array($this, 'getCampaignFive9'));

            add_action('init', array($this, 'check_utm_campaign'));

            $cpt = new CptCampaign();
        }

        public static function instance() {
            if (!isset(self::$instance)) {
                self::$instance = new self();
            }
            return self::$instance;
        }

        public function start_session() {
            if (!session_id()) {
                session_start();
            }
        }

        public function plugins_loaded() {
            // Reserved for future actions
        }

        public function check_utm_campaign() {
            if (isset($_GET['utm_campaign'])) {
                $utm_campaign = sanitize_text_field($_GET['utm_campaign']);
                $campaign = get_posts(
                    array(
                        "post_type" => CptCampaign::POST_TYPE,
                        "posts_per_page" => 1,
                        "meta_key" => CptCampaign::kMETA_CAMPAIGN_ID,
                        "meta_value" => $utm_campaign
                    )
                );

                if (!empty($campaign)) {
                    $campaign = $campaign[0];
                    $campaignID = get_post_meta($campaign->ID, CptCampaign::kMETA_CAMPAIGN_ID, true);
                    $campaignName = get_post_meta($campaign->ID, CptCampaign::kMETA_CAMPAIGN_NAME, true);
                    $campaignPhone = get_post_meta($campaign->ID, CptCampaign::kMETA_CAMPAIGN_PHONE, true);

                    $this->setCampaignCookies($campaignID, $campaignName, $campaignPhone);

                    if (!session_id()) {
                        session_start();
                    }
                    $_SESSION[self::kCOOKIE_ID] = $campaignID;
                    $_SESSION[self::kCOOKIE_PHONE] = $campaignPhone;
                }
            }
        }

        public function setCampaignCookies($id, $CampaignName, $phone) {
            setcookie(self::kCOOKIE_ID, $id, 0, '/');
            setcookie(self::kCOOKIE_CAMPAIGN_NAME, $CampaignName, 0, '/');
            setcookie(self::kCOOKIE_PHONE, $phone, 0, '/');
        }

        public function check_campaign_active_tel($phonenumber) {
            if (!empty($_COOKIE[self::kCOOKIE_ID])) {
                $campaign = $this->getActiveCampaignPhoneByID($_COOKIE[self::kCOOKIE_ID]);
                if (!empty($campaign)) {
                    return $campaign;
                }
            }
            if (!empty($_SESSION[self::kCOOKIE_ID])) {
                $campaign = $this->getActiveCampaignPhoneByID($_SESSION[self::kCOOKIE_ID]);
                if (!empty($campaign)) {
                    return $campaign;
                }
            }
            return self::DEFAULT_PHONE_NUMBER;
        }

        public function check_campaign_active_ass_phone($phonenumber) {
            if (!empty($_COOKIE[self::kCOOKIE_ID])) {
                $campaign = $this->getActiveCampaignPhoneByID($_COOKIE[self::kCOOKIE_ID]);
                if (!empty($campaign)) {
                    return $campaign;
                }
            }
            if (!empty($_SESSION[self::kCOOKIE_ID])) {
                $campaign = $this->getActiveCampaignPhoneByID($_SESSION[self::kCOOKIE_ID]);
                if (!empty($campaign)) {
                    return $campaign;
                }
            }
            return self::DEFAULT_PHONE_NUMBER;
        }

        // Retrieve campaign-related information from cookies/sessions
        public static function getCampaignID() {
            if (!empty($_COOKIE[self::kCOOKIE_ID])) {
                return $_COOKIE[self::kCOOKIE_ID];
            }
            if (!empty($_SESSION[self::kCOOKIE_ID])) {
                return $_SESSION[self::kCOOKIE_ID];
            }
            // Return the default campaign ID if no campaign ID is available
            return self::DEFAULT_CAMPAIGN_ID;
        }

        public static function getCampaignFive9() {
            if (!empty($_COOKIE[self::kCOOKIE_ID_FIVE9])) {
                return $_COOKIE[self::kCOOKIE_ID_FIVE9];
            }
            if (!empty($_SESSION[self::kCOOKIE_ID_FIVE9])) {
                return $_SESSION[self::kCOOKIE_ID_FIVE9];
            }
            return self::DEFAULT_FIVE9;
        }

        public static function getCampaignSO() {
            if (!empty($_COOKIE[self::KCOOKIE_WEB_TOP_BAR])) {
                return $_COOKIE[self::KCOOKIE_WEB_TOP_BAR];
            }
            if (!empty($_SESSION[self::KCOOKIE_WEB_TOP_BAR])) {
                return $_SESSION[self::KCOOKIE_WEB_TOP_BAR];
            }
            return null;
        }

        public function get_phone_number() {
            $phoneNumber = get_option('cta_tel', true);
            return $phoneNumber;
        }

        public function getActiveCampaignPhoneByID($campaignID = "-1") {
            $campaign = get_posts(
                array(
                    "post_type" => CptCampaign::POST_TYPE,
                    "posts_per_page" => 1,
                    "meta_key" => CptCampaign::kMETA_CAMPAIGN_ID,
                    "meta_value" => $campaignID
                )
            );

            if (!empty($campaign)) {
                $campaign = $campaign[0];
                $campaignStart = get_post_meta($campaign->ID, CptCampaign::kMETA_CAMPAIGN_START_DATE, true);
                $campaignEnd = get_post_meta($campaign->ID, CptCampaign::kMETA_CAMPAIGN_END_DATE, true);
                $campaignStart .= " 00:00:00";
                $campaignEnd .= " 23:59:59";
                $campaignStart = strtotime($campaignStart);
                $campaignEnd = strtotime($campaignEnd);
                $now = time();
                if ($now >= $campaignStart && $now <= $campaignEnd) {
                    $campaignPhone = get_post_meta($campaign->ID, CptCampaign::kMETA_CAMPAIGN_PHONE, true);
                    return $campaignPhone;
                } else {
                    return false;
                }
            }
            return false;
        }

        public function setCampaign($id = "", $CampaignName = "", $phone = "", $id_five_9 = "") {
            setcookie(self::kCOOKIE_ID, $id, 0, '/');
            setcookie(self::kCOOKIE_CAMPAIGN_NAME, $CampaignName, 0, '/');
            setcookie(self::kCOOKIE_PHONE, $phone, 0, '/');
            setcookie(self::kCOOKIE_ID_FIVE9, $id_five_9, 0, '/');

            if (!session_id()) {
                session_start();
            }
            $_SESSION[self::kCOOKIE_ID] = $id;
            $_SESSION[self::kCOOKIE_PHONE] = $phone;
            $_SESSION[self::kCOOKIE_ID_FIVE9] = $id_five_9;
        }

        public function activate() {
            $cpt = new CptCampaign();
            $cpt->rewrite_flush();
        }

        public function cronJob($data) {

            if (!empty($data->ResponseBody)) {

                $existings = get_posts(
                    array(
                        "post_type" => CptCampaign::POST_TYPE,
                        "posts_per_page" => -1,
                        "post_status" => "publish"
                    )
                );

                if (!empty($existings)) {
                    foreach ($existings as $post) {
                        update_post_meta($post->ID, CptCampaign::kMETA_DELETE, true);
                    }
                }
                unset($existings);

                foreach ($data->ResponseBody as $single) :
                    $CampaignID = $single->CampaignID;
                    $StartDate = $single->StartDate;
                    $PhoneNumber = $single->PhoneNumber;
                    $LandingURL = $single->LandingURL;
                    $FriendlyURL = $single->FriendlyURL;
                    $EndDate = $single->EndDate;
                    $CampaignName = $single->CampaignName;
                    $Five9CallbackCampaign = $single->Five9CallbackCampaign;
                    $postname = str_replace(get_bloginfo('wpurl'), "", $FriendlyURL);

                    $post = get_posts(
                        array(
                            "post_type" => CptCampaign::POST_TYPE,
                            "posts_per_page" => -1,
                            "post_status" => "publish",
                            "meta_key" => CptCampaign::kMETA_CAMPAIGN_ID,
                            "meta_value" => $CampaignID
                        )
                    );

                    if (!empty($post)) {
                        $post = $post[0];
                        update_post_meta($post->ID, CptCampaign::kMETA_DELETE, false);
                        $my_post = array(
                            'ID' => $post->ID,
                            'post_title' => wp_strip_all_tags($CampaignName),
                            'post_content' => "",
                            'post_status' => 'publish',
                            'post_author' => 1,
                            'post_type' => CptCampaign::POST_TYPE,
                            'post_name' => $postname,
                            'meta_input' => array(
                                CptCampaign::kMETA_CAMPAIGN_ID => $CampaignID,
                                CptCampaign::kMETA_CAMPAIGN_START_DATE => $StartDate,
                                CptCampaign::kMETA_CAMPAIGN_PHONE => $PhoneNumber,
                                CptCampaign::kMETA_CAMPAIGN_LANDING_URL => $LandingURL,
                                CptCampaign::kMETA_CAMPAIGN_SHORT_URL => $FriendlyURL,
                                CptCampaign::kMETA_CAMPAIGN_END_DATE => $EndDate,
                                CptCampaign::kMETA_CAMPAIGN_NAME => $CampaignName,
                                CptCampaign::kMETA_FIVE9 => $Five9CallbackCampaign,
                            )
                        );

                        wp_update_post($my_post);

                        echo "\nUPDATE CAMPAIGN " . $CampaignName;
                    } else {

                        $my_post = array(
                            'post_title' => wp_strip_all_tags($CampaignName),
                            'post_content' => "",
                            'post_status' => 'publish',
                            'post_author' => 1,
                            'post_type' => CptCampaign::POST_TYPE,
                            'post_name' => $postname,
                            'meta_input' => array(
                                CptCampaign::kMETA_CAMPAIGN_ID => $CampaignID,
                                CptCampaign::kMETA_CAMPAIGN_START_DATE => $StartDate,
                                CptCampaign::kMETA_CAMPAIGN_PHONE => $PhoneNumber,
                                CptCampaign::kMETA_CAMPAIGN_LANDING_URL => $LandingURL,
                                CptCampaign::kMETA_CAMPAIGN_SHORT_URL => $FriendlyURL,
                                CptCampaign::kMETA_CAMPAIGN_END_DATE => $EndDate,
                                CptCampaign::kMETA_CAMPAIGN_NAME => $CampaignName,
                                CptCampaign::kMETA_FIVE9 => $Five9CallbackCampaign,
                            )
                        );

                        wp_insert_post($my_post);

                        echo "\nCreated Campaign: " . $CampaignName;
                    }

                endforeach;

                $todelete = get_posts(
                    array(
                        "post_type" => CptCampaign::POST_TYPE,
                        "posts_per_page" => -1,
                        "post_status" => "publish",
                        "meta_key" => CptCampaign::kMETA_DELETE,
                        "meta_value" => true
                    )
                );

                if (!empty($todelete)) {
                    echo "\n\n*** CAMPAIGN DELETE ***";
                    foreach ($todelete as $post) {
                        echo "\n" . $post->post_title;
                        wp_trash_post($post->ID);
                    }
                }
                unset($todelete);
            }
        }

        public function load_campaign_script($hook) {
            if (('post.php' == $hook || 'post-new.php' == $hook) && get_post_type() == CptCampaign::POST_TYPE) {
                wp_enqueue_style('jquery-ui');
                wp_enqueue_script('jquery-ui-datepicker');
                wp_enqueue_script("campaign.metabox", kPLUGIN_DIR_URL . 'res/js/campaign.metabox.min.js', false, filemtime(kPLUGIN_DIR_PATH . 'res/js/campaign.metabox.min.js'));
            }
        }
    }
}

if (class_exists('CampaignController')) {
    register_activation_hook(__FILE__, array('CampaignController', 'activate'));
    CampaignController::instance();
}