<?php
/*
 * ----------------------------------------------------------------------
 *
 *                          Borlabs Cookie
 *                      developed by Borlabs
 *
 * ----------------------------------------------------------------------
 *
 * Copyright 2018 Borlabs - Benjamin A. Bornschein. All rights reserved.
 * This file may not be redistributed in whole or significant part.
 * Content of this file is protected by international copyright laws.
 *
 * ----------------- Borlabs Cookie IS NOT FREE SOFTWARE -----------------
 *
 * @copyright Borlabs - Benjamin A. Bornschein, https://borlabs.io
 * @author Benjamin A. Bornschein, Borlabs ben@borlabs.io
 *
 */

namespace BorlabsCookie\Cookie\Backend;

use BorlabsCookie\Cookie\API;
use BorlabsCookie\Cookie\Config;
use BorlabsCookie\Cookie\Tools;

class License
{
    private static $instance;

    private $imagePath;
    private $licenseData;

    public static function getInstance()
    {
        if (null === self::$instance) {
            self::$instance = new self;
        }

        return self::$instance;
    }

    private function __clone()
    {
    }

    private function __wakeup()
    {
    }

    protected function __construct()
    {
        $this->imagePath = plugins_url('images', realpath(__DIR__.'/../../'));
    }

    public function displayTabLicense()
    {
        // Remove license
        if (!empty($_POST['formSend']) && !empty($_POST['removeLicense']) && check_admin_referer('borlabs_cookie_remove_license')) {
            $this->removeLicense();

            Backend::getInstance()->addMessage(_x('License removed successfully.', 'Status message', 'borlabs-cookie'), 'success');
        }

        // Test environment
        if (!empty($_POST['formSend']) && !empty($_POST['enableTestEnvironment']) && check_admin_referer('borlabs_cookie_test_environment')) {
            $this->save($_POST);

            Backend::getInstance()->addMessage(_x('Saved successfully.', 'Status message', 'borlabs-cookie'), 'success');
        }

        // Register license
        if (!empty($_POST['formSend']) && !empty($_POST['registerLicense']) && !empty($_POST['licenseKey']) && check_admin_referer('borlabs_cookie_manage_license')) {

            $responseRegisterLicense = API::getInstance()->registerLicense($_POST['licenseKey']);

            if (!empty($responseRegisterLicense->successMessage)) {
                Backend::getInstance()->addMessage($responseRegisterLicense->successMessage, 'success');
            } else {
                Backend::getInstance()->addMessage($responseRegisterLicense->errorMessage, 'error');
            }
        }

        // Unlink website
        if (!empty($_POST['formSend']) && !empty($_POST['unlinkWebsite']) && check_admin_referer('borlabs_cookie_unlink_routine')) {

            // If website was selected
            if (!empty($_POST['hash']) && !empty($_POST['licenseKey'])) {

                $responseUnlinkWebsite = API::getInstance()->unlinkWebsite($_POST['licenseKey'], $_POST['hash']);

                if (!empty($responseUnlinkWebsite->successMessage)) {
                    Backend::getInstance()->addMessage($responseUnlinkWebsite->successMessage, 'success');
                } else {
                    Backend::getInstance()->addMessage($responseUnlinkWebsite->errorMessage, 'error');
                }
            }
        }

        $this->validateLicense();

        $licenseKey             = preg_replace('/[^\-]/', '*', sanitize_text_field(get_site_option('BorlabsCookieLicenseKey')));
        $licenseStatus          = $this->isValidLicense() ? 'valid' : 'expired';
        $licenseStatusMessage   = $this->getLicenseStatusMessage($licenseStatus);
        $licenseData            = $this->getLicenseData();
        $validUntil             = !empty($licenseData->validUntil) ? new \DateTime($licenseData->validUntil) : null;
        $supportUntil           = !empty($licenseData->supportUntil) ? new \DateTime($licenseData->supportUntil) : null;
        $licenseValidUntil      = !empty($licenseData->validUntil) ? Tools::getInstance()->formatTimestamp($validUntil->getTimestamp(), null, false) : '';
        $licenseSupportUntil    = !empty($licenseData->supportUntil) ? Tools::getInstance()->formatTimestamp($supportUntil->getTimestamp(), null, false) : '';
        $licenseTitle           = !empty($licenseData->licenseType) ? $this->getLicenseTitle($licenseData->licenseType) : '';
        $licenseMaxSites        = !empty($licenseData->maxSites) ? intval($licenseData->maxSites) : '';

        $checkboxTestEnvironment= Config::getInstance()->get('testEnvironment') ? ' checked' : '';

        $licenseUnlinkData = get_site_option('BorlabsCookieUnlinkData');

        if ($this->isPluginUnlocked() === false) {
            Backend::getInstance()->addMessage(_x('Can not find your license key? <a href="https://de.borlabs.io/borlabs-cookie-lizenzschluessel-wiederherstellen/?utm_source=BorlabsCookie&amp;utm_medium=Text&amp;utm_campaign=Textlink" target="_blank">Click here</a> for more information.', 'Status message', 'borlabs-cookie'), 'notice');
        }

        include Backend::getInstance()->templatePath.'/settings-license.html';
    }

