<?php

class Wishlist
{
    private PDO $db;

    public function __construct()
    {
        $this->db = Database::getInstance();
    }

    public function addToWishlist(int $userId, string $itemType, int $itemId, array $data = []): int
    {
        $stmt = $this->db->prepare(
            'INSERT INTO wishlists (user_id, item_type, item_id, notes, target_price, priority)
             VALUES (:user_id, :item_type, :item_id, :notes, :target_price, :priority)
             ON DUPLICATE KEY UPDATE 
             notes = VALUES(notes),
             target_price = VALUES(target_price),
             priority = VALUES(priority),
             updated_at = CURRENT_TIMESTAMP'
        );
        
        $stmt->execute([
            'user_id'      => $userId,
            'item_type'    => $itemType,
            'item_id'      => $itemId,
            'notes'        => $data['notes'] ?? null,
            'target_price' => $data['target_price'] ?? null,
            'priority'     => $data['priority'] ?? 'medium',
        ]);
        
        return (int)$this->db->lastInsertId();
    }

    public function removeFromWishlist(int $userId, string $itemType, int $itemId): bool
    {
        $stmt = $this->db->prepare(
            'DELETE FROM wishlists WHERE user_id = :user_id AND item_type = :item_type AND item_id = :item_id'
        );
        return $stmt->execute([
            'user_id'   => $userId,
            'item_type' => $itemType,
            'item_id'   => $itemId,
        ]);
    }

    public function isInWishlist(int $userId, string $itemType, int $itemId): bool
    {
        $stmt = $this->db->prepare(
            'SELECT COUNT(*) FROM wishlists WHERE user_id = :user_id AND item_type = :item_type AND item_id = :item_id'
        );
        $stmt->execute([
            'user_id'   => $userId,
            'item_type' => $itemType,
            'item_id'   => $itemId,
        ]);
        return (bool)$stmt->fetchColumn();
    }

    public function getWishlistItem(int $userId, string $itemType, int $itemId): ?array
    {
        $stmt = $this->db->prepare(
            'SELECT * FROM wishlists WHERE user_id = :user_id AND item_type = :item_type AND item_id = :item_id LIMIT 1'
        );
        $stmt->execute([
            'user_id'   => $userId,
            'item_type' => $itemType,
            'item_id'   => $itemId,
        ]);
        $row = $stmt->fetch();
        return $row ?: null;
    }

    public function getUserWishlist(int $userId): array
    {
        $stmt = $this->db->prepare(
            'SELECT w.*, 
                    CASE w.item_type
                        WHEN "item" THEN i.nominal_value
                        WHEN "coin" THEN c.nominal_value
                    END as nominal_value,
                    CASE w.item_type
                        WHEN "item" THEN i.catalog_number
                        WHEN "coin" THEN c.catalog_number
                    END as catalog_number,
                    CASE w.item_type
                        WHEN "item" THEN i.country
                        WHEN "coin" THEN c.country
                    END as country,
                    CASE w.item_type
                        WHEN "item" THEN i.image_obverse
                        WHEN "coin" THEN c.image_obverse
                    END as image_obverse,
                    CASE w.item_type
                        WHEN "item" THEN i.image_reverse
                        WHEN "coin" THEN c.image_reverse
                    END as image_reverse,
                    CASE w.item_type
                        WHEN "item" THEN s.name
                        WHEN "coin" THEN s.name
                    END as subcollection_name,
                    CASE w.item_type
                        WHEN "item" THEN col.name
                        WHEN "coin" THEN col.name
                    END as collection_name
             FROM wishlists w
             LEFT JOIN items i ON w.item_type = "item" AND w.item_id = i.id
             LEFT JOIN coins c ON w.item_type = "coin" AND w.item_id = c.id
             LEFT JOIN subcollections s ON 
                 (w.item_type = "item" AND i.subcollection_id = s.id) OR 
                 (w.item_type = "coin" AND c.subcollection_id = s.id)
             LEFT JOIN collections col ON s.collection_id = col.id
             WHERE w.user_id = :user_id
             ORDER BY w.priority DESC, w.created_at DESC'
        );
        $stmt->execute(['user_id' => $userId]);
        return $stmt->fetchAll();
    }

