
<?php
require_once __DIR__ . '/../functions.php';



class Rating
{
    private $conn;

    public function __construct($conn) {
        $this->conn = $conn;
    }
    public function Add($data) {
        $product_id = $data['product_id'] ?? null;
        $user_id = $data['user_id'] ?? null;
        $rating = $data['rating'] ?? null;

        if (  $rating > 5) {
            echo json_encode(["error" => "امتیاز باید بین ۱ تا ۵ باشد"]);
            exit;
        }
        $stmt = $this->conn->prepare("SELECT id FROM product_ratings WHERE product_id = :pid AND user_id = :uid");
        $stmt->execute([':pid' => $product_id, ':uid' => $user_id]);

        if ($stmt->rowCount() > 0) {
            // اگر قبلاً امتیاز داده، آپدیت کن
            $update = $this->conn->prepare("UPDATE product_ratings SET rating = :rating WHERE product_id = :pid AND user_id = :uid");
            $update->execute([':rating' => $rating, ':pid' => $product_id, ':uid' => $user_id]);
        } else {
            // اگر اولین بارشه
            $insert = $this->conn->prepare("INSERT INTO product_ratings (product_id, user_id, rating) VALUES (:pid, :uid, :rating)");
            $insert->execute([':pid' => $product_id, ':uid' => $user_id, ':rating' => $rating]);
        }

        return $this->conn->lastInsertId();

    }
    public function getAverageRating($product_id)
    {
        $sql = "SELECT AVG(rating) AS average_rating, COUNT(*) AS total_votes 
            FROM ratings 
            WHERE product_id = :product_id";
        $stmt = $this->conn->prepare($sql);
        $stmt->execute([':product_id' => $product_id]);
        $result = $stmt->fetch(PDO::FETCH_ASSOC);

        // اگر هنوز امتیازی ثبت نشده بود
        if (!$result || !$result['average_rating']) {
            return ['average_rating' => 0, 'total_votes' => 0];
        }

        // میانگین را تا دو رقم اعشار گرد کنیم
        $result['average_rating'] = round($result['average_rating'], 2);
        return $result;
    }

}

// بررسی ورودی‌ها


// بررسی اینکه آیا قبلاً امتیاز داده است یا نه



?>
