<?php
class Favorite
{
    private $conn;
    private $table_name = "favorites";

    public $id;
    public $user_id;
    public $guesthouse_id;
    public $created_at;

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

    // Toggle Favorite (Add if not exists, Remove if exists)
    public function toggle($user_id, $guesthouse_id)
    {
        if ($this->isFavorite($user_id, $guesthouse_id)) {
            return $this->remove($user_id, $guesthouse_id);
        } else {
            return $this->add($user_id, $guesthouse_id);
        }
    }

    public function add($user_id, $guesthouse_id)
    {
        $query = "INSERT INTO " . $this->table_name . " SET user_id=:user_id, guesthouse_id=:guesthouse_id";
        $stmt = $this->conn->prepare($query);

        $stmt->bindParam(":user_id", $user_id);
        $stmt->bindParam(":guesthouse_id", $guesthouse_id);

        if ($stmt->execute()) {
            return "added";
        }
        return false;
    }

    public function remove($user_id, $guesthouse_id)
    {
        $query = "DELETE FROM " . $this->table_name . " WHERE user_id=:user_id AND guesthouse_id=:guesthouse_id";
        $stmt = $this->conn->prepare($query);

        $stmt->bindParam(":user_id", $user_id);
        $stmt->bindParam(":guesthouse_id", $guesthouse_id);

        if ($stmt->execute()) {
            return "removed";
        }
        return false;
    }

    public function isFavorite($user_id, $guesthouse_id)
    {
        $query = "SELECT id FROM " . $this->table_name . " WHERE user_id = ? AND guesthouse_id = ? LIMIT 0,1";
        $stmt = $this->conn->prepare($query);
        $stmt->bindParam(1, $user_id);
        $stmt->bindParam(2, $guesthouse_id);
        $stmt->execute();
        return $stmt->rowCount() > 0;
    }

    public function getUserFavorites($user_id)
    {
        // Join with guesthouses table to get details
        $query = "SELECT f.id as favorite_id, g.*,
                         (SELECT AVG(rating) FROM reviews WHERE guesthouse_id = g.id) as avg_rating,
                         (SELECT COUNT(*) FROM reviews WHERE guesthouse_id = g.id) as reviews_count,
                         (SELECT photo_url FROM guesthouse_photos WHERE guesthouse_id = g.id ORDER BY is_main DESC, id ASC LIMIT 1) as photo_url
                  FROM " . $this->table_name . " f
                  JOIN guesthouses g ON f.guesthouse_id = g.id
                  WHERE f.user_id = :user_id
                  ORDER BY f.created_at DESC";

        $stmt = $this->conn->prepare($query);
        $stmt->bindParam(":user_id", $user_id);
        $stmt->execute();

        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
}
?>