<?php

class PeepSo3_Helper_Addons {

    // Hours after installation before the upsell notice is displayed
    const UPSELL_DELAY_HOURS = 1;

    // Hours after installation before discounts may be offered
    const DISCOUNT_DELAY_HOURS = 48;

    public static function get_license() {
        $license = (isset($_REQUEST['bundle_license'])) ? $_REQUEST['bundle_license'] : PeepSo::get_option('bundle_license');

        if (!$license || !is_string($license) || strlen($license) < 10) return FALSE;

        return strlen($license) ? $license : FALSE;
    }

    public static function license_to_data($license=NULL, $cache = TRUE) {

        if(NULL===$license) {
            $license=self::get_license();
        }

        if(!$license) return FALSE;

        $pscc = /** checked for NULL**/ (new PeepSoCom_Connect(['license_to_id' => $license],$cache, NULL, TRUE))->get();

        if(NULL === $pscc) {
            return FALSE;
        }

        $data = (array) $pscc;

        if(is_array($data) && isset($data['bundle_id']) && isset($data['bundle_name'])) {
            return $data;
        }

        return FALSE;
    }

    public static function license_to_id($license, $cache = TRUE) {
        $data = self::license_to_data($license, $cache);

        if(FALSE !== $data) {
            return $data['bundle_id'];
        }

        return FALSE;
    }

    public static function license_to_name($license=NULL, $cache = TRUE) {
        if(NULL === $license) {
            $license = self::get_license();
        }

        $data = self::license_to_data($license, $cache);
        if(FALSE !== $data) {
            return $data['bundle_name'];
        }

        return FALSE;
    }

    public static function license_is_eligible_upgrade() {

        // License is free bundle
        if (PeepSo3_Helper_Addons::license_is_free_bundle()) {
            return 1;
        }

        // No license (fresh install / PeepSo Foundation only
        $license = PeepSo3_Helper_Addons::get_license();
        if (!PeepSo3_Utilities_String::maybe_strlen($license)) {
            return 2;
        }

        // License Provided but PeepSo Foundation only
        if (PeepSo3_Utilities_String::maybe_strlen($license)) {
            $current_item_id = PeepSo3_Helper_Addons::license_to_id($license);
            if (!$current_item_id) {
                return 3;
            }
        }

        $display_warning = PeepSo3_Mayfly::get('peepso_has_displayed_license_warning');
        if (PeepSo3_Utilities_String::maybe_strlen($display_warning)) {
            //return 4;
        }
        return FALSE;
    }

    public static function license_is_free_bundle($cache = TRUE) {
        return ('bundle-free' == PeepSo3_Helper_Addons::license_to_name(NULL, $cache));
    }

    public static function license_is_community_bundle($cache = TRUE) {
        return ('bundle-community' == PeepSo3_Helper_Addons::license_to_name(NULL, $cache));
    }

    public static function license_is_ultimate_bundle($cache = TRUE) {
        return ('bundle-ultimate-yearly' == PeepSo3_Helper_Addons::license_to_name(NULL, $cache) || 'bundle-ultimate-five-years' == PeepSo3_Helper_Addons::license_to_name(NULL, $cache));
    }

    public static function license_is_ultimate_five_years($cache = TRUE) {
        return ('bundle-ultimate-five-years' == PeepSo3_Helper_Addons::license_to_name(NULL, $cache));
    }

    /**
     * Whether the license never expires.
     *
     * A lifetime license reports a zero-shaped expiration_raw ('0'/0/NULL/''), with
     * expiration formatted as the epoch. Its bundle_name is indistinguishable from a
     * yearly one ('bundle-ultimate-yearly'), so the expiration is the only signal.
     *
     * @param array|FALSE|NULL $data result of license_to_data(), fetched when omitted
     * @return bool
     */
    public static function license_is_lifetime($data = NULL) {

        if (NULL === $data) {
            $data = self::license_to_data();
        }

        // No license, or an unusable response
        if (!is_array($data) || !isset($data['bundle_id'])) {
            return FALSE;
        }

        return empty($data['expiration_raw']);
    }

    public static function license_is_basic_bundle($cache = TRUE) {
        return ('bundle-basic' == PeepSo3_Helper_Addons::license_to_name(NULL, $cache));
    }

    public static function license_is_monthly_bundle($cache = TRUE) {
        return ('bundle-monthly' == PeepSo3_Helper_Addons::license_to_name(NULL, $cache) || 'bundle-ultimate-monthly' == PeepSo3_Helper_Addons::license_to_name(NULL, $cache));
    }

    public static function get_pfb_disabled_text() {
        $pscc =  /** checked for NULL**/ (new PeepSoCom_Connect('upsell/peepso-free-bundle/admin-disabled-message.html'))->get();

        if(NULL === $pscc) {
            return '';
        }

        return $pscc;
    }

