<?php
require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/BuyerSystem.php';

if (!isLoggedIn() || getUserType() !== 'buyer') {
    header('Location: ' . APP_URL . '/auth/login.php');
    exit();
}

use App\Database;
$database = Database::getInstance();
$db = $database->getConnection();
$currentUserId = getUserId();

// Handle remove favorite
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'remove') {
    $productId = (int)$_POST['product_id'];
    $sql = "DELETE FROM favorites WHERE user_id = ? AND product_id = ?";
    $stmt = $db->prepare($sql);
    $stmt->execute([$currentUserId, $productId]);
    
    $_SESSION['flash_message'] = 'Removed from favorites';
    $_SESSION['flash_type'] = 'success';
    header('Location: ' . APP_URL . '/buyer/favorites.php');
    exit();
}

// Get favorites
$sql = "SELECT f.*, p.*, u.full_name as seller_name, u.phone_number as seller_phone,
               d.district_name as seller_district
        FROM favorites f
        INNER JOIN products p ON f.product_id = p.id
        INNER JOIN users u ON p.seller_id = u.id
        LEFT JOIN districts d ON u.district_id = d.id
        WHERE f.user_id = ?
        ORDER BY f.created_at DESC";
$stmt = $db->prepare($sql);
$stmt->execute([$currentUserId]);
$favorites = $stmt->fetchAll(PDO::FETCH_ASSOC);

$pageTitle = 'My Favorites';
$breadcrumbs = [['title' => 'Favorites', 'url' => '']];

require_once __DIR__ . '/includes/base.php';
require_once __DIR__ . '/includes/helpers.php';
renderBuyerHeader($pageTitle, $breadcrumbs);
?>

<div class="card shadow-sm">
    <div class="card-header bg-white py-3">
        <h5 class="mb-0"><i class="bi bi-heart-fill text-danger me-2"></i>My Favorites (<?php echo count($favorites); ?>)</h5>
    </div>
    <div class="card-body">
        <?php if (empty($favorites)): ?>
            <div class="text-center py-5">
                <i class="bi bi-heart" style="font-size: 4rem; color: #d1d5db;"></i>
                <h5 class="mt-3 text-muted">No favorites yet</h5>
                <p class="text-muted">Save products you're interested in</p>
                <a href="<?php echo APP_URL; ?>/marketplace/" class="btn btn-primary mt-2">
                    <i class="bi bi-shop me-2"></i>Browse Products
                </a>
            </div>
        <?php else: ?>
            <div class="row g-4">
                <?php foreach ($favorites as $product): ?>
                <div class="col-md-4 col-sm-6">
                    <div class="card h-100">
                        <img src="<?php echo getProductImage($product['images']); ?>" 
                             class="card-img-top" style="height: 200px; object-fit: cover;"
                             alt="<?php echo htmlspecialchars($product['product_name']); ?>">
                        <div class="card-body">
                            <h6 class="card-title"><?php echo htmlspecialchars($product['product_name']); ?></h6>
                            <p class="text-muted small mb-2">
                                <i class="bi bi-person me-1"></i><?php echo htmlspecialchars($product['seller_name']); ?>
                            </p>
                            <h5 class="text-success mb-3"><?php echo formatCurrency($product['price_per_unit']); ?></h5>
                            <div class="d-flex gap-2">
                                <a href="<?php echo APP_URL; ?>/marketplace/product-details.php?id=<?php echo $product['product_id']; ?>" 
                                   class="btn btn-sm btn-primary flex-grow-1">
                                    <i class="bi bi-eye me-1"></i> View
                                </a>
                                <form method="POST" class="d-inline">
                                    <input type="hidden" name="action" value="remove">
                                    <input type="hidden" name="product_id" value="<?php echo $product['product_id']; ?>">
                                    <button type="submit" class="btn btn-sm btn-outline-danger">
                                        <i class="bi bi-heart-fill"></i>
                                    </button>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </div>
</div>

<?php renderBuyerFooter(); ?>