HEX
Server: Apache
System: Linux srv13.cpanelhost.cl 3.10.0-962.3.2.lve1.5.38.el7.x86_64 #1 SMP Thu Jun 18 05:28:41 EDT 2020 x86_64
User: cca63905 (4205)
PHP: 7.3.20
Disabled: NONE
Upload Files
File: /home4/cca63905/public_html/nueva/modules/pmproductvideoreviews/src/Utils.php
<?php
/**
 * rec.reviews
 *
 * @author    Presta-Module.com <support@presta-module.com> - https://www.presta-module.com
 * @copyright Presta-Module - https://www.presta-module.com
 * @license   see file: LICENSE.txt
 *
 *           ____     __  __
 *          |  _ \   |  \/  |
 *          | |_) |  | |\/| |
 *          |  __/   | |  | |
 *          |_|      |_|  |_|
 */

namespace PrestaModule\ProductVideoReviews;
if (!defined('_PS_VERSION_')) {
    exit;
}
use Db;
use Image;
use Order;
use Tools;
use Context;
use DbQuery;
use CartRule;
use Currency;
use Customer;
use Language;
use Validate;
use Translate;
use OrderState;
use Configuration;
use RecReviews\Client as RecReviewsClient;
use PrestaModule\ProductVideoReviews\Utils;
use PrestaModule\ProductVideoReviews\Ratings;
use PrestaModule\ProductVideoReviews\VoucherAssoc;
class Utils
{
    public static function defaultSentences($configuration_key)
    {
        $sentence = '';
        switch ($configuration_key) {
            case 'PVR_VOUCHER_INCENTIVE_TEXT':
                $sentence = Translate::getModuleTranslation('pmproductvideoreviews', 'Get {voucher_amount} by posting a review!', 'Utils');
                break;
            case 'PVR_VOUCHER_MIN_AMOUNT_DESC':
                $sentence = Translate::getModuleTranslation('pmproductvideoreviews', 'Valid for a minimum purchase amount of {order_amount}', 'Utils');
                break;
            default:
                $sentence = Translate::getModuleTranslation('pmproductvideoreviews', 'No data set', 'Utils');
                break;
        }
        return $sentence;
    }
    public static function defaultValueField($configuration_key)
    {
        $value = '';
        switch ($configuration_key) {
            case 'PVR_VOUCHER_PREFIX':
                $value = 'REVIEW';
                break;
            case 'PVR_VOUCHER_PERCENT':
                $value = 10;
                break;
            case 'PVR_VOUCHER_AMOUNT':
                $value = 10;
                break;
            case 'PVR_VOUCHER_QTY':
                $value = 1;
                break;
            case 'PVR_VOUCHER_MIN_AMOUNT':
                $value = 0;
                break;
            case 'PVR_VOUCHER_VALIDITY':
                $value = 365;
                break;
            default:
                $value = '';
                break;
        }
        return $value;
    }
    public static function getControllerUrl($controller_name, $current_lang = 0, $data = [])
    {
        if (empty($current_lang)) {
            return Context::getContext()->link->getModuleLink('pmproductvideoreviews', $controller_name, $data);
        } else {
            $lang_iso = Language::getIsoById($current_lang);
            return str_replace('/' . $lang_iso . '/', '/', Context::getContext()->link->getModuleLink('pmproductvideoreviews', $controller_name, $data));
        }
    }
    public static function getOrderStates($current_lang, $filter = '')
    {
        $order_states = OrderState::getOrderStates($current_lang);
        $order_states_output = [];
        if (empty($filter)) {
            return $order_states;
        }
        foreach ($order_states as $order_data) {
            if ($order_data[$filter] == 1) {
                $order_states_output[] = [
                    'id_order_state' => $order_data['id_order_state'],
                    'name' => $order_data['name'],
                ];
            }
        }
        return $order_states_output;
    }
    public static function getProductImageUrl($product, $image_type, $customer_id_lang)
    {
        $image_url = '';
        if (Validate::isLoadedObject($product)) {
            $images = Image::getCover($product->id);
            if (!empty($images)) {
                $image_url = Context::getContext()->link->getImageLink($product->link_rewrite[$customer_id_lang], $images['id_image'], $image_type);
            }
        }
        return $image_url;
    }
    public static function detectHttpUri($uri)
    {
        if (!strstr($uri, 'http')) {
            $uri = 'http' . (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off' ? 's' : '') . '://' . $_SERVER['HTTP_HOST'] . $uri;
        }
        return $uri;
    }
    public static function isOauthed()
    {
        static $is_oauth = false;
        if (!empty(Configuration::get('PVR_OAUTH'))) {
            if ($is_oauth === false && !empty(Configuration::get('PVR_OAUTH'))) {
                $is_oauth = !empty(json_decode(Configuration::get('PVR_OAUTH'))->access_token) ? true : false;
            }
        }
        return $is_oauth;
    }
    public static function generatePublicModuleUrl()
    {
        return Context::getContext()->link->getAdminLink('AdminModules') . '&configure=pmproductvideoreviews';
    }
    public static function updateApiModuleConfiguration()
    {
        $oCurrency = new Currency((int)Configuration::get('PVR_VOUCHER_CURRENCY'));
        $moduleConfiguration = json_decode(Configuration::get('PVR_OAUTH'));
        $aDataToSend['PVR_VOUCHER_MIN_AMOUNT_DESC'] = is_string(Configuration::get('PVR_VOUCHER_MIN_AMOUNT_DESC')) ? json_decode(Configuration::get('PVR_VOUCHER_MIN_AMOUNT_DESC'), true) : ['1' => 'not configured'];
        $aDataToSend['PVR_VOUCHER_INCENTIVE_TEXT'] = is_string(Configuration::get('PVR_VOUCHER_INCENTIVE_TEXT')) ? json_decode(Configuration::get('PVR_VOUCHER_INCENTIVE_TEXT'), true) : ['1' => 'not configured'];
        $aDataToSend['PVR_ENABLE_VOUCHER'] = (bool)Configuration::get('PVR_ENABLE_VOUCHER');
        $aDataToSend['PVR_STATUS_SELECTION'] = (int)Configuration::get('PVR_STATUS_SELECTION');
        $aDataToSend['PVR_VOUCHER_HIGHLIGHT'] = (bool)Configuration::get('PVR_VOUCHER_HIGHLIGHT');
        $aDataToSend['PVR_VOUCHER_CUMULATE'] = (bool)Configuration::get('PVR_VOUCHER_CUMULATE');
        $aDataToSend['PVR_ENABLE_BATTLE'] = (bool)Configuration::get('PVR_ENABLE_BATTLE');
        $aDataToSend['PVR_VOUCHER_TAX'] = (bool)Configuration::get('PVR_VOUCHER_TAX');
        $aDataToSend['PVR_VOUCHER_PREFIX'] = !empty((string)Configuration::get('PVR_VOUCHER_PREFIX')) ? (string)Configuration::get('PVR_VOUCHER_PREFIX') : 'REVIEW';
        $aDataToSend['PVR_VOUCHER_TYPE'] = !empty((string)Configuration::get('PVR_VOUCHER_TYPE')) ? (string)Configuration::get('PVR_VOUCHER_TYPE') : 'amount';
        $aDataToSend['PVR_VOUCHER_AMOUNT'] = !empty((string)Configuration::get('PVR_VOUCHER_AMOUNT')) ? (string)Configuration::get('PVR_VOUCHER_AMOUNT') : '1';
        $aDataToSend['PVR_VOUCHER_PERCENT'] = !empty((string)Configuration::get('PVR_VOUCHER_PERCENT')) ? (string)Configuration::get('PVR_VOUCHER_PERCENT') : '1';
        $aDataToSend['PVR_VOUCHER_CURRENCY'] = !empty((string)Configuration::get('PVR_VOUCHER_CURRENCY')) ? (string)Configuration::get('PVR_VOUCHER_CURRENCY') : '1';
        $aDataToSend['PVR_VOUCHER_QTY'] = !empty((string)Configuration::get('PVR_VOUCHER_QTY')) ? (string)Configuration::get('PVR_VOUCHER_QTY') : '1';
        $aDataToSend['PVR_VOUCHER_MIN_AMOUNT'] = !empty((string)Configuration::get('PVR_VOUCHER_MIN_AMOUNT')) ? (string)Configuration::get('PVR_VOUCHER_MIN_AMOUNT') : '1';
        $aDataToSend['PVR_VOUCHER_VALIDITY'] = !empty((string)Configuration::get('PVR_VOUCHER_VALIDITY')) ? (string)Configuration::get('PVR_VOUCHER_VALIDITY') : '365';
        $aDataToSend['PVR_PRODUCT_REVIEW_LINES'] = (int)Configuration::get('PVR_PRODUCT_REVIEW_LINES');
        $aDataToSend['PVR_PRODUCT_NB_LOAD_ITEM'] = (int)Configuration::get('PVR_PRODUCT_NB_LOAD_ITEM');
        $aDataToSend['PVR_VOUCHER_CURRENCY_CODE'] = !empty($oCurrency->iso_code) ? $oCurrency->iso_code : 'EUR';
        $aDataToSend['websiteUrl'] = trim((string)Context::getContext()->link->getBaseLink(), '/');
        $aDataToSend['logoUrl'] = _PS_BASE_URL_ . _PS_IMG_ . Configuration::get('PS_LOGO', null, null, Context::getContext()->shop->id);
        $aDataToSend['name'] = Configuration::get('PS_SHOP_NAME');
        $aDataToSend['cmsName'] = 'PrestaShop';
        $aDataToSend['cmsVersion'] = _PS_VERSION_;
        $aDataToSend['moduleVersion'] = \pmproductvideoreviews::$moduleVersion;
        RecReviewsClient::updateModuleConfigurationForGis($moduleConfiguration->access_token, ['configuration' => $aDataToSend]);
    }
    public static function makeToken($customer_id, $product_id, $id_order)
    {
        return Tools::hash($customer_id . $product_id . $id_order);
    }
    public static function generateCronUrl()
    {
        if (empty(Configuration::get('PVR_CRON_URL'))) {
            $cron_token = Tools::hash(Tools::passwdGen(16, 'NUMERIC'));
            Configuration::updateValue('PVR_CRON_URL', self::getControllerUrl('cron', (int)Context::getContext()->language->id, ['pvr_token' => $cron_token]));
            Configuration::updateValue('PVR_CRON_TOKEN', $cron_token);
        }
    }
    public static function generateDashboardShopLink()
    {
        if (!empty(Configuration::get('PVR_OAUTH'))) {
            $token = json_decode(Configuration::get('PVR_OAUTH'));
            if (!empty($token->access_token)) {
                Configuration::updateValue('PVR_API_SHOP_ID', RecReviewsClient::getShop($token->access_token));
            }
        }
    }
    public static function getProductImage($product, $image_type, $customer_id_lang)
    {
        $sImgUrl = '';
        if (Validate::isLoadedObject($product)) {
            $aImage = Image::getCover($product->id);
            if (!empty($aImage)) {
                $sImgUrl = Context::getContext()->link->getImageLink($product->link_rewrite[$customer_id_lang], $aImage['id_image'], $image_type);
                $sImgUrl = self::detectHttpUri($sImgUrl);
            }
        }
        return $sImgUrl;
    }
    public static function reviewSync()
    {
        if (!empty(Utils::isOauthed())) {
            $api_token = json_decode(Configuration::get('PVR_OAUTH'));
            if (!empty($api_token->access_token)) {
                $date_sync = date('Y-m-d H:i:s');
                $has_voucher = false;
                $data_for_api = [];
                $published_review_api = RecReviewsClient::getReviewData($api_token->access_token, ['published' => true]);
                $deleted_review_api = RecReviewsClient::getReviewData($api_token->access_token, ['deleted' => true]);
                if (!empty($published_review_api)) {
                    foreach ($published_review_api as $review_api) {
                        if (empty($review_api->previous_id_review) && !empty($review_api->published_at)) {
                            $id_order = self::getOrderId($review_api->order_reference);
                            if (!empty($id_order)) {
                                if (empty(self::hasRating($id_order, Context::getContext()->shop->id, (int)$review_api->id_order_product))) {
                                    $customer = new Customer((int)$review_api->id_customer);
                                    $timestamp = new \DateTimeImmutable($review_api->date);
                                    $api_data = [
                                        'id_customer' => (int)$review_api->id_customer,
                                        'order_reference' => $review_api->order_reference,
                                        'id_product' => (int)$review_api->id_order_product,
                                        'rating' => (int)$review_api->rating,
                                    ];
                                    $rating = new Ratings();
                                    $rating->id_api = (string)$review_api->id;
                                    $rating->id_shop = Context::getContext()->shop->id;
                                    $rating->id_product = $review_api->id_order_product;
                                    $rating->id_lang = $customer->id_lang;
                                    $rating->note = (int)$review_api->rating;
                                    $rating->status = 1;
                                    $rating->id_customer = $customer->id;
                                    $rating->id_order = (int)$id_order;
                                    $rating->video_url = $review_api->video_url;
                                    $rating->video_prw_img = $review_api->thumbnail_url;
                                    $rating->date_publish = $timestamp->format('Y-m-d h:m:s');
                                    $rating->data = json_encode($api_data);
                                    if ($rating->add()) {
                                        if (!empty(Configuration::get('PVR_ENABLE_VOUCHER'))) {
                                            if (Configuration::get('PVR_VOUCHER_GENERATE') == 'order') {
                                                $has_voucher = self::hasVoucherAssociate($customer->id, $id_order);
                                            } else {
                                                $has_voucher = self::hasVoucherAssociate($customer->id);
                                            }
                                            if (empty($has_voucher)) {
                                                $aSelectCategory = ''; 
                                                $voucher = new CartRule();
                                                $voucher->name[1] = Translate::getModuleTranslation('pmproductvideoreviews', 'Voucher code for video review', 'Utils');
                                                $voucher->active = 1;
                                                if (Configuration::get('PVR_VOUCHER_TYPE') == 'percent') {
                                                    if (!empty(Configuration::get('PVR_VOUCHER_PERCENT'))) {
                                                        $voucher->reduction_percent = (float)Configuration::get('PVR_VOUCHER_PERCENT');
                                                    }
                                                } elseif (Configuration::get('PVR_VOUCHER_TYPE') == 'amount') {
                                                    if (!empty(Configuration::get('PVR_VOUCHER_AMOUNT'))) {
                                                        $voucher->reduction_amount = (float)Configuration::get('PVR_VOUCHER_AMOUNT');
                                                        $voucher->reduction_tax = Configuration::get('PVR_VOUCHER_TAX');
                                                        $voucher->reduction_currency = Configuration::get('PVR_VOUCHER_CURRENCY');
                                                    }
                                                }
                                                $voucher->code = Configuration::get('PVR_VOUCHER_PREFIX') . '-' . $customer->id . rand($customer->id, $customer->id + 9999);
                                                $voucher->id_customer = (int)$customer->id;
                                                $voucher->quantity_per_user = (int)Configuration::get('PVR_VOUCHER_QTY');
                                                $voucher->cart_rule_restriction = (int)Configuration::get('PVR_VOUCHER_CUMULATE');
                                                $voucher->quantity = 1;
                                                if (!empty($aSelectCategory)) {
                                                    $voucher->product_restriction = 1;
                                                }
                                                $voucher->partial_use = 0;
                                                $voucher->minimum_amount = Configuration::get('PVR_VOUCHER_MIN_AMOUNT');
                                                if (!empty(version_compare(_PS_VERSION_, '1.7.7.0', '>='))) {
                                                    $voucher->minimum_amount_currency = Configuration::get('PVR_VOUCHER_CURRENCY');
                                                }
                                                $voucher->date_from = date('Y-m-d H:i:s', $_SERVER['REQUEST_TIME']);
                                                $voucher->date_to = date('Y-m-d H:i:s', mktime(date('H'), date('i'), date('s'), date('m'), date('d') + (int)Configuration::get('PVR_VOUCHER_VALIDITY'), date('Y')));
                                                if ($voucher->add()) {
                                                    $selected_categories = json_decode(Configuration::get('PVR_VOUCHER_CAT'));
                                                    if (!empty($selected_categories)) {
                                                        self::addProductRule($voucher->id, 1, 'categories', $selected_categories);
                                                    }
                                                    $voucher_association = new VoucherAssoc();
                                                    $voucher_association->id_voucher = $voucher->id;
                                                    $voucher_association->id_customer = (int)$customer->id;
                                                    $voucher_association->id_order = (int)$id_order;
                                                    $voucher_association->id_product = (int)$review_api->id_order_product;
                                                    $voucher_association->id_rating = $rating->id;
                                                    $voucher_association->id_shop = (int)Context::getContext()->shop->id;
                                                    if ($voucher_association->add()) {
                                                        $currency = new Currency((int)Configuration::get('PVR_VOUCHER_CURRENCY'));
                                                        $data_for_api = [
                                                            'order' => [
                                                                'reference' => $review_api->order_reference,
                                                            ],
                                                            'voucher' => [
                                                                'code' => $voucher->code,
                                                                'percentage' => $voucher->reduction_percent != '0.00' ? (string)$voucher->reduction_percent : null,
                                                                'amount' => $voucher->reduction_amount != '0.00' ? (string)$voucher->reduction_amount : null,
                                                                'currency' => $currency->sign,
                                                                'tax' => !empty($voucher->reduction_tax) ? true : false,
                                                                'min_amount' => $voucher->minimum_amount,
                                                                'validity' => $voucher->date_to,
                                                                'mode' => Configuration::get('PVR_VOUCHER_GENERATE'),
                                                            ],
                                                        ];
                                                        RecReviewsClient::sendVoucher($api_token->access_token, $data_for_api);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                } else {
                                    if (empty($review_api->unpublished_at)) {
                                        $unpublished_rating_id = Ratings::getUnplishedReviewsId($id_order);
                                        if (!empty($unpublished_rating_id)) {
                                            $customer = new Customer((int)$review_api->id_customer);
                                            $timestamp = new \DateTimeImmutable($review_api->date);
                                            $rating = 0;
                                            $api_data = [
                                                'id_customer' => (int)$review_api->id_customer,
                                                'order_reference' => $review_api->order_reference,
                                                'id_product' => (int)$review_api->id_order_product,
                                                'rating' => (int)$review_api->rating,
                                            ];
                                            $rating_republished = new Ratings((int)$unpublished_rating_id);
                                            $rating_republished->id_shop = (int)Context::getContext()->shop->id;
                                            $rating_republished->id_product = $review_api->id_order_product;
                                            $rating_republished->id_lang = $customer->id_lang;
                                            $rating_republished->note = (int)$review_api->rating;
                                            $rating_republished->status = 1;
                                            $rating_republished->id_customer = $customer->id;
                                            $rating_republished->id_order = (int)$id_order;
                                            $rating_republished->video_url = $review_api->video_url;
                                            $rating_republished->video_prw_img = $review_api->thumbnail_url;
                                            $rating_republished->date_publish = $timestamp->format('Y-m-d h:m:s');
                                            $rating_republished->date_unpublish = null;
                                            $rating_republished->data = json_encode($api_data);
                                            $rating_republished->update();
                                        }
                                    }
                                }
                            }
                        }
                        if (!empty($review_api->previous_id_review) && !empty($review_api->published_at)) {
                            $new_review = RecReviewsClient::getReview($api_token->access_token, $review_api->id);
                            $old_local_id = self::getLocalRatingId($review_api->previous_id_review);
                            if (!empty($old_local_id)) {
                                $replace_rating = new Ratings($old_local_id);
                                $replace_rating->id_api = $new_review->id;
                                $replace_rating->video_url = $new_review->video_url;
                                $replace_rating->video_prw_img = $new_review->thumbnail_url;
                                $replace_rating->update();
                            }
                            $local_id = self::getLocalRatingId($review_api->id);
                            if (!empty($local_id)) {
                                $local_rating = new Ratings($local_id);
                                $local_rating->id_api = $new_review->id;
                                $local_rating->video_url = $new_review->video_url;
                                $local_rating->video_prw_img = $new_review->thumbnail_url;
                                $local_rating->update();
                            }
                        }
                    }
                }
                if (!empty($deleted_review_api)) {
                    foreach ($deleted_review_api as $unpublished) {
                        if (!empty($unpublished->deleted_at)) {
                            $timestamp = new \DateTimeImmutable($unpublished->deleted_at);
                            $local_rating = self::getLocalRatingId($unpublished->id);
                            if (!empty($local_rating)) {
                                $rating = new Ratings((int)$local_rating);
                                $rating->status = 2;
                                $rating->date_unpublish = $timestamp->format('Y-m-d h:m:s');
                                $rating->id_shop = (int)Context::getContext()->shop->id;
                                $rating->update();
                            }
                        }
                        if (!empty($unpublished->previous_id_review)) {
                            $local_rating = self::getLocalRatingId($unpublished->id);
                            $rating = new Ratings((int)$local_rating);
                            $rating->status = 4;
                            $rating->update();
                        }
                    }
                }
            }
        }
        Configuration::updateValue('PVR_LAST_REVIEW_SYNC', $date_sync);
    }
    public static function getOrderId($order_reference)
    {
        $sql = new DbQuery();
        $sql->select('o.id_order');
        $sql->from('orders', 'o');
        $sql->where('o.reference = "' . pSQL($order_reference) . '"');
        $sql->where('o.id_shop = ' . (int)Context::getContext()->shop->id);
        return Db::getInstance()->getValue($sql);
    }
    public static function hasRating($id_order, $id_shop, $id_product)
    {
        $sql = new DbQuery();
        $sql->select('r.id_rating');
        $sql->from('pvr_rating', 'r');
        $sql->where('r.id_order = ' . (int)$id_order);
        $sql->where('r.id_shop = ' . (int)$id_shop);
        $sql->where('r.id_product = ' . (int)$id_product);
        return Db::getInstance()->getValue($sql);
    }
    public static function hasVoucherAssociate($customer_id, $id_order = null, $product_id = null)
    {
        $sql = new DbQuery();
        $sql->select('va.id_assoc');
        $sql->from('pvr_voucher_assoc', 'va');
        $sql->where('va.id_customer =' . (int)$customer_id);
        if (!empty($id_order)) {
            $sql->where('va.id_order =' . (int)$id_order);
        }
        if (!empty($product_id)) {
            $sql->where('va.id_product =' . (int)$product_id);
        }
        $sql->where('va.id_shop =' . (int)Context::getContext()->shop->id);
        return Db::getInstance()->getValue($sql);
    }
    public static function getLocalRatingId($api_review_id)
    {
        $sql = new DbQuery();
        $sql->select('r.id_rating');
        $sql->from('pvr_rating', 'r');
        $sql->where('r.id_api ="' . (string)$api_review_id . '"');
        $sql->where('r.id_shop =' . (int)Context::getContext()->shop->id);
        return Db::getInstance()->getValue($sql);
    }
    public static function ratingAverage(array $reviews)
    {
        $total_reviews = count($reviews);
        $some_reviews = 0;
        foreach ($reviews as $review) {
            $some_reviews = $some_reviews + (int)$review['note'];
        }
        $average_data = ['review_average_int' => 0, 'review_average_float' => 0];
        $average_data['review_average_int'] = !empty($total_reviews) ? $some_reviews / $total_reviews : 0;
        $average_data['review_average_float'] = number_format($average_data['review_average_int'], 1, ',', ',');
        $average_data['has_half'] = false;
        $fFloatingPoint = fmod($average_data['review_average_int'], 1);
        $average_data['has_half'] = false;
        if ($fFloatingPoint != 0) {
            if ($fFloatingPoint < 0.25) {
                $fFloatingPoint = 0;
            } elseif ($fFloatingPoint < 0.5) {
                $fFloatingPoint = 0.5;
            } elseif ($fFloatingPoint < 0.75) {
                $fFloatingPoint = 0.5;
            } else {
                $fFloatingPoint = 1;
            }
            if ($fFloatingPoint == 0.5) {
                $average_data['has_half'] = true;
                $average_data['review_average_int'] = (floor($average_data['review_average_int']) + $fFloatingPoint) * 2;
            } else {
                $average_data['review_average_int'] = floor($average_data['review_average_int']) + $fFloatingPoint;
            }
        } else {
            $average_data['review_average_int'] = (int)$average_data['review_average_int'];
            $average_data['review_average_float'] = $average_data['review_average_int'];
        }
        return $average_data;
    }
    public static function getDistribution($product_id, $reviews)
    {
        $distribution_data = [];
        $rating = new Ratings();
        $distribution_data = $rating->getProductRatingGroupByNote($product_id);
        $total_product_reviews = $rating->getProductRatingCount($product_id);
        $percent_per_note = [];
        if (!empty($distribution_data)) {
            foreach ($distribution_data as $key => $value) {
                $distribution_data[$key]['percent'] = (int)(((int)$value['nb'] / (int)$total_product_reviews) * 100);
            }
        }
        if (!empty($distribution_data)) {
            foreach ($distribution_data as $key => $data) {
                $distribution_data[$key]['note'] = (int)$data['note'];
            }
            if (!empty($distribution_data)) {
                foreach ($distribution_data as $aRating) {
                    $aTmp[$aRating['note']] = $aRating['nb'];
                }
                unset($distribution_data);
                for ($i = 5; 1 <= $i; --$i) {
                    if (array_key_exists($i, $aTmp)) {
                        $distribution_data[$i] = $aTmp[$i];
                    } else {
                        $distribution_data[$i] = 0;
                    }
                }
            }
            foreach ($distribution_data as $key => $count) {
                $percent_per_note[$key] = (int)(($count / count($reviews)) * 100);
            }
        }
        return ['distribution' => $distribution_data, 'percent_note' => $percent_per_note];
    }
    public static function formatReviewsDetail($reviews, $product_id)
    {
        $reviews_detail = [];
        $review_data = [
            'average' => Utils::ratingAverage($reviews),
            'total_reviews' => count($reviews),
            'full_review_data' => $reviews,
        ];
        foreach ($reviews as $review) {
            $customer_obj = new Customer((int)$review['id_customer']);
            $order_obj = new Order((int)$review['id_order']);
            $reviews_detail[$review['id_rating']] = ['firstname' => $customer_obj->firstname . ' ' . Tools::substr($customer_obj->lastname, 0, 1) . '.', 'date_add' => $order_obj->date_add];
        }
        $review_data['reviews_detail'] = $reviews_detail;
        $battles = self::getBattle($product_id);
        if (!empty($battles['best'] && !empty($battles['worst']))) {
            $review_data['battles'] = $battles;
            foreach ($battles as $battle) {
                $customer_obj = new Customer((int)$battle['id_customer']);
                $order_obj = new Order($battle['id_order']);
                $battle_details[$battle['id_rating']] = ['firstname' => $customer_obj->firstname . ' ' . Tools::substr($customer_obj->lastname, 0, 1) . '.', 'date_add' => $order_obj->date_add];
            }
            $review_data['battle_details'] = $battle_details;
        }
        return $review_data;
    }
    public static function showMoreData($reviews, $total_review, $show_more_value)
    {
        if ($show_more_value < $total_review) {
            $show_more_data['display_reviews'] = array_chunk($reviews, (int)$show_more_value)[0];
            $show_more_data['has_show_more'] = true;
            $show_more_data['show_more_value'] = $show_more_value + (int)Configuration::get('PVR_PRODUCT_REVIEW_LINES');
        } else {
            $show_more_data['display_reviews'] = array_chunk($reviews, (int)$total_review)[0];
            $show_more_data['has_show_more'] = false;
            $show_more_data['show_more_value'] = $show_more_value + (int)Configuration::get('PVR_PRODUCT_REVIEW_LINES');
        }
        $show_more_data['default_value'] = $show_more_value;
        return $show_more_data;
    }
    public static function getBattle($product_id)
    {
        $battles = [
            'worst' => Ratings::getBattle($product_id, 'worst'),
            'best' => Ratings::getBattle($product_id, 'best'),
        ];
        return $battles;
    }
    public static function addProductRule($cart_rule_id, $quantity, $type, array $element_ids)
    {
        $is_insert = false;
        Db::getInstance()->Execute('BEGIN');
        $query = 'INSERT INTO ' . _DB_PREFIX_ . 'cart_rule_product_rule_group (id_cart_rule, quantity) VALUES('
            . (int)$cart_rule_id . ', ' . (int)$quantity . ')';
        if (Db::getInstance()->Execute($query)) {
            $query = 'INSERT INTO ' . _DB_PREFIX_ . 'cart_rule_product_rule (id_product_rule_group, type) VALUES('
                . Db::getInstance()->Insert_ID() . ', "' . pSQL($type) . '")';
            if (Db::getInstance()->Execute($query)) {
                if (!empty($element_ids)) {
                    $is_insert = true;
                    $iLastInsertId = Db::getInstance()->Insert_ID();
                    foreach ($element_ids as $iId) {
                        $query = 'INSERT INTO ' . _DB_PREFIX_ . 'cart_rule_product_rule_value (id_product_rule, id_item) VALUES('
                            . (int)$iLastInsertId . ', ' . (int)$iId . ')';
                        if (!Db::getInstance()->Execute($query)) {
                            $is_insert = false;
                        }
                    }
                }
            }
        }
        $is_insert = ($is_insert) ? Db::getInstance()->Execute('COMMIT') : Db::getInstance()->Execute('ROLLBACK');
        return $is_insert;
    }
    public static function handleOrderReferenceForRecorderLink($templateVars)
    {
        $orderId = 0;
        $orderReference = '';
        if (!is_array($templateVars) || empty($templateVars)) {
            return $orderReference;
        }
        if (!empty($templateVars['{order_name}'])) {
            return (string)$templateVars['{order_name}'];
        }
        if (!empty($templateVars['{id_order}'])) {
            $orderId = (int)$templateVars['{id_order}'];
        } elseif (!empty($templateVars['{order_id}'])) {
            $orderId = (int)$templateVars['{order_id}'];
        } elseif (!empty($templateVars['{orderId}'])) {
            $orderId = (int)$templateVars['{orderId}'];
        } elseif (!empty($templateVars['{idOrder}'])) {
            $orderId = (int)$templateVars['{idOrder}'];
        }
        if (!empty($orderId)) {
            $orderReference = Order::getUniqReferenceOf($orderId);
        }
        return $orderReference;
    }
}