    public static function get_upsell() {

        $license = self::get_license();
        $expired = FALSE;
        $expired_since = -1;
        $args = ['location'=>'admin_top'];

        // Reset cache if license is being saved
        $data = PeepSo3_Helper_Addons::license_to_data(NULL, !isset($_REQUEST['bundle_license']));

        if(is_array($data) && isset($data['expiration_raw']) && $data['expiration_raw'] > 0 ) {
            $expired_since = intval((strtotime(current_time('Y-m-d H:i:s')) - strtotime($data['expiration'])) / 3600);

            if ($expired_since > 0) {
                $expired = TRUE;
            }
        }



        // No license (fresh install / PeepSo Foundation only)
        if (!PeepSo3_Utilities_String::maybe_strlen($license)) {                                if(isset($_GET['dbg'])) echo 'Fresh';
            $args['show_pcb'] = 1;
        }

        // Any expired license - no creative flags, the endpoint decides.
        // The branch still matters: it keeps expired licenses out of the ones below.
        elseif($expired) {                                                                      if(isset($_GET['dbg'])) echo 'Expired';
        }

        // Monthly Basic and PFB
        elseif(
            PeepSo3_Helper_Addons::license_is_basic_bundle()
            || PeepSo3_Helper_Addons::license_is_monthly_bundle()
            || PeepSo3_Helper_Addons::license_is_free_bundle()
        ) {
            $args['show_pcb'] = 1;
	        $args['show_pcb_upgrade'] = 0;                                                       if(isset($_GET['dbg'])) echo 'M B F';
        } elseif(PeepSo3_Helper_Addons::license_is_community_bundle()) {
            $args['show_pcb_upgrade'] = 1;
	        $args['show_pcb'] = 0;
	        $args['show_peepso'] = 0;
        }

        // Ultimate and any other scenario - hide PeepSo
        else {                                                                                  if(isset($_GET['dbg'])) echo 'Ultimate';
            $args['show_peepso'] = 0;
        }

        $args['expired_since'] = ($expired && $expired_since > 0) ? $expired_since : 0;

        if (!PeepSo3_Utilities_String::maybe_strlen($license)) {
            $args['show_free'] = 1;
        }

        // AweDesk is no longer upsold, to anyone
        $args['show_alsp'] = 0;

        // Which app products are still sellable to this site
        // (replaces the old show_app flag)
        $app = self::get_app_context();
        $args['app_show_lite']    = $app['app_show_lite'];
        $args['app_show_service'] = $app['app_show_service'];

        // 5-year bundles are no longer sold, so Lifetime is offered to everyone -
        // except the people already holding it. $data is reused so the cache flag matches.
        $args['show_lifetime'] = (int) !self::license_is_lifetime($data);

        // 1 = offer a discount, 0 = do not. Everyone qualifies once the install is
        // old enough; the show_* flags above decide WHICH offer is presented.
        $args['discount'] = (int) self::discounts_allowed();

        $args['installer_url'] = admin_url('admin.php?page=peepso-installer&action=peepso-free');
        $url = add_query_arg($args, 'upsell/upsell.php');
//	    $args['cb']=time();echo "<pre>";var_dump($args);echo "</pre>";
        // No fallback message - if PeepSo.com is unreachable the upsell stays silent
        $pscc =  /** checked for NULL**/ (new PeepSoCom_Connect($url,TRUE,NULL, FALSE))->get();

        if(NULL === $pscc) {
            return '';
        }

        if(is_string($pscc)) {
            if(stristr($pscc, 'upsell_is_empty')) {
                return '';
            }
            return $pscc;
        }

        return '';

    }

    public static function get_addons() {
        global $wp_version;
        $has_new = FALSE;

        $args = [
            'ver_bundle'    => PeepSo3_Helper_Addons::license_to_name(),
            'ver_wp'        => $wp_version,
            'ver_php'       => PHP_VERSION,
            'ver_locale'    => get_locale(),
            'theme'         => wp_get_theme()->get('Name'),
        ];

        foreach($args as $k=>$v) {
            $args[$k] = urlencode($v);
        }

        $url = add_query_arg($args, $url = "?product_bundles_list");

        $pscc =  /** checked for NULL**/ (new PeepSoCom_Connect($url))->get();

        if (NULL === $pscc) {
            return FALSE;
        } else {
            $result = json_decode($pscc);
            if($result !== NULL) {
                PeepSo3_Mayfly::set('bundle_info', $result, 24*3600);
                foreach($result as $item) {
                    if(isset($item->new)) {
                        $has_new = $item->id;
                        break;
                    }
                }
            }

            if($has_new) {
                PeepSo3_Mayfly_Int::set('installer_has_new', $has_new);
            } else {
                PeepSo3_Mayfly_Int::del('installer_has_new');
            }
        }

        return $result;
    }