    /**
     * getLicenseStatusMessage function.
     *
     * @access public
     * @param mixed $status
     * @return void
     */
    public function getLicenseStatusMessage($status)
    {
        if ($status == 'valid') {
            $message = _x('Your license is valid.', 'License status message', 'borlabs-cookie');
        } elseif ($status == 'expired') {
            $message = _x('Your license has expired.', 'License status message', 'borlabs-cookie');
        }

        return $message;
    }

    /**
     * getLicenseData function.
     *
     * @access public
     * @return void
     */
    public function getLicenseData()
    {
        if (empty($this->licenseData)) {
            // Such license system, much secure, wow.
            // Just kidding, you want all the trouble with updates, just to save some bucks?
            // Please support an independent developer and buy a license, thank you :)
            $licenseData = get_site_option('BorlabsCookieLicenseData');

            if (!empty($licenseData)) {
                $this->licenseData = unserialize(base64_decode($licenseData));
            } else {
                $this->licenseData = (object) ['noLicense'=>true];
            }
        }

        return $this->licenseData;
    }

    /**
     * getNoLicenseMessage function.
     *
     * @access public
     * @param bool $compact (default: false)
     * @return void
     */
    public function getNoLicenseMessage($compact = false)
    {
        $html = '<div class="messages">';
        $html .= '<p class="offer'.(!empty($compact) ? ' small' : '').'">';
        $html .= _x('Please activate your license key first. <a href="?page=borlabs_cookie_settings&amp;tab=license">Click here</a> to enter your license key.', 'License info', 'borlabs-cookie');
        $html .= '</p></div>';

        return $html;
    }

    /**
     * save function.
     *
     * @access public
     * @param mixed $data
     * @return void
     */
    public function save($data)
    {
        $updatedConfig = Config::getInstance()->get();

        $updatedConfig['testEnvironment'] = !empty($data['testEnvironment']) ? true : false;

        // Save config
        Config::getInstance()->saveConfig($updatedConfig);
    }

    /**
     * removeLicense function.
     *
     * @access public
     * @return void
     */
    public function removeLicense()
    {
        delete_site_option('BorlabsCookieLicenseData');
        delete_site_option('BorlabsCookieLicenseKey');
        delete_site_option('BorlabsCookieUnlinkData');

        // Set property to null
        $this->licenseData = null;

        // getLicenseData is now able to set the correct information for licenseData
        $this->getLicenseData();
    }

    /**
     * saveLicenseData function.
     *
     * @access public
     * @param mixed $licenseData
     * @return void
     */
    public function saveLicenseData($licenseData)
    {
        if (!empty($licenseData->licenseKey)) {

            update_site_option('BorlabsCookieLicenseData', base64_encode(serialize($licenseData)), 'no');
            update_site_option('BorlabsCookieLicenseKey', $licenseData->licenseKey, 'no');

            $this->licenseData = $licenseData;
        }
    }

