<?php

namespace Bongo\Builder\Http\Controllers\Api;

use Bongo\Framework\Http\Controllers\AbstractApiController;
use Bongo\Review\Models\Review;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

class ReviewSummaryController extends AbstractApiController
{
    public function index(Request $request)
    {
        $noOfReviews = Cache::remember('no_of_reviews', config('settings.cache_default'),
            function () {
                return Review::active()->count();
            });

        // Get the average rating of all active reviews
        $averageRating = Cache::remember('average_rating', config('settings.cache_default'),
            function () {
                return ceil(Review::active()->average('rating'));
            });

        // Get the corresponding text version of the active reviews
        if ($averageRating >= 5) {
            $averageRatingText = 'Excellent';
        } elseif ($averageRating >= 4) {
            $averageRatingText = 'Great';
        } elseif ($averageRating >= 3) {
            $averageRatingText = 'Average';
        } elseif ($averageRating >= 2) {
            $averageRatingText = 'Poor';
        } else {
            $averageRatingText = 'Bad';
        }

        return view('builder::api.review_summary', compact('noOfReviews', 'averageRating', 'averageRatingText'))
            ->render();
    }
}
