<?php

class ISTKR_ServiceController
{

    public static function istkr_get_cid()
    {
        $ga = isset($_COOKIE['_ga']) ? $_COOKIE['_ga'] : null;

        try {
            if ($ga) {

                $ga_array = explode('.', $ga);
                $cid =  $ga_array[2] . '.' . $ga_array[3];

                if (isset($ga_array[4])) {
                    $cid .= '.' . $ga_array[4];
                }

                return strlen($cid) > 10 ? $cid : false;
            }

            return false;
        } catch (Exception $e) {
            echo $e->getMessage();
        }
    }

    public static function istkr_activation_events()
    {

        self::istkr_upsert_db_tables();
        self::istkr_migrate_data();
    }

    public static function istkr_deactivation_events()
    {
        ISTKR_AdvisorController::istkr_advisor_deactivate();
        ISTKR_404Controller::istkr_404_deactivate();
        ISTKR_LogController::istkr_log_viewer_deactivate();
    }

    public static function istkr_uninstall_events()
    {
        ISTKR_AdvisorController::istkr_advisor_deactivate();
        ISTKR_404Controller::istkr_404_deactivate();
        ISTKR_LogController::istkr_log_viewer_deactivate();

    }

    public static function istkr_init_gtm(){
        echo '
        <script async src="https://www.googletagmanager.com/gtag/js?id='. ISTKR_Constants::$GA_ID .'"></script>
        <script>
            window.dataLayer = window.dataLayer || [];
            function gtag(){dataLayer.push(arguments);}
            gtag("js", new Date());
            gtag("config", "' . ISTKR_Constants::$GA_ID . '");
        </script>';
    }

    public static function istkr_upsert_db_tables()
    {
        global $wpdb;

        require_once ABSPATH . '/wp-admin/includes/upgrade.php';

        #Check to see if the table exists already, if not, then create it
        if ($wpdb->get_var("SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = '" . ISTKR_404_LOG . "'") !== ISTKR_404_LOG) {

            $sql = "CREATE TABLE `" .  ISTKR_404_LOG . "` (
                `id` int(128) NOT NULL AUTO_INCREMENT,
                `path` varchar(255) NOT NULL,
                `hits` int(11) NOT NULL DEFAULT 1,
                `referrer` varchar(255) DEFAULT 'n/a',
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ,
                updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
                PRIMARY KEY (`id`)
              ) ENGINE=InnoDB DEFAULT CHARSET=utf8";
            dbDelta($sql);
        }
    }

    public static function istkr_migrate_data()
    {
        $istkr_advisor_notifications_email = get_option('istkr_advisor_notifications_email');
        if ($istkr_advisor_notifications_email) {

            $instance = new ISTKR_AdvisorController();
            $notificator = new ISTKR_Notificator($instance);
            $event = $notificator->istkr_build_unique_event_name();

            $options = [
                'notifications_email' => $istkr_advisor_notifications_email,
                'notifications_email_recurrence' => 'daily',
                'action' => $notificator->action,
            ];

            update_option($event, $options);
            delete_option('istkr_advisor_notifications_email');
            delete_option('istkr_advisor_state');
        }

        $istkr_404_notifications_email = get_option('istkr_404_notifications_email');
        if ($istkr_404_notifications_email) {
            $instance = new ISTKR_404Controller();
            $notificator = new ISTKR_Notificator($instance);
            $event = $notificator->istkr_build_unique_event_name();

            $options = [
                'notifications_email' => $istkr_404_notifications_email,
                'notifications_email_recurrence' => 'hourly',
                'action' => $notificator->action,
            ];

            update_option($event, $options);
            delete_option('istkr_404_notifications_email');
        }
    }

    public static function istkr_is_dev()
    {
        try {
            $path = get_home_path() . '.env';
            if (file_exists($path)) {
                $env = file_get_contents($path);
                return (bool)strpos($env, 'development');
            }
            return false;
        } catch (Exception $e) {
            // nothing to do
        }
    }
}
