<?php
// หน้าแสดงรายการสินค้าที่ผู้ซื้อกดถูกใจ (favorites.php)
require_once 'auth.php';

// ตรวจสอบว่าผู้ซื้อเข้าสู่ระบบแล้วหรือยัง
requireBuyerLogin();

$user = getCurrentUser();
$userId = $user['id'];

// ดึงรายการสินค้าที่ผู้ใช้งานคนนี้กดถูกใจ
try {
    $stmt = $conn->prepare("
        SELECT p.*, c.name as category_name,
        (SELECT image_url FROM product_images WHERE product_id = p.id AND is_main = 1 LIMIT 1) as main_image,
        (SELECT image_url FROM product_images WHERE product_id = p.id ORDER BY sort_order ASC LIMIT 1) as fallback_image,
        pl.created_at as liked_at
        FROM product_likes pl
        JOIN products p ON pl.product_id = p.id
        LEFT JOIN categories c ON p.category_id = c.id
        WHERE pl.user_id = :user_id AND p.status = 'active'
        ORDER BY pl.created_at DESC
    ");
    $stmt->execute([':user_id' => $userId]);
    $likedProducts = $stmt->fetchAll();
} catch (PDOException $e) {
    $likedProducts = [];
}

// นับจำนวนสินค้าในตะกร้า
$cartCount = 0;
if (isset($_SESSION['cart'])) {
    foreach ($_SESSION['cart'] as $item) {
        $cartCount += $item['qty'];
    }
}
?>
<!DOCTYPE html>
<html lang="th">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>สินค้าที่ถูกใจ - AMARA STUDIO</title>
    <link rel="stylesheet" href="style.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css">
</head>
<body>

    <!-- Header Navigation -->
    <header>
        <div class="nav-container">
            <a href="index.php" class="logo">AMARA<span>STUDIO</span></a>
            <ul class="nav-menu">
                <li><a href="index.php" class="nav-link">คอลเลกชันทั้งหมด</a></li>
                <li>
                    <a href="cart.php" class="nav-link cart-icon-wrapper">
                        ตะกร้าสินค้า
                        <span class="cart-count" id="cart-nav-count"><?= $cartCount ?></span>
                    </a>
                </li>
                <li><a href="manual.php" class="nav-link">📖 คู่มือการใช้งาน</a></li>
                <li><a href="favorites.php" class="nav-link active">❤️ สินค้าที่ถูกใจ</a></li>
                <?php if (isLoggedIn()): ?>
                    <li style="display: flex; align-items: center; gap: 10px; margin-left: 15px;">
                        <span style="color: var(--primary); font-size: 14px;">👋 <?= htmlspecialchars(getAdminName()) ?></span>
                        <a href="logout.php" class="btn btn-sm btn-outline-danger" style="padding: 4px 10px; font-size: 12px;">ออกจากระบบ</a>
                    </li>
                <?php else: ?>
                    <li><a href="login.php" class="nav-link admin-btn">เข้าสู่ระบบ</a></li>
                <?php endif; ?>

            </ul>
        </div>
    </header>

    <div class="container" style="margin-top: 40px; margin-bottom: 60px;">
        <div style="margin-bottom: 30px;">
            <h1 style="font-size: 28px; font-weight: 700; color: var(--dark-text);">❤️ สินค้าที่ถูกใจของคุณ</h1>
            <p style="color: #718096; font-size: 15px; margin-top: 5px;">รายการสินค้าที่คุณบันทึกไว้ดูภายหลัง</p>
        </div>

        <?php if (empty($likedProducts)): ?>
            <div style="text-align: center; padding: 60px 20px; background: white; border-radius: var(--radius); box-shadow: var(--shadow);">
                <div style="font-size: 50px; margin-bottom: 15px;">🤍</div>
                <h3 style="font-size: 20px; color: var(--dark-text);">ยังไม่มีสินค้าในรายการถูกใจ</h3>
                <p style="color: #a0aec0; margin-top: 8px; margin-bottom: 25px;">เลือกชมสินค้าและกดปุ่ม ❤️ เพื่อเก็บไว้ในรายการโปรด</p>
                <a href="index.php" class="btn btn-primary">เลือกชมสินค้าเลย</a>
            </div>
        <?php else: ?>
            <div class="product-grid" id="favorites-grid">
                <?php foreach ($likedProducts as $prod): 
                    $imgUrl = !empty($prod['main_image']) ? $prod['main_image'] : (!empty($prod['fallback_image']) ? $prod['fallback_image'] : 'https://via.placeholder.com/600x800?text=No+Image');
                ?>
                    <div class="product-card" id="product-card-<?= $prod['id'] ?>" style="position: relative;">
                        <button type="button" class="btn-like active" onclick="toggleLike(<?= $prod['id'] ?>, this)" title="ยกเลิกถูกใจ" style="position: absolute; top: 12px; right: 12px; z-index: 5; background: rgba(255,255,255,0.9); border: none; border-radius: 50%; width: 36px; height: 36px; display: flex; align-items: center; justify-content: center; cursor: pointer; box-shadow: 0 2px 8px rgba(0,0,0,0.15); transition: transform 0.2s;">
                            ❤️
                        </button>
                        <a href="product.php?id=<?= $prod['id'] ?>" style="text-decoration: none; color: inherit; display: flex; flex-direction: column; height: 100%;">
                            <div class="product-card-img-wrapper">
                                <img src="<?= htmlspecialchars($imgUrl) ?>" alt="<?= htmlspecialchars($prod['name']) ?>" class="product-card-img" loading="lazy">
                            </div>
                            <div class="product-card-info">
                                <span class="product-card-cat"><?= htmlspecialchars($prod['category_name'] ?? 'สินค้า') ?></span>
                                <h3 class="product-card-title"><?= htmlspecialchars($prod['name']) ?></h3>
                                <div class="product-card-price-row">
                                    <span class="product-card-price">฿<?= number_format($prod['base_price'], 2) ?></span>
                                    <span style="font-size: 13px; color: var(--primary); font-weight: 600;">ดูรายละเอียด →</span>
                                </div>
                            </div>
                        </a>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <script>
    function toggleLike(productId, btn) {
        fetch('api.php?action=toggle_like', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ product_id: productId })
        })
        .then(res => res.json())
        .then(data => {
            if (data.success) {
                if (!data.liked) {
                    // ลบการ์ดออกจากหน้า favorites
                    const card = document.getElementById('product-card-' + productId);
                    if (card) {
                        card.style.opacity = '0';
                        card.style.transform = 'scale(0.9)';
                        card.style.transition = 'all 0.3s ease';
                        setTimeout(() => {
                            card.remove();
                            if (document.querySelectorAll('.product-card').length === 0) {
                                location.reload();
                            }
                        }, 300);
                    }
                }
                const Toast = Swal.mixin({
                    toast: true,
                    position: 'top-end',
                    showConfirmButton: false,
                    timer: 2000
                });
                Toast.fire({
                    icon: 'success',
                    title: data.message
                });
            } else {
                Swal.fire({ icon: 'error', title: 'ข้อผิดพลาด', text: data.message });
            }
        });
    }
    </script>
</body>
</html>