    public function getUserWishlistByType(int $userId, string $itemType): array
    {
        $stmt = $this->db->prepare(
            'SELECT w.*, 
                    CASE w.item_type
                        WHEN "item" THEN i.nominal_value
                        WHEN "coin" THEN c.nominal_value
                    END as nominal_value,
                    CASE w.item_type
                        WHEN "item" THEN i.catalog_number
                        WHEN "coin" THEN c.catalog_number
                    END as catalog_number,
                    CASE w.item_type
                        WHEN "item" THEN i.country
                        WHEN "coin" THEN c.country
                    END as country,
                    CASE w.item_type
                        WHEN "item" THEN i.image_obverse
                        WHEN "coin" THEN c.image_obverse
                    END as image_obverse,
                    CASE w.item_type
                        WHEN "item" THEN i.image_reverse
                        WHEN "coin" THEN c.image_reverse
                    END as image_reverse,
                    s.name as subcollection_name,
                    col.name as collection_name
             FROM wishlists w
             LEFT JOIN items i ON w.item_type = "item" AND w.item_id = i.id
             LEFT JOIN coins c ON w.item_type = "coin" AND w.item_id = c.id
             LEFT JOIN subcollections s ON 
                 (w.item_type = "item" AND i.subcollection_id = s.id) OR 
                 (w.item_type = "coin" AND c.subcollection_id = s.id)
             LEFT JOIN collections col ON s.collection_id = col.id
             WHERE w.user_id = :user_id AND w.item_type = :item_type
             ORDER BY w.priority DESC, w.created_at DESC'
        );
        $stmt->execute([
            'user_id'   => $userId,
            'item_type' => $itemType,
        ]);
        return $stmt->fetchAll();
    }

    public function updateWishlistItem(int $userId, string $itemType, int $itemId, array $data): bool
    {
        $setParts = [];
        $params = ['user_id' => $userId, 'item_type' => $itemType, 'item_id' => $itemId];

        if (isset($data['notes'])) {
            $setParts[] = 'notes = :notes';
            $params['notes'] = $data['notes'];
        }
        if (isset($data['target_price'])) {
            $setParts[] = 'target_price = :target_price';
            $params['target_price'] = $data['target_price'];
        }
        if (isset($data['priority'])) {
            $setParts[] = 'priority = :priority';
            $params['priority'] = $data['priority'];
        }

        if (empty($setParts)) {
            return false;
        }

        $setParts[] = 'updated_at = CURRENT_TIMESTAMP';
        $sql = 'UPDATE wishlists SET ' . implode(', ', $setParts) . ' WHERE user_id = :user_id AND item_type = :item_type AND item_id = :item_id';
        
        $stmt = $this->db->prepare($sql);
        return $stmt->execute($params);
    }

    public function getWishlistCount(int $userId): int
    {
        $stmt = $this->db->prepare('SELECT COUNT(*) FROM wishlists WHERE user_id = :user_id');
        $stmt->execute(['user_id' => $userId]);
        return (int)$stmt->fetchColumn();
    }

    public function getWishlistCountByType(int $userId, string $itemType): int
    {
        $stmt = $this->db->prepare('SELECT COUNT(*) FROM wishlists WHERE user_id = :user_id AND item_type = :item_type');
        $stmt->execute(['user_id' => $userId, 'item_type' => $itemType]);
        return (int)$stmt->fetchColumn();
    }

    public function getWishlistStats(int $userId): array
    {
        $stmt = $this->db->prepare(
            'SELECT 
                COUNT(*) as total_items,
                COUNT(CASE WHEN item_type = "item" THEN 1 END) as banknotes_count,
                COUNT(CASE WHEN item_type = "coin" THEN 1 END) as coins_count,
                SUM(target_price) as total_target_price,
                AVG(target_price) as avg_target_price,
                COUNT(CASE WHEN target_price IS NOT NULL THEN 1 END) as items_with_price
             FROM wishlists 
             WHERE user_id = :user_id'
        );
        $stmt->execute(['user_id' => $userId]);
        return $stmt->fetch();
    }
}
