<?php
/**
* 2007-2017 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License (AFL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/afl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
*  @author    PrestaShop SA <contact@prestashop.com>
*  @copyright 2007-2017 PrestaShop SA
*  @license   http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
*  International Registered Trademark & Property of PrestaShop SA
*/

require_once 'Api/TSApiClient.php';

class TSMember
{
    /**
     * @desc Check if user has access and complete tsconfig
     *
     * @param boolean
     */
    public static function hasAccess()
    {
        if (!empty(Configuration::get('TRUSTEDSHOPS_MEMBER_UUID')) && Configuration::get('TRUSTEDSHOPS_MEMBER_FAILED') == 0 && isset($_SESSION['TRUSTEDSHOPS_SHOPS'])) {
            return true;
        }
        $ts_credentials = Configuration::get('TRUSTEDSHOPS_MEMBER_CREDENTIALS');
        if ($ts_credentials == false) {
            return false;
        }
        $client = new TSApiClient();
        $webservice = $client->getWrapper('memberships');
        $webservice->setCredentials($ts_credentials);
        $client->call($webservice);

        if ($client->getResponse()->isSuccess() == false && Configuration::get('TRUSTEDSHOPS_MEMBER_TRIAL') == 'TRIAL') {
            Configuration::updateValue('TRUSTEDSHOPS_MEMBER_TRIAL', 'EXPIRED_TRIAL');
            return false;
        } elseif ($client->getResponse()->isSuccess() == false) {
            return false;
        }

        $content = $client->getResponse()->getContent();
        Configuration::updateValue('TRUSTEDSHOPS_MEMBER_UUID', $content['retailer']['memberships'][0]['uuid']);
        $status = 'NO_TRIAL';
        foreach ($content['retailer']['memberships'][0]['serviceItems'] as $item) {
            if ($item['type'] == 'MEMBERSHIP_TRIAL') {
                $status = 'TRIAL';
                break;
            }
        }
        Configuration::updateValue('TRUSTEDSHOPS_MEMBER_TRIAL', $status);

        $webservice = $client->getWrapper('shops');
        $webservice->setCredentials($ts_credentials);
        $client->call($webservice);
        $response = $client->getResponse();
        $shops = $response->getContent();
        if (!is_array($shops)) {
            // API unavailable
            return false;
        }
        $shops = $shops['retailer']['shops'];
        $_SESSION['TRUSTEDSHOPS_SHOPS'] = $shops;
        foreach ($shops as $shop) {
            $idTsConfig = TSID::getTSId($shop['tsId']);
            if ($idTsConfig == true) {
                $tsid = new TSID($idTsConfig);
                // fix upgrade v1 to V2 to force display if variant not hide
                if ($tsid->current_mode != '') {
                    if ($tsid->variant != 'hide') {
                        $tsid->display_trustbadge = 1;
                    }
                    if ($tsid->current_mode == 'expert') {
                        $tsid->display_trustbadge = 1;
                        $tsid->trustbadge_advanced_configuration = 1;
                        $tsid->products_reviews_advanced_configuration = 1;
                        $tsid->rating_stars_advanced_configuration = 1;
                    }
                    $tsid->current_mode = '';
                }
            } else {
                $tsid = new TSID();
                // check if id_lang exists
                $idLang = Language::getIdByIso($shop['languageISO2']);
                $idShop = self::domainExists($shop['url']);
                $tsid->id_lang = $idLang;
                $tsid->id_shop = $idShop;
                $tsid->id_trusted_shops = $shop['tsId'];
                $tsid->api_url = $shop['url'];
                $tsid->api_lang = $shop['languageISO2'];
            }
            $tsid->uuid = Configuration::get('TRUSTEDSHOPS_MEMBER_UUID');
            $tsid->save();
        }

        return true;
    }

    /**
     * @desc get id_shop from domain
     * @param string $domain domain return by API
     *
     * @return int id of the shop
     */
    private static function domainExists($domain)
    {
        $sql = "SELECT id_shop FROM "._DB_PREFIX_."shop_url
                WHERE domain='".pSQL($domain)."'";

        $result = Db::getInstance()->getValue($sql);
        if ($result != null) {
            return $result;
        }

        return 0;
    }
}
