<?php
    /*
        *****************************************************************************
        * MEGA Digital Space - by MEGA Digital Studio                               *
        * ------------------------------------------------------------------------- *
        * CMS Website:  https://megadigital.space                                   *
        * License:  https://megadigital.space/license                               *
        * Owner:  Giorgi Basharuli                                                  *
        * Contact:  online@megadigital.studio                                       *
        * MEGA Digital Studio – Official Development Studio for MEGA Digital Space  *
        * Website:  https://megadigital.studio                                      *
        * ------------------------------------------------------------------------- *
        * Description: This file is a part of the MEGA Digital Space CMS system.    *
        * Unauthorized distribution, modification, or commercial use is strictly -  *
        * prohibited without prior written permission.                              *
        * ------------------------------------------------------------------------- *
        * Copyright (c) 2023-2025 MEGA Digital Studio.                              *
        * All rights reserved.                                                      *
        *****************************************************************************
    */


    function addRating($entity_type, $entity_id, $user_id = null, $rating, $review_text = null) {
        global $db_connect;
        $db = $db_connect;

        // 1. Добавляем голос
        $db->insert('ratings', [
            'entity_type' => $entity_type,
            'entity_id' => $entity_id,
            'user_id' => $user_id,
            'rating' => $rating,
            'review_text' => $review_text,
            'status' => 'approved',
            'created_at' => date('Y-m-d H:i:s'),
            'updated_at' => date('Y-m-d H:i:s')
        ]);

        // 2. Обновляем рейтинг агрегатов для сущности
        $allRatings = $db->select('ratings', 'rating', [
            'entity_type' => $entity_type,
            'entity_id' => $entity_id,
            'status' => 'approved'
        ]);

        $votes_count = count($allRatings);
        $total_rating = array_sum($allRatings);

        $exists = $db->has('rating_totals', [
            'entity_type' => $entity_type,
            'entity_id' => $entity_id
        ]);

        if ($exists) {
            $db->update('rating_totals', [
                'total_rating' => $total_rating,
                'votes_count' => $votes_count
            ], [
                'entity_type' => $entity_type,
                'entity_id' => $entity_id
            ]);
        } else {
            $db->insert('rating_totals', [
                'entity_type' => $entity_type,
                'entity_id' => $entity_id,
                'total_rating' => $total_rating,
                'votes_count' => $votes_count
            ]);
        }

        return $votes_count ? round($total_rating / $votes_count, 2) : 0;
    }

    // =================== Функция рейтинга товара + обновление рейтинга магазина ===================
    function rateProduct($product_id, $user_id, $rating, $review_text = null) {
        global $db_connect;
        $db = $db_connect;

        // 1. Добавляем рейтинг товара
        addRating('product', $product_id, $user_id, $rating, $review_text);

        // 2. Получаем id магазина
        $product = $db->get('shop_products', ['shop_id'], ['id' => $product_id]);
        if (!$product) return;

        $shop_id = $product['shop_id'];

        // 3. Получаем все рейтинги товаров магазина
        $product_ids = $db->select('shop_products', 'id', ['shop_id' => $shop_id]);
        if (!$product_ids) return;

        $allRatings = $db->select('ratings', 'rating', [
            'entity_type' => 'product',
            'entity_id' => $product_ids,
            'status' => 'approved'
        ]);

        $totalShop = array_sum($allRatings);
        $countShop = count($allRatings);

        // 4. Обновляем агрегат магазина
        $exists = $db->has('rating_totals', [
            'entity_type' => 'shop',
            'entity_id' => $shop_id
        ]);

        if ($exists) {
            $db->update('rating_totals', [
                'total_rating' => $totalShop,
                'votes_count' => $countShop
            ], [
                'entity_type' => 'shop',
                'entity_id' => $shop_id
            ]);
        } else {
            $db->insert('rating_totals', [
                'entity_type' => 'shop',
                'entity_id' => $shop_id,
                'total_rating' => $totalShop,
                'votes_count' => $countShop
            ]);
        }
    }

    // =================== Получение рейтинга ===================
    function getRating($entity_type, $entity_id) {
        global $db_connect;
        $db = $db_connect;

        $row = $db->get('rating_totals', ['total_rating', 'votes_count', 'average_rating'], [
            'entity_type' => $entity_type,
            'entity_id' => $entity_id
        ]);

        return $row ?: ['total_rating'=>0,'votes_count'=>0,'average_rating'=>0];
    }


    function tplStars($average, $max = 5) {
        $full = floor($average);
        $half = ($average - $full) >= 0.5 ? 1 : 0;
        $empty = $max - $full - $half;

        $html = str_repeat('<i class="bi bi-star-fill text-warning"></i>', $full);
        $html .= str_repeat('<i class="bi bi-star-half text-warning"></i>', $half);
        $html .= str_repeat('<i class="bi bi-star text-warning"></i>', $empty);

        return $html;
    }

    /**
     * Получаем все approved отзывы для товара
     *
     * @param int $product_id
     * @param int|null $limit - сколько отзывов вернуть, null = все
     * @return array
     */
    function getProductReviews($product_id, $limit = null) {
        global $db_connect;
        $db = $db_connect;

        $options = [
            'entity_type' => 'product',
            'entity_id'   => $product_id,
            'status'      => 'approved',
            'ORDER'       => ['created_at' => 'DESC']
        ];

        if ($limit) {
            $options['LIMIT'] = $limit;
        }

        $reviews = $db->select('ratings', ['user_id', 'rating', 'review_text', 'created_at'], $options);

        // Получим имена пользователей для отзывов (если есть)
        foreach ($reviews as &$r) {
            if ($r['user_id']) {
                $user = $db->get('users', ['name'], ['id' => $r['user_id']]);
                $r['user_name'] = $user ? $user['name'] : 'Пользователь';
            } else {
                $r['user_name'] = 'Гость';
            }
        }

        return $reviews;
    }




