<?php
class Wishlist {
    private $conn;
    private $table_name = "wishlist";

    public $id;
    public $user_id;
    public $product_id;

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

    public function addToWishlist() {
        $query = "INSERT INTO " . $this->table_name . " (user_id, product_id) VALUES (:user_id, :product_id)";

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

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

    public function removeFromWishlist() {
        $query = "DELETE FROM " . $this->table_name . " WHERE user_id = :user_id AND product_id = :product_id";

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

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

    public function isInWishlist() {
        $query = "SELECT id FROM " . $this->table_name . " WHERE user_id = :user_id AND product_id = :product_id LIMIT 1";

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

        return $stmt->rowCount() > 0;
    }

    public function getUserWishlist($user_id) {
        $query = "SELECT w.id, w.product_id, p.name, p.price, p.image, p.description
                  FROM " . $this->table_name . " w
                  JOIN products p ON w.product_id = p.id
                  WHERE w.user_id = :user_id
                  ORDER BY w.created_at DESC";

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

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