<?php
session_start();

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: auth-system/login.php');
    exit;
}

// Check if user is customer
if ($_SESSION['user_role'] !== 'customer') {
    header('Location: shop.php');
    exit;
}

// Database connection
require_once __DIR__ . '/config/db.php';

$user_id = $_SESSION['user_id'];

// Get favorites
$favorites_query = $connection->prepare("
    SELECT id, product_id, product_name, product_price, product_image, added_at
    FROM favorites
    WHERE user_id = ?
    ORDER BY added_at DESC
");
$favorites_query->bind_param("i", $user_id);
$favorites_query->execute();
$favorites_result = $favorites_query->get_result();

$favorites = [];
$total_price = 0;
while ($item = $favorites_result->fetch_assoc()) {
    $favorites[] = $item;
    $total_price += $item['product_price'];
}

$page_title = 'Wishlist - My Favorites';
include 'header-php.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo htmlspecialchars($page_title); ?></title>
    <link rel="stylesheet" href="assets/css/bootstrap.min.css">
    <style>
        /* ========== RESET & BASE STYLES ========== */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        html, body {
            height: 100%;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: #f8f9fa;
        }

        body {
            padding: 0;
        }

        /* ========== CONTAINER & LAYOUT ========== */
        .wishlist-wrapper {
            padding: 0rem;
        }

        .wishlist-container {
            margin: 0 auto;
            padding: 1rem;
        }

        /* ========== HEADER SECTION ========== */
        .wishlist-header {
            background: linear-gradient(135deg, #333 0%, #555 100%);
            color: white;
            padding: 2rem 1.5rem;
            border-radius: 8px;
            margin-bottom: 2rem;
            box-shadow: 0 4px 12px rgba(0,0,0,0.15);
        }

        .wishlist-header h1 {
            font-size: 2rem;
            font-weight: 700;
            margin-bottom: 0.5rem;
        }

        .wishlist-header p {
            font-size: 1rem;
            opacity: 0.9;
        }

        /* ========== EMPTY STATE ========== */
        .empty-state {
            background: white;
            border: 2px dashed #d4a574;
            border-radius: 8px;
            padding: 3rem;
            text-align: center;
            margin: 2rem 0;
        }

        .empty-state-icon {
            font-size: 3rem;
            margin-bottom: 1rem;
        }

        .empty-state h2 {
            color: #333;
            font-size: 1.5rem;
            margin-bottom: 0.5rem;
        }

        .empty-state p {
            color: #666;
            font-size: 1rem;
            margin-bottom: 1.5rem;
        }

        /* ========== FAVORITES GRID ========== */
        .favorites-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
            gap: 1.5rem;
            margin-bottom: 2rem;
        }

        @media (max-width: 768px) {
            .favorites-grid {
                grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
                gap: 1rem;
            }
        }

        @media (max-width: 480px) {
            .favorites-grid {
                grid-template-columns: 1fr;
            }
        }

        /* ========== PRODUCT CARD ========== */
        .favorite-card {
            background: white;
            border: 1px solid #ddd;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 2px 8px rgba(0,0,0,0.08);
            transition: all 0.3s ease;
            display: flex;
            flex-direction: column;
        }

        .favorite-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 8px 16px rgba(0,0,0,0.15);
            border-color: #d4a574;
        }

        .favorite-card-image {
            width: 100%;
            height: 200px;
            object-fit: cover;
            background: #f5f5f5;
        }

        .favorite-card-content {
            padding: 1rem;
            flex: 1;
            display: flex;
            flex-direction: column;
        }

        .favorite-card-name {
            font-size: 1rem;
            font-weight: 600;
            color: #333;
            margin-bottom: 0.5rem;
            line-height: 1.3;
        }

        .favorite-card-price {
            font-size: 1.3rem;
            color: #d4a574;
            font-weight: 700;
            margin-bottom: 1rem;
        }

        .favorite-card-actions {
            display: flex;
            gap: 0.5rem;
            margin-top: auto;
        }

        .favorite-card-actions button,
        .favorite-card-actions a {
            flex: 1;
            padding: 0.5rem;
            border: none;
            border-radius: 4px;
            font-size: 0.85rem;
            font-weight: 600;
            cursor: pointer;
            text-decoration: none;
            transition: all 0.3s ease;
            text-align: center;
        }

        .btn-remove {
            background: #ff4444;
            color: white;
        }

        .btn-remove:hover {
            background: #ff2222;
        }

        .btn-add-cart {
            background: #333;
            color: white;
        }

        .btn-add-cart:hover {
            background: #555;
        }

        /* ========== SUMMARY SECTION ========== */
        .wishlist-summary {
            background: white;
            border: 1px solid #ddd;
            border-radius: 8px;
            padding: 2rem;
            margin-bottom: 2rem;
            box-shadow: 0 2px 8px rgba(0,0,0,0.08);
        }

        .summary-row {
            display: flex;
            justify-content: space-between;
            padding: 0.75rem 0;
            border-bottom: 1px solid #f0f0f0;
        }

        .summary-row:last-child {
            border-bottom: none;
            font-weight: 700;
            font-size: 1.1rem;
            padding-top: 1rem;
            padding-bottom: 0;
        }

        .summary-label {
            color: #666;
        }

        .summary-value {
            color: #333;
            font-weight: 600;
        }

        /* ========== ACTION BUTTONS ========== */
        .action-buttons {
            display: flex;
            gap: 1rem;
            flex-wrap: wrap;
            margin-top: 2rem;
        }

        .action-btn {
            padding: 0.75rem 1.5rem;
            border: none;
            border-radius: 5px;
            font-weight: 600;
            font-size: 1rem;
            cursor: pointer;
            text-decoration: none;
            transition: all 0.3s ease;
            display: inline-block;
        }

        .btn-primary {
            background: #d4a574;
            color: white;
        }

        .btn-primary:hover {
            background: #c49564;
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(212, 165, 116, 0.3);
        }

        .btn-secondary {
            background: #6c757d;
            color: white;
        }

        .btn-secondary:hover {
            background: #5a6268;
        }

        /* ========== TOAST NOTIFICATION ========== */
        .toast {
            position: fixed;
            bottom: 20px;
            right: 20px;
            padding: 1rem 1.5rem;
            border-radius: 5px;
            color: white;
            font-weight: 600;
            box-shadow: 0 4px 12px rgba(0,0,0,0.2);
            z-index: 1000;
            display: none;
            animation: slideIn 0.3s ease;
        }

        .toast.success {
            background: #28a745;
        }

        .toast.error {
            background: #dc3545;
        }

        @keyframes slideIn {
            from {
                transform: translateX(400px);
                opacity: 0;
            }
            to {
                transform: translateX(0);
                opacity: 1;
            }
        }

        /* ========== RESPONSIVE ========== */
        @media (max-width: 768px) {
            .wishlist-wrapper {
                margin-top: 100px;
                padding: 0.75rem;
            }

            .wishlist-container {
                padding: 0.75rem;
            }

            .wishlist-header {
                padding: 1.5rem 1rem;
                margin-bottom: 1.5rem;
            }

            .wishlist-header h1 {
                font-size: 1.5rem;
            }

            .wishlist-header p {
                font-size: 0.95rem;
            }

            .empty-state {
                padding: 2rem;
            }

            .favorite-card-image {
                height: 180px;
            }

            .wishlist-summary {
                padding: 1.5rem;
            }

            .action-buttons {
                flex-direction: column;
            }

            .action-btn {
                width: 100%;
            }
        }

        @media (max-width: 576px) {
            .wishlist-wrapper {
                margin-top: 0;
                padding: 0.5rem;
            }

            .wishlist-container {
                padding: 0.5rem;
                max-width: 100%;
            }

            .wishlist-header {
                padding: 1.25rem 0.75rem;
                margin-bottom: 1rem;
                border-radius: 6px;
            }

            .wishlist-header h1 {
                font-size: 1.25rem;
                margin-bottom: 0.25rem;
            }

            .wishlist-header p {
                font-size: 0.85rem;
                margin: 0;
            }

            .empty-state {
                padding: 1.5rem;
                margin: 1rem 0;
                border-radius: 6px;
            }

            .empty-state-icon {
                font-size: 2.5rem;
                margin-bottom: 0.75rem;
            }

            .empty-state h2 {
                font-size: 1.25rem;
                margin-bottom: 0.5rem;
            }

            .empty-state p {
                font-size: 0.9rem;
                margin-bottom: 1rem;
            }

            .favorites-grid {
                grid-template-columns: 1fr;
                gap: 0.75rem;
                margin-bottom: 1rem;
            }

            .favorite-card {
                border-radius: 6px;
            }

            .favorite-card-image {
                height: 150px;
            }

            .favorite-card-content {
                padding: 0.75rem;
            }

            .favorite-card-name {
                font-size: 0.95rem;
                margin-bottom: 0.4rem;
            }

            .favorite-card-price {
                font-size: 1.1rem;
                margin-bottom: 0.75rem;
            }

            .favorite-card-actions {
                gap: 0.4rem;
            }

            .favorite-card-actions button,
            .favorite-card-actions a {
                padding: 0.4rem;
                font-size: 0.75rem;
            }

            .wishlist-summary {
                padding: 1rem;
                margin-bottom: 1rem;
                border-radius: 6px;
            }

            .summary-row {
                padding: 0.5rem 0;
                font-size: 0.9rem;
            }

            .action-buttons {
                flex-direction: column;
                gap: 0.75rem;
                margin-top: 1rem;
            }

            .action-btn {
                width: 100%;
                padding: 0.65rem 1rem;
                font-size: 0.9rem;
            }

            .toast {
                bottom: 10px;
                right: 10px;
                padding: 0.75rem 1rem;
                font-size: 0.85rem;
            }
        }
    </style>