    public static function maybe_powered_by_peepso() {

        if(PeepSo::get_option('system_show_peepso_link',0)) {

            $pscc =  /** checked for NULL**/ (new PeepSoCom_Connect('upsell/peepso-free-bundle/powered-by-peepso.php'))->get();

            if(NULL === $pscc) {
                return '';
            }

            if(is_string($pscc)) {
                return $pscc;
            }

            return '';
        }

        if(apply_filters('peepso_free_bundle_should_brand', FALSE) && self::license_is_free_bundle()) {
            $PeepSoConfigSettings = PeepSoConfigSettings::get_instance();
            $PeepSoConfigSettings->set_option('system_show_peepso_link', 1);
            $pscc =  /** checked for NULL**/ (new PeepSoCom_Connect('upsell/peepso-free-bundle/powered-by-peepso.php'))->get();

            if(NULL === $pscc) {
                return '';
            }

            if(is_string($pscc)) {
                return $pscc;
            }

            return '';
        }

        return '';
    }

    public static function maybe_optin_stats() {

        if(PeepSo::get_option('optin_stats',0)) {
            return TRUE;
        }

        if(self::license_is_free_bundle()) {
            PeepSoConfigSettings::get_instance()->set_option('optin_stats', 1);
            return TRUE;
        }

        return PeepSo::get_option('optin_stats',0);
    }

    public static function maybe_installer_has_new() {
        return (PeepSo3_Mayfly_Int::get('installer_has_new') || !self::get_license());
    }


    /**
     * App context for the upsell endpoint: which app products are still sellable.
     *
     *   neither plugin  -> lite 1, service 1
     *   new-app         -> lite 0, service 0   (has the full app already)
     *   universo only   -> lite 0, service 1   (service is still available)
     *
     * Params are injectable for testing; in production both are detected.
     *
     * @param bool|NULL $has_app       PeepSoNewAppPlugin (new-app) present
     * @param bool|NULL $has_universal PeepSoNewAppUniversalPlugin (new-app-universo) present
     * @return array app_show_lite and app_show_service, as ints
     */
    public static function get_app_context($has_app = NULL, $has_universal = NULL) {

        if (NULL === $has_app) {
            $has_app = class_exists('PeepSoNewAppPlugin');
        }

        if (NULL === $has_universal) {
            $has_universal = class_exists('PeepSoNewAppUniversalPlugin');
        }

        // Full app plugin - nothing left to offer
        if ($has_app) {
            return ['app_show_lite' => 0, 'app_show_service' => 0];
        }

        // Universal app only - the service is still available
        if ($has_universal) {
            return ['app_show_lite' => 0, 'app_show_service' => 1];
        }

        return ['app_show_lite' => 1, 'app_show_service' => 1];
    }

    /**
     * Whether promotional content may be displayed in wp-admin.
     * Mirrors the "Allow special offers in the admin area" switch.
     * @return bool
     */
    public static function promos_allowed() {
        return (bool) PeepSo::get_option('peepsocom_connect_upsell');
    }

    /**
     * Whether this installation is old enough to be offered a discount.
     * @return bool
     */
    public static function discounts_allowed() {
        return (self::get_peepso_age() >= self::DISCOUNT_DELAY_HOURS);
    }

    /**
     * Retrieve the age of PeepSo installation in HOURS
     * @return int amount of HOURS passed since PeepSo installation
     */
    public static function get_peepso_age() {
        $start_date = isset($_GET['peepso_start_date']) ? $_GET['peepso_start_date'] : get_option('peepso_install_date');

        $ps_start= strtotime($start_date);
        $ps_time = 0;
        if($ps_start) {
            $ps_time = intval((strtotime(current_time('Y-m-d H:i:s')) - $ps_start) / 3600);
        }

        return $ps_time;
    }
}

add_action('admin_notices', function() {

    if(!PeepSo::is_admin() || !PeepSo3_Helper_Addons::promos_allowed()) { return; }

    $peepsoAge = PeepSo3_Helper_Addons::get_peepso_age(); // in hours
    if($peepsoAge < PeepSo3_Helper_Addons::UPSELL_DELAY_HOURS) return;

    $mayfly = 'user_'.get_current_user_id().'upsell_dismiss';

    if(isset($_GET['peepso_upsell_dismiss_reset'])) {
        PeepSo3_Mayfly::del($mayfly);
        PeepSo3_Utility_Redirect::_(remove_query_arg('peepso_upsell_dismiss_reset'));
    }

    if(isset($_GET['peepso_upsell_dismiss'])) {
        // Default: dismiss for  7 days
        $ttl = 7*24*3600;

        if(PeepSo3_Helper_Addons::license_is_ultimate_bundle() || PeepSo3_Helper_Addons::license_is_community_bundle()) {
            // Ultimate: dismiss for 14 days
            $ttl = 14*24*3600;
        }

        PeepSo3_Mayfly::set($mayfly,1,$ttl);
        PeepSo3_Utility_Redirect::_(remove_query_arg('peepso_upsell_dismiss'));
    }

    if(PeepSo3_Mayfly::get($mayfly)) { return; }

    $upsell = PeepSo3_Helper_Addons::get_upsell();

    if(($upsell)) {
        ?>
        <div style="clear:both">
        <a href="<?php echo esc_url(add_query_arg(['peepso_upsell_dismiss'=>1]));?>">Dismiss</a>
        <?php
        echo $upsell;
        echo "</div>";
    }
},0,99);
