<?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\Frontend;

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

class Log
{
    private static $instance;

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

        return self::$instance;
    }

    public function __construct()
    {
    }

    private function __clone()
    {
    }

    private function __wakeup()
    {
    }

    /**
     * add function.
     *
     * @access public
     * @param mixed $uid
     * @param mixed $option
     * @return void
     */
    public function add($uid, $option)
    {
        global $wpdb;

        $allowedOptions = [
            'all',
            'first-party',
            'reject-all',
            'no-selection',
            'opted-out-ga',
            'opted-out-fb'
        ];

        // Get all blocked content type ids and add them to the allowed options list
        $blockedContentTypeIdsResult = $wpdb->get_results("
            SELECT
                `type_id`
            FROM
                `".$wpdb->prefix."borlabs_cookie_blocked_content_types`
        ");

        if (!empty($blockedContentTypeIdsResult)) {
            foreach ($blockedContentTypeIdsResult as $item) {
                $allowedOptions[] = $item->type_id;
            }
        }

        if (preg_match('/[0-9a-z]{8}\-[0-9a-z]{8}\-[0-9a-z]{8}\-[0-9a-z]{8}/', $uid) && in_array($option, $allowedOptions)) {
            $wpdb->query("
                INSERT INTO
                    `".(Config::getInstance()->get('aggregateCookieConsent') ? $wpdb->base_prefix : $wpdb->prefix)."borlabs_cookie_log`
                    (
                        `log_id`,
                        `uid`,
                        `option`,
                        `stamp`
                    )
                VALUES
                    (
                        null,
                        '".esc_sql($uid)."',
                        '".esc_sql($option)."',
                        NOW()
                    )
            ");
        }

        return true;
    }

    /**
     * getHistory function.
     *
     * @access public
     * @param mixed $uid
     * @param mixed $language
     * @return void
     */
    public function getHistory($uid, $language)
    {
        global $wpdb;

        $history = [];

        if (preg_match('/[0-9a-z]{8}\-[0-9a-z]{8}\-[0-9a-z]{8}\-[0-9a-z]{8}/', $uid)) {

            // Sanitize language
            $language = strtoupper(preg_replace('/[^a-z\-_]+/', '', $language));

            // Load config of the language
            Config::getInstance()->loadConfig($language);

            $stringMatch = [
                'all'=>Config::getInstance()->get('textLogOptionThirdParty'),
                'first-party'=>Config::getInstance()->get('textLogOptionFirstParty'),
                'reject-all'=>Config::getInstance()->get('textLogOptionRejectAllCookies'),
                'no-selection'=>Config::getInstance()->get('textLogOptionNoSelection'),
                'opted-out-ga'=>Config::getInstance()->get('textLogOptOutGoogleAnalytics'),
                'opted-out-fb'=>Config::getInstance()->get('textLogOptOutFacebookPixel'),
            ];

            // Get all blocked content type ids and add them to the allowed options list
            $blockedContentTypesResult = $wpdb->get_results("
                SELECT
                    `type_id`,
                    `name`
                FROM
                    `".$wpdb->prefix."borlabs_cookie_blocked_content_types`
            ");

            if (!empty($blockedContentTypesResult)) {
                foreach ($blockedContentTypesResult as $item) {
                    $stringMatch[$item->type_id] = str_replace('%%name%%', $item->name, Config::getInstance()->get('textLogOptInToUnblockType'));
                }
            }

            $historyResult = $wpdb->get_results("
                SELECT
                    `option`,
                    `stamp`
                FROM
                    `".(Config::getInstance()->get('aggregateCookieConsent') ? $wpdb->base_prefix : $wpdb->prefix)."borlabs_cookie_log`
                WHERE
                    `uid`='".esc_sql($uid)."'
                ORDER BY
                    `stamp`
                    ASC
            ");

            foreach ($historyResult as $logItem) {
                $history[] = [
                    'option'=>!empty($stringMatch[$logItem->option]) ? $stringMatch[$logItem->option] : str_replace('%%name%%', $logItem->option, Config::getInstance()->get('textLogOptInToUnblockType')),
                    'stamp'=>$logItem->stamp
                ];
            }
        }

        return $history;
    }
}