</head>
<body>
    <div class="wishlist-wrapper">
        <div class="wishlist-container">
            <!-- Header -->
            <div class="wishlist-header">
                <h1>❤️ My Wishlist</h1>
                <p>Your collection of favorite products</p>
            </div>

            <?php if (empty($favorites)): ?>
                <!-- Empty State -->
                <div class="empty-state">
                    <div class="empty-state-icon">💭</div>
                    <h2>Your wishlist is empty</h2>
                    <p>Start adding your favorite products to your wishlist</p>
                    <a href="shop.php" class="action-btn btn-primary">🛍️ Explore Products</a>
                </div>
            <?php else: ?>
                <!-- Favorites Grid -->
                <div class="favorites-grid">
                    <?php foreach ($favorites as $fav): ?>
                        <div class="favorite-card">
                            <img src="<?php echo htmlspecialchars($fav['product_image'] ?? 'assets/img/placeholder.jpg'); ?>" 
                                 alt="<?php echo htmlspecialchars($fav['product_name']); ?>" 
                                 class="favorite-card-image">
                            <div class="favorite-card-content">
                                <div class="favorite-card-name"><?php echo htmlspecialchars($fav['product_name']); ?></div>
                                <div class="favorite-card-price">Rs. <?php echo number_format($fav['product_price'], 0); ?></div>
                                <div class="favorite-card-actions">
                                    <button class="btn-remove" data-product-id="<?php echo $fav['product_id']; ?>" 
                                            onclick="removeFavorite(<?php echo $fav['product_id']; ?>)">❌ Remove</button>
                                    <button class="btn-add-cart" data-product-id="<?php echo $fav['product_id']; ?>" 
                                            data-name="<?php echo htmlspecialchars($fav['product_name']); ?>" 
                                            data-price="<?php echo $fav['product_price']; ?>" 
                                            data-image="<?php echo htmlspecialchars($fav['product_image']); ?>" 
                                            onclick="addToCart(this)">🛒 Add Cart</button>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>

                <!-- Summary -->
                <div class="wishlist-summary">
                    <div class="summary-row">
                        <span class="summary-label">Total Items:</span>
                        <span class="summary-value"><?php echo count($favorites); ?></span>
                    </div>
                    <div class="summary-row">
                        <span class="summary-label">Total Value:</span>
                        <span class="summary-value">Rs. <?php echo number_format($total_price, 0); ?></span>
                    </div>
                </div>

                <!-- Action Buttons -->
                <div class="action-buttons">
                    <a href="shop.php" class="action-btn btn-secondary">🛍️ Continue Shopping</a>
                    <a href="cart.php" class="action-btn btn-primary">🛒 View Cart</a>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <!-- Toast Notification -->
    <div id="toast" class="toast"></div>

    <!-- JavaScript -->
    <script>
        /**
         * Remove from favorites
         */
        async function removeFavorite(productId) {
            try {
                const response = await fetch('auth-system/favorites-api.php?action=remove', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ product_id: productId })
                });

                const data = await response.json();

                if (data.success) {
                    showToast('✅ Removed from favorites', 'success');
                    setTimeout(() => {
                        location.reload();
                    }, 1000);
                } else {
                    showToast('❌ Error: ' + (data.message || 'Unknown error'), 'error');
                }
            } catch (error) {
                console.error('Error:', error);
                showToast('❌ Error removing from favorites', 'error');
            }
        }

        /**
         * Add to cart
         */
        async function addToCart(button) {
            const productId = button.getAttribute('data-product-id');
            const productName = button.getAttribute('data-name');
            const price = button.getAttribute('data-price');
            const image = button.getAttribute('data-image');

            button.disabled = true;
            const originalText = button.textContent;
            button.textContent = '⏳ Adding...';

            try {
                const formData = new FormData();
                formData.append('product_id', productId);
                formData.append('product_name', productName);
                formData.append('price', price);
                formData.append('image', image);
                formData.append('quantity', 1);

                const response = await fetch('auth-system/cart-api.php?action=add', {
                    method: 'POST',
                    body: formData
                });

                const data = await response.json();

                if (data.success) {
                    showToast('✅ Added to cart', 'success');
                } else {
                    showToast('❌ ' + (data.message || 'Error'), 'error');
                }
            } catch (error) {
                console.error('Error:', error);
                showToast('❌ Error adding to cart', 'error');
            } finally {
                button.disabled = false;
                button.textContent = originalText;
            }
        }

        /**
         * Display toast notification
         */
        function showToast(message, type) {
            const toast = document.getElementById('toast');
            if (!toast) return;

            toast.textContent = message;
            toast.className = 'toast ' + type;
            toast.style.display = 'block';

            setTimeout(() => {
                toast.style.display = 'none';
            }, 3000);
        }
    </script>

    <?php include 'footer-section.html'; ?>
</body>
</html>
