<?php
session_start();

// --- DATABASE CONNECTION ---
$host   = "webdev.iyaserver.com";
$userid = "dhreid_guest";
$userpw = "tPTG;A+J{]Ze";
$db     = "dhreid_marketplace";

$mysql = new mysqli($host, $userid, $userpw, $db);
if ($mysql->connect_errno) { die("DB Error: " . $mysql->connect_error); }

// Login Check
if (empty($_SESSION['user_id'])) {
    header("Location: loginPage.php");
    exit();
}

$user_id = $_SESSION['user_id'];

// FETCH SAVED ITEMS
$sql = "
    SELECT 
        i.item_id, 
        i.title, 
        i.price_cents, 
        i.description, 
        (SELECT url FROM item_images WHERE item_id = i.item_id ORDER BY is_primary DESC LIMIT 1) AS image_url
    FROM saved_items s
    JOIN items i ON s.item_id = i.item_id
    WHERE s.user_id = ?
    ORDER BY s.created_at DESC
";

$stmt = $mysql->prepare($sql);
$stmt->bind_param("i", $user_id);
$stmt->execute();
$res = $stmt->get_result();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>My Saved Items</title>
    <link rel="stylesheet" href="stylesheet.css">
    <style>
        .saved-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
            gap: 20px;
            margin-top: 30px;
        }
        .saved-card {
            background: white;
            border: 1px solid var(--border);
            border-radius: 12px;
            overflow: hidden;
            box-shadow: var(--shadow-sm);
            transition: transform 0.2s ease;
            position: relative;
        }
        .saved-card:hover { transform: translateY(-4px); box-shadow: var(--shadow-md); }
        .saved-thumb {
            height: 200px;
            width: 100%;
            object-fit: cover;
            background: #f0f0f0;
        }
        .saved-info { padding: 15px; }
        .saved-title { font-weight: bold; margin-bottom: 5px; display: block; color: var(--text); }
        .saved-price { color: #990000; font-weight: bold; }

        .remove-btn {
            background: #ffebeb;
            color: #990000;
            border: 1px solid #fab1b1;
            width: 100%;
            padding: 10px;
            text-align: center;
            font-size: 14px;
            cursor: pointer;
            border-bottom-left-radius: 12px;
            border-bottom-right-radius: 12px;
            font-weight: 600;
            transition: background 0.2s;
        }
        .remove-btn:hover { background: #fee2e2; }
    </style>
</head>
<body>

<?php include 'nav.php'; ?>

<main class="wrap">
    <h1>My Saved Items</h1>
    <p>Items you are watching.</p>

    <?php if ($res->num_rows == 0): ?>
        <div style="text-align:center; padding:50px; background:white; border-radius:12px; margin-top:20px;">
            <h3>No saved items yet.</h3>
            <p>Go browse the marketplace and click the heart icon to save things for later.</p>
            <br>
            <a href="search.php" class="btn primary">Start Browsing</a>
        </div>
    <?php else: ?>
        <div class="saved-grid">
            <?php while($row = $res->fetch_assoc()):
                $image_url = !empty($row['image_url']) ? $row['image_url'] : "no-image.png";
                $price = '$' . number_format($row['price_cents']/100, 2);
                ?>
                <div class="saved-card" id="card-<?php echo $row['item_id']; ?>">
                    <a href="details_page.php?item_id=<?php echo $row['item_id']; ?>">
                        <img src="<?php echo htmlspecialchars($image_url); ?>" class="saved-thumb">
                    </a>
                    <div class="saved-info">
                        <a href="details_page.php?item_id=<?php echo $row['item_id']; ?>" class="saved-title">
                            <?php echo htmlspecialchars($row['title']); ?>
                        </a>
                        <div class="saved-price"><?php echo $price; ?></div>
                    </div>
                    <button class="remove-btn" onclick="removeSaved(<?php echo $row['item_id']; ?>)">
                        Remove from Saved
                    </button>
                </div>
            <?php endwhile; ?>
        </div>
    <?php endif; ?>

</main>

<script>
    function removeSaved(itemId) {
        if(!confirm("Remove this item?")) return;

        fetch('toggle_save.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ item_id: itemId })
        })
            .then(res => res.json())
            .then(data => {
                if (data.success && data.status === 'unsaved') {
                    // Fade out and remove the card
                    const card = document.getElementById('card-' + itemId);
                    card.style.opacity = '0';
                    setTimeout(() => card.remove(), 300);
                } else {
                    alert("Error removing item.");
                }
            });
    }
</script>

</body>
</html>