<?php
class Review
{
    private $conn;
    private $table_name = "reviews";

    public $id;
    public $guesthouse_id;
    public $user_id;
    public $booking_id;
    public $rating;
    public $comment;
    public $created_at;

    public function __construct($db)
    {
        $this->conn = $db;
    }

    public function create()
    {
        $query = "INSERT INTO " . $this->table_name . " SET 
                guesthouse_id=:guesthouse_id, 
                user_id=:user_id, 
                booking_id=:booking_id,
                rating=:rating,
                comment=:comment";

        $stmt = $this->conn->prepare($query);

        // Sanitize
        $this->guesthouse_id = htmlspecialchars(strip_tags($this->guesthouse_id));
        $this->user_id = htmlspecialchars(strip_tags($this->user_id));
        $this->booking_id = !empty($this->booking_id) ? htmlspecialchars(strip_tags($this->booking_id)) : null;
        $this->rating = htmlspecialchars(strip_tags($this->rating));
        $this->comment = htmlspecialchars(strip_tags($this->comment ?? ''));

        // Bind values
        $stmt->bindParam(":guesthouse_id", $this->guesthouse_id);
        $stmt->bindParam(":user_id", $this->user_id);
        $stmt->bindParam(":booking_id", $this->booking_id);
        $stmt->bindParam(":rating", $this->rating);
        $stmt->bindParam(":comment", $this->comment);

        if ($stmt->execute()) {
            $this->id = $this->conn->lastInsertId();
            return true;
        }
        return false;
    }

    public function getByGuesthouseId($guesthouse_id)
    {
        $query = "SELECT r.*, u.name as user_name 
                FROM " . $this->table_name . " r
                JOIN users u ON r.user_id = u.id
                WHERE r.guesthouse_id = ? 
                ORDER BY r.created_at DESC";

        $stmt = $this->conn->prepare($query);
        $stmt->bindParam(1, $guesthouse_id);
        $stmt->execute();
        return $stmt;
    }

    public function getAverageRating($guesthouse_id)
    {
        $query = "SELECT AVG(rating) as avg_rating, COUNT(*) as reviews_count 
                FROM " . $this->table_name . " 
                WHERE guesthouse_id = ?";

        $stmt = $this->conn->prepare($query);
        $stmt->bindParam(1, $guesthouse_id);
        $stmt->execute();
        return $stmt->fetch(PDO::FETCH_ASSOC);
    }
}
?>