<?php

class WishlistController {

    // ─── GET /api/wishlist ──────────────────────────────────────────────────
    public static function getWishlist(): void {
        $user   = AuthController::requireAuth();
        $userId = $user['id'];
        $db     = getDb();

        $stmt = $db->prepare(
            "SELECT w.id, w.product_id, w.created_at,
                    p.name, p.price, p.discount_percent, p.images, p.stock
             FROM wishlist w
             JOIN products p ON p.id = w.product_id
             WHERE w.user_id = ? AND (p.is_deleted = 0 OR p.is_deleted IS NULL)
             ORDER BY w.created_at DESC"
        );
        $stmt->bind_param('i', $userId);
        $stmt->execute();
        $items = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
        $stmt->close();

        foreach ($items as &$item) {
            $item['effective_price'] = ProductController::effectivePrice($item['price'], $item['discount_percent']);
        }

        sendSuccess($items);
    }

    // ─── POST /api/wishlist/add ──────────────────────────────────────────────
    public static function addToWishlist(): void {
        $user      = AuthController::requireAuth();
        $userId    = $user['id'];
        $body      = getJsonBody();
        $productId = (int)($body['product_id'] ?? 0);

        if (!$productId) sendError('Product ID is required', 422);

        $db = getDb();

        // Verify product exists
        $stmt = $db->prepare("SELECT id FROM products WHERE id = ? AND (is_deleted = 0 OR is_deleted IS NULL) LIMIT 1");
        $stmt->bind_param('i', $productId);
        $stmt->execute();
        if (!$stmt->get_result()->fetch_assoc()) {
            $stmt->close();
            sendError('Product not found', 404);
        }
        $stmt->close();

        // Add (Ignore if already exists due to unique constraint)
        $stmt = $db->prepare("INSERT IGNORE INTO wishlist (user_id, product_id) VALUES (?, ?)");
        $stmt->bind_param('ii', $userId, $productId);
        $stmt->execute();
        $stmt->close();

        sendSuccess(null, 'Item added to wishlist');
    }

    // ─── POST /api/wishlist/remove ───────────────────────────────────────────
    public static function removeFromWishlist(): void {
        $user      = AuthController::requireAuth();
        $userId    = $user['id'];
        $body      = getJsonBody();
        $productId = (int)($body['product_id'] ?? 0);

        if (!$productId) sendError('Product ID is required', 422);

        $db   = getDb();
        $stmt = $db->prepare("DELETE FROM wishlist WHERE user_id = ? AND product_id = ?");
        $stmt->bind_param('ii', $userId, $productId);
        $stmt->execute();
        $stmt->close();

        sendSuccess(null, 'Item removed from wishlist');
    }
}
