<?php
// Include the secure database connection
require_once 'config.php';

try {
    // Fetch all products so the JavaScript can map the saved IDs to real data
    $stmt = $pdo->query('SELECT id, name, cat, price, oldPrice, img, rating, badge, `desc` FROM products');
    $productsData = $stmt->fetchAll();
    
} catch (\PDOException $e) {
    // If the DB fails, pass an empty array so the page doesn't crash
    $productsData = [];
}
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My Wishlist | B-A Home Appliances</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="icon" type="image/png" href="img/logo.png">
    <style>
    /* =========================================
       VARIABLES & CORE CSS
       ========================================= */
    :root {
        --primary: #0B5ED7;
        --primary-hover: #0a4ebd;
        --secondary: #F4F6F9;
        --bg-color: #ffffff;
        --text-main: #1a1a1a;
        --text-muted: #6c757d;
        --border-color: #e9ecef;
        --glass-bg: rgba(255, 255, 255, 0.85);
        --glass-border: rgba(255, 255, 255, 0.3);
        --shadow-soft: 0 8px 32px rgba(0, 0, 0, 0.05);
        --shadow-hover: 0 12px 48px rgba(11, 94, 215, 0.15);
        --radius-sm: 8px;
        --radius-md: 16px;
        --transition: all 0.3s ease;
    }

    [data-theme="dark"] {
        --bg-color: #121212;
        --secondary: #1e1e1e;
        --text-main: #f8f9fa;
        --text-muted: #adb5bd;
        --border-color: #2d2d2d;
        --glass-bg: rgba(30, 30, 30, 0.85);
        --glass-border: rgba(255, 255, 255, 0.05);
        --shadow-soft: 0 8px 32px rgba(0, 0, 0, 0.3);
    }

    * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
    }

    body {
        font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Arial, sans-serif;
        background-color: var(--bg-color);
        color: var(--text-main);
        line-height: 1.6;
        transition: background-color 0.3s, color 0.3s;
    }

    a {
        text-decoration: none;
        color: inherit;
    }

    button {
        cursor: pointer;
        border: none;
        background: none;
        font-family: inherit;
    }

    .glass {
        background: var(--glass-bg);
        backdrop-filter: blur(12px);
        -webkit-backdrop-filter: blur(12px);
        border: 1px solid var(--glass-border);
    }

    .btn-primary {
        background-color: var(--primary);
        color: white;
        padding: 12px 24px;
        border-radius: var(--radius-sm);
        font-weight: 600;
        transition: var(--transition);
        display: inline-flex;
        align-items: center;
        justify-content: center;
        gap: 8px;
        width: 100%;
    }

    .btn-primary:hover {
        background-color: var(--primary-hover);
        transform: translateY(-2px);
        box-shadow: var(--shadow-soft);
    }

    .btn-danger-outline {
        background: transparent;
        border: 1px solid #dc3545;
        color: #dc3545;
        padding: 12px;
        border-radius: var(--radius-sm);
        font-weight: 600;
        width: 100%;
        transition: var(--transition);
        display: flex;
        justify-content: center;
        align-items: center;
        gap: 8px;
    }

    .btn-danger-outline:hover {
        background: #dc3545;
        color: white;
    }

    /* =========================================
       PREMIUM GREY HEADER (Matched to index.html)
       ========================================= */
    header.header-premium {
        position: sticky;
        top: 0;
        z-index: 1000;
        padding: 16px 5%;
        display: flex;
        justify-content: space-between;
        align-items: center;
        background: rgba(225, 225, 234, 0.85);
        backdrop-filter: blur(16px);
        -webkit-backdrop-filter: blur(16px);
        border-bottom: 1px solid rgba(0, 0, 0, 0.05);
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
        transition: background-color 0.3s, border-color 0.3s;
    }

    [data-theme="dark"] header.header-premium {
        background: rgba(30, 30, 30, 0.95);
        border-bottom: 1px solid rgba(255, 255, 255, 0.1);
    }

    /* Brand Logo & Typography */
    .brand-logo {
        display: flex;
        align-items: center;
        gap: 15px;
        text-decoration: none;
    }

    .brand-icon {
        height: 40px;
        width: auto;
        object-fit: contain;
        filter: brightness(0) opacity(0.8);
        transition: filter 0.3s;
    }

    [data-theme="dark"] .brand-icon {
        filter: brightness(1);
    }

    .brand-text {
        display: flex;
        align-items: baseline;
        gap: 8px;
    }

    .text-ba {
        font-size: 2.2rem;
        font-weight: 900;
        background: linear-gradient(135deg, #0B5ED7 0%, #00f2fe 100%);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
        font-family: "Arial Black", Impact, system-ui, sans-serif;
        letter-spacing: -1.5px;
        line-height: 1;
    }

    .text-appliances {
        font-size: 1rem;
        font-weight: 500;
        color: var(--text-muted);
        text-transform: uppercase;
        letter-spacing: 3px;
        font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
    }

    /* Header Search Bar */
    header.header-premium .search-bar {
        flex: 0 1 400px;
        position: relative;
    }

    header.header-premium .search-bar input {
        width: 100%;
        padding: 12px 20px 12px 40px;
        border-radius: 50px;
        background: rgba(255, 255, 255, 0.7);
        border: 1px solid var(--border-color);
        color: var(--text-main);
        outline: none;
        transition: var(--transition);
    }

    header.header-premium .search-bar input::placeholder {
        color: var(--text-muted);
    }

    header.header-premium .search-bar i {
        position: absolute;
        left: 15px;
        top: 50%;
        transform: translateY(-50%);
        color: var(--text-muted);
    }

    header.header-premium .search-bar input:focus {
        border-color: var(--primary);
        background: #ffffff;
        box-shadow: 0 0 0 3px rgba(11, 94, 215, 0.1);
    }

    [data-theme="dark"] header.header-premium .search-bar input {
        background: rgba(255, 255, 255, 0.08);
        border-color: rgba(255, 255, 255, 0.15);
        color: #ffffff;
    }

    [data-theme="dark"] header.header-premium .search-bar input::placeholder {
        color: rgba(255, 255, 255, 0.5);
    }

    [data-theme="dark"] header.header-premium .search-bar i {
        color: rgba(255, 255, 255, 0.5);
    }

    /* Header Icons */
    header.header-premium .nav-icons {
        display: flex;
        gap: 24px;
        align-items: center;
    }

    header.header-premium .icon-btn {
        position: relative;
        font-size: 1.2rem;
        transition: var(--transition);
        color: var(--text-main);
    }

    header.header-premium .icon-btn:hover {
        color: var(--primary);
        transform: scale(1.1);
    }

    .badge-count {
        position: absolute;
        top: -8px;
        right: -10px;
        background: #dc3545;
        color: white;
        font-size: 0.7rem;
        font-weight: bold;
        padding: 2px 6px;
        border-radius: 50%;
        animation: pulse 2s infinite;
        display: none;
    }

    @media (max-width: 768px) {
        header.header-premium {
            flex-wrap: wrap;
            gap: 16px;
        }

        header.header-premium .search-bar {
            order: 3;
            flex: 1 1 100%;
        }
    }

    /* PAGE LAYOUT */
    .wishlist-container {
        padding: 40px 5%;
        max-width: 1400px;
        margin: 0 auto;
    }

    .page-header {
        margin-bottom: 30px;
        display: flex;
        align-items: center;
        gap: 12px;
        border-bottom: 1px solid var(--border-color);
        padding-bottom: 20px;
    }

    .grid {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
        gap: 24px;
    }

    .product-card {
        background: var(--bg-color);
        border: 1px solid var(--border-color);
        border-radius: var(--radius-md);
        padding: 16px;
        transition: var(--transition);
        position: relative;
        display: flex;
        flex-direction: column;
        animation: fadeIn 0.6s ease-out;
    }

    .product-card:hover {
        transform: translateY(-5px);
        box-shadow: var(--shadow-hover);
        border-color: var(--primary);
    }

    .product-img-wrapper {
        position: relative;
        width: 100%;
        height: 200px;
        border-radius: var(--radius-sm);
        overflow: hidden;
        margin-bottom: 16px;
    }

    .product-img-wrapper img {
        width: 100%;
        height: 100%;
        object-fit: cover;
        transition: transform 0.5s;
    }

    .product-card:hover .product-img-wrapper img {
        transform: scale(1.08);
    }

    .product-category {
        font-size: 0.8rem;
        color: var(--text-muted);
        text-transform: uppercase;
        letter-spacing: 1px;
    }

    .product-title {
        font-size: 1.1rem;
        font-weight: 600;
        margin: 8px 0;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        overflow: hidden;
    }

    .product-price {
        font-size: 1.2rem;
        font-weight: 700;
        color: var(--primary);
        margin-top: 8px;
    }

    .card-actions {
        margin-top: auto;
        padding-top: 16px;
        display: flex;
        flex-direction: column;
        gap: 8px;
    }

    /* ANIMATIONS & TOASTS */
    @keyframes fadeIn {
        from {
            opacity: 0;
            transform: translateY(20px);
        }

        to {
            opacity: 1;
            transform: translateY(0);
        }
    }

    @keyframes slideInRight {
        from {
            transform: translateX(100%);
            opacity: 0;
        }

        to {
            transform: translateX(0);
            opacity: 1;
        }
    }

    @keyframes pulse {
        0% {
            transform: scale(1);
        }

        50% {
            transform: scale(1.05);
        }

        100% {
            transform: scale(1);
        }
    }

    .toast-container {
        position: fixed;
        bottom: 20px;
        right: 20px;
        z-index: 9999;
        display: flex;
        flex-direction: column;
        gap: 10px;
    }

    .toast {
        background: var(--text-main);
        color: var(--bg-color);
        padding: 16px 24px;
        border-radius: var(--radius-sm);
        box-shadow: var(--shadow-soft);
        animation: slideInRight 0.3s ease-out;
        transition: opacity 0.3s;
        display: flex;
        align-items: center;
        gap: 10px;
        font-weight: 500;
    }

    .empty-state {
        text-align: center;
        padding: 60px 20px;
        color: var(--text-muted);
    }
    </style>
</head>

<body>

    <header class="header-premium">
        <a href="index.php" class="brand-logo">
            <img src="img/head.png" alt="B-A Logo" class="brand-icon">
            <div class="brand-text">
                <span class="text-ba">B-A</span>
                <span class="text-appliances">home appliances.</span>
            </div>
        </a>

        <div class="search-bar">
            <i class="fa-solid fa-magnifying-glass"></i>
            <input type="text" id="searchInput" placeholder="Search premium products..." aria-label="Search">
        </div>

        <nav class="nav-icons">
            <button class="icon-btn" aria-label="Dark Mode Toggle" id="themeToggle">
                <i class="fa-solid fa-moon" id="themeIcon"></i>
            </button>
            <a href="wishlist.php" class="icon-btn" aria-label="Wishlist">
                <i class="fa-solid fa-heart" style="color: #dc3545;"></i>
                <span class="badge-count" id="wishlistBadge">0</span>
            </a>
            <a href="checkout.php" class="icon-btn" aria-label="Shopping Cart">
                <i class="fa-solid fa-cart-shopping"></i>
                <span class="badge-count" id="cartBadge">0</span>
            </a>
            <button class="icon-btn" aria-label="Profile">
                <i class="fa-regular fa-user"></i>
            </button>
        </nav>
    </header>

    <main class="wishlist-container">
        <div class="page-header">
            <h2 style="font-size: 2rem;"><i class="fa-solid fa-heart" style="color: #dc3545;"></i> My Wishlist</h2>
            <span style="color: var(--text-muted); font-weight: 600;" id="wishlistCount">(0 items)</span>
        </div>

        <div class="grid" id="wishlistGrid">
        </div>
    </main>

    <div class="toast-container" id="toastContainer"></div>

    <script>
    // --- DATA LAYER (Dynamically fetched from PHP) ---
    const products = <?php echo json_encode($productsData, JSON_NUMERIC_CHECK); ?>;

    // --- STATE MANAGEMENT ---
    let wishlist = JSON.parse(localStorage.getItem('homepro_wishlist')) || [];
    let cart = JSON.parse(localStorage.getItem('homepro_cart')) || [];

    const saveWishlist = () => localStorage.setItem('homepro_wishlist', JSON.stringify(wishlist));
    const saveCart = () => localStorage.setItem('homepro_cart', JSON.stringify(cart));
    const formatPrice = (price) => Number(price).toFixed(2);

    function showToast(message, icon = "fa-check-circle") {
        const container = document.getElementById('toastContainer');
        const toast = document.createElement('div');
        toast.className = 'toast';
        toast.innerHTML = `<i class="fa-solid ${icon}"></i> ${message}`;
        container.appendChild(toast);
        setTimeout(() => {
            toast.style.opacity = '0';
            setTimeout(() => toast.remove(), 300);
        }, 3000);
    }

    function updateBadges() {
        const cBadge = document.getElementById('cartBadge');
        const wBadge = document.getElementById('wishlistBadge');

        const totalItems = cart.reduce((sum, item) => sum + item.quantity, 0);
        if (cBadge) {
            cBadge.innerText = totalItems;
            cBadge.style.display = totalItems > 0 ? 'inline-block' : 'none';
        }
        if (wBadge) {
            wBadge.innerText = wishlist.length;
            wBadge.style.display = wishlist.length > 0 ? 'inline-block' : 'none';
        }
    }

    // --- RENDER LOGIC ---
    const grid = document.getElementById('wishlistGrid');
    const countEl = document.getElementById('wishlistCount');

    function renderWishlist() {
        grid.innerHTML = '';
        countEl.innerText = `(${wishlist.length} items)`;

        if (wishlist.length === 0) {
            grid.innerHTML = `
          <div class="empty-state" style="grid-column: 1/-1;">
            <i class="fa-regular fa-heart fa-4x" style="color: var(--border-color); margin-bottom: 20px;"></i>
            <h3>Your wishlist is empty.</h3>
            <p>Save items you love and buy them later.</p>
            <button class="btn-primary" style="max-width: 200px; margin: 20px auto 0;" onclick="window.location.href='index.php'">Explore Store</button>
          </div>
        `;
            return;
        }

        wishlist.forEach(id => {
            const p = products.find(prod => prod.id === id);
            if (!p) return;

            const card = document.createElement('article');
            card.className = 'product-card';
            card.innerHTML = `
          <div class="product-img-wrapper">
            <img src="${p.img}" alt="${p.name}">
          </div>
          <span class="product-category">${p.cat}</span>
          <h3 class="product-title">${p.name}</h3>
          <div class="product-price">$${formatPrice(p.price)}</div>
          <div class="card-actions">
            <button class="btn-primary" onclick="moveToCart(${p.id})"><i class="fa-solid fa-cart-plus"></i> Move to Cart</button>
            <button class="btn-danger-outline" onclick="removeFromWishlist(${p.id})"><i class="fa-solid fa-trash-can"></i> Remove</button>
          </div>
        `;
            grid.appendChild(card);
        });
    }

    window.moveToCart = (id) => {
        const product = products.find(p => p.id === id);
        const existingItem = cart.find(item => item.id === id);
        if (existingItem) existingItem.quantity += 1;
        else cart.push({
            ...product,
            quantity: 1
        });
        saveCart();
        removeFromWishlist(id, false);
        updateBadges();
        showToast(`${product.name} moved to cart!`, "fa-cart-arrow-down");
    };

    window.removeFromWishlist = (id, showTst = true) => {
        const index = wishlist.indexOf(id);
        if (index > -1) {
            wishlist.splice(index, 1);
            saveWishlist();
            renderWishlist();
            updateBadges();
            if (showTst) showToast("Item removed from wishlist", "fa-trash");
        }
    };

    // --- THEME SYNC ---
    const themeToggle = document.getElementById('themeToggle');
    const themeIcon = document.getElementById('themeIcon');

    function updateThemeIcon() {
        if (document.body.getAttribute('data-theme') === 'dark') {
            themeIcon.classList.remove('fa-moon');
            themeIcon.classList.add('fa-sun');
        } else {
            themeIcon.classList.remove('fa-sun');
            themeIcon.classList.add('fa-moon');
        }
    }

    if (localStorage.getItem('homepro_theme') === 'dark') {
        document.body.setAttribute('data-theme', 'dark');
    }
    updateThemeIcon();

    themeToggle.addEventListener('click', () => {
        if (document.body.getAttribute('data-theme') === 'dark') {
            document.body.removeAttribute('data-theme');
            localStorage.setItem('homepro_theme', 'light');
        } else {
            document.body.setAttribute('data-theme', 'dark');
            localStorage.setItem('homepro_theme', 'dark');
        }
        updateThemeIcon();
    });

    // Init
    renderWishlist();
    updateBadges();
    </script>
</body>

</html>