    /**
     * validateLicense function.
     *
     * @access public
     * @return void
     */
    public function validateLicense ()
    {
        $lastCheck = intval(get_site_option('BorlabsCookieLicenseLastCheck', 0));
        $licenseKey = get_site_option('BorlabsCookieLicenseKey');

        if (!empty($licenseKey) && (empty($lastCheck) || $lastCheck < intval(date('Ymd', mktime(date('H'), date('i'), date('s'), date('m'), date('d')-3))))) {

            $responseRegisterLicense = API::getInstance()->registerLicense($licenseKey);

            if (empty($responseRegisterLicense->successMessage)) {
                $this->removeLicense();
            } else {
                // Update last check
                update_site_option('BorlabsCookieLicenseLastCheck', date('Ymd'), 'no');
            }
        }
    }

    /**
     * isValidLicense function.
     *
     * @access public
     * @return void
     */
    public function isValidLicense()
    {
        // Such license system, much secure, wow.
        // Just kidding, you want all the trouble with updates, just to save some bucks?
        // Please support an independent developer and buy a license, thank you :)
        $isValid = false;

        if (!empty($this->getLicenseData()->validUntil)) {
            if ($this->getLicenseData()->validUntil >= date('Y-m-d')) {
                $isValid = true;
            }
        }

        return $isValid;
    }

    /**
     * isPluginUnlocked function.
     *
     * @access public
     * @return void
     */
    public function isPluginUnlocked()
    {
        // Such license system, much secure, wow.
        // Just kidding, you want all the trouble with updates, just to save some bucks?
        // Please support an independent developer and buy a license, thank you :)
        $unlocked = false;

        if (!empty($this->getLicenseData()->licenseType)) {
            if ($this->getLicenseData()->licenseType === 'borlabs-cookie') {
                $unlocked = true;
            } elseif ($this->getLicenseData()->licenseType === 'borlabs-cookie-agency') {
                $unlocked = true;
            } elseif ($this->getLicenseData()->licenseType === 'borlabs-cookie-personal') {
                $unlocked = true;
            } elseif ($this->getLicenseData()->licenseType === 'borlabs-cookie-business') {
                $unlocked = true;
            } elseif ($this->getLicenseData()->licenseType === 'borlabs-cookie-professional') {
                $unlocked = true;
            } elseif ($this->getLicenseData()->licenseType === 'borlabs-cookie-legacy') {
                $unlocked = true;
            }
        }

        // If installation is in a test environment
        if (Config::getInstance()->get('testEnvironment')) {
            $unlocked = true;
        }

        return $unlocked;
    }

    /**
     * getLicenseTitle function.
     *
     * @access public
     * @param mixed $licenseType
     * @return void
     */
    public function getLicenseTitle($licenseType)
    {
        $licenseType = strtolower($licenseType);

        switch ($licenseType) {
            case 'legacy':
                $licenseType = _x('Legacy', 'License Title', 'borlabs-cookie');
                break;
            case 'borlabs-cookie-agency':
                $licenseType = _x('Agency', 'License Title', 'borlabs-cookie');
                break;
            case 'borlabs-cookie-personal':
                $licenseType = _x('Personal', 'License Title', 'borlabs-cookie');
                break;
            case 'borlabs-cookie-business':
                $licenseType = _x('Business', 'License Title', 'borlabs-cookie');
                break;
            case 'borlabs-cookie-professional':
                $licenseType = _x('Professional', 'License Title', 'borlabs-cookie');
                break;
            case 'borlabs-cookie-legacy':
                $licenseType = _x('Agency (Legacy)', 'License Title', 'borlabs-cookie');
                break;
            case 'borlabs-cookie':
            default:
                $licenseType = _x('Classic', 'License Title', 'borlabs-cookie');
        }

        return $licenseType;
    }
}
