<?php
namespace App\Services\Product\Rate;

use App\Models\Product;
use App\Models\Rate;

/**
 * Class based Helper to Send Notifications
 */
class RateService
{

    private $product;

    public function __construct(Product $product = null)
    {
        $this->product = $product;
    }

    public function getRate($num =null)
    {
        $rates = [
            'count'=>$this->count($num),
            'rate'=>$this->rate($num),
        ];
        return $rates;
    }

    private function rate($num = null)
    {
        $rates = 0;
        $count = $this->count();
        if ($count == 0)
        {
            return $rates;
        }
        $query = Rate::where('product_id',$this->product->id);
        if($num)
        {
            $query->where('rate',$num);
        }
        $rates = $query->sum('rate') / $count;
        return round($rates,1);
    }

    private function count($num = null)
    {
        $query = Rate::where('product_id',$this->product->id);
        if($num)
        {
            $query->where('rate',$num);
        }
        $rates = $query->count();
        return $rates;
    }
}


