<?php
session_start();

require_once '../../config/database.php';

header('Content-Type: application/json');

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['error' => 'User not logged in']);
    exit;
}

try {
    $database = new Database();
    $conn = $database->getConnection();

    // Get currency settings
    $stmt = $conn->prepare("SELECT setting_value FROM settings WHERE setting_key = 'default_currency'");
    $stmt->execute();
    $currency_result = $stmt->fetch(PDO::FETCH_ASSOC);
    $currency = $currency_result ? $currency_result['setting_value'] : 'EGP';

    $currency_symbols = [
        'EGP' => 'ج.م',
        'USD' => '$',
        'EUR' => '€',
        'AED' => 'د.إ'
    ];
    $currency_symbol = $currency_symbols[$currency] ?? 'ج.م';

    // Get wishlist items with product details
    $stmt = $conn->prepare("
        SELECT p.id, p.name, p.price, p.image
        FROM wishlist w
        JOIN products p ON w.product_id = p.id
        WHERE w.user_id = ? AND p.stock_quantity > 0
        ORDER BY w.created_at DESC
        LIMIT 5
    ");
    $stmt->execute([$_SESSION['user_id']]);
    $wishlist_items = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Format items for JSON response
    $items = array_map(function($item) use ($currency_symbol) {
        return [
            'id' => $item['id'],
            'name' => htmlspecialchars($item['name']),
            'price' => number_format($item['price'], 2),
            'currency' => $currency_symbol,
            'image' => !empty($item['image']) && file_exists('../backend/uploads/products/' . $item['image'])
                ? '../backend/uploads/products/' . htmlspecialchars($item['image'])
                : '../backend/uploads/products/product.jpg'
        ];
    }, $wishlist_items);

    echo json_encode(['items' => $items]);

} catch(PDOException $e) {
    echo json_encode(['error' => 'Database error: ' . $e->getMessage()]);
}
?>