<?php
require_once '../app/Core/init.php';

Auth::requireCustomer();

$customerModel = new Customer();
$user_id = Auth::id();
$customer_data = $customerModel->findByUserId($user_id);

if (!$customer_data) {
    redirect('profile.php');
}

$customer_id = $customer_data['id'];

// Handle remove
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['remove_favorite'])) {
    $item_id = (int)($_POST['item_id'] ?? 0);
    if ($item_id > 0) {
        $db = Database::getInstance();
        $db->execute("DELETE FROM favourites WHERE customer_id = ? AND item_id = ?", [$customer_id, $item_id]);
    }
    redirect('favourites.php');
}

// Pagination
$page = max(1, (int)($_GET['page'] ?? 1));
$limit = 12;
$offset = ($page - 1) * $limit;

// FIXED QUERY - Correct column names from your database
$db = Database::getInstance();
$favorites = $db->fetchAll("
    SELECT 
        f.id,
        f.item_id,
        f.created_at,
        i.title,
        i.slug,
        i.main_image,
        i.price_per_day,
        i.approval_status,
        i.status as availability_status,
        v.business_name as vendor_name,
        c.name as category_name
    FROM favourites f
    LEFT JOIN items i ON f.item_id = i.id
    LEFT JOIN vendors v ON i.vendor_id = v.id
    LEFT JOIN categories c ON i.category_id = c.id
    WHERE f.customer_id = ?
    ORDER BY f.created_at DESC
", [$customer_id]);

if (!is_array($favorites)) {
    $favorites = [];
}

$total_favorites = count($favorites);
$favorites = array_slice($favorites, $offset, $limit);
$total_pages = ceil($total_favorites / $limit);

$page_title = 'My Favorites';
$active_menu = 'favourites';

include '../templates/layouts/customer/head.php';
?>

<style>
    .favorite-card {
        transition: transform 0.3s ease, box-shadow 0.3s ease;
        border: none;
        box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        height: 100%;
    }
    .favorite-card:hover {
        transform: translateY(-5px);
        box-shadow: 0 8px 25px rgba(0,0,0,0.15);
    }
    .item-image {
        width: 100%;
        height: 200px;
        object-fit: cover;
    }
    .vendor-badge {
        font-size: 0.8rem;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    }
    .price-tag {
        font-size: 1.1rem;
        font-weight: 600;
        color: #2c3e50;
    }
    .empty-state {
        text-align: center;
        padding: 60px 20px;
    }
    .empty-state i {
        font-size: 4rem;
        margin-bottom: 20px;
        color: #dee2e6;
    }
    .availability-badge {
        position: absolute;
        top: 10px;
        left: 10px;
        z-index: 1;
    }
</style>

<body class="fixed sidebar-mini">
    <div class="wrapper">
        <nav class="sidebar">
            <div class="sidebar-header">
                <?php include '../templates/layouts/customer/navbar.php'; ?>
            </div>
        </nav>
        
        <div class="content-wrapper">
            <div class="main-content">
                <?php include '../templates/layouts/customer/header.php'; ?>

                <div class="container-fluid py-4">
                    <div class="row mb-4">
                        <div class="col-12">
                            <div class="d-flex justify-content-between align-items-center">
                                <div>
                                    <h1 class="h3 mb-1">
                                        <i class="fas fa-heart text-danger me-2"></i>My Favorites
                                    </h1>
                                    <p class="text-muted mb-0"><?= $total_favorites ?> items</p>
                                </div>
                                <a href="../items.php" class="btn btn-primary">
                                    <i class="fas fa-plus me-2"></i>Browse Items
                                </a>
                            </div>
                        </div>
                    </div>

                    <?php if (count($favorites) === 0): ?>
                        <div class="card">
                            <div class="card-body">
                                <div class="empty-state">
                                    <i class="fas fa-heart-broken"></i>
                                    <h4>No Favorites Yet</h4>
                                    <p class="fs-5 mb-4">Start exploring!</p>
                                    <a href="../items.php" class="btn btn-primary btn-lg">
                                        <i class="fas fa-search me-2"></i>Browse Items
                                    </a>
                                </div>
                            </div>
                        </div>
                    <?php else: ?>
                        <div class="row g-4">
                            <?php foreach ($favorites as $fav): ?>
                                <div class="col-lg-3 col-md-4 col-sm-6">
                                    <div class="card favorite-card position-relative">
                                        <?php if ($fav['availability_status'] === 'approved'): ?>
                                            <span class="badge bg-success availability-badge">
                                                <i class="fas fa-check-circle me-1"></i>Available
                                            </span>
                                        <?php else: ?>
                                            <span class="badge bg-danger availability-badge">
                                                <i class="fas fa-times-circle me-1"></i>Unavailable
                                            </span>
                                        <?php endif; ?>

                                        <?php 
                                        $img = $fav['main_image'] 
                                            ? "../public/uploads/items/" . htmlspecialchars($fav['main_image'])
                                            : "../assets/dist/img/placeholder.jpg";
                                        ?>
                                        <img src="<?= $img ?>" 
                                             alt="<?= htmlspecialchars($fav['title'] ?? 'Item') ?>" 
                                             class="item-image"
                                             onerror="this.src='../assets/dist/img/placeholder.jpg'">
                                        
                                        <div class="card-body">
                                            <?php if ($fav['category_name']): ?>
                                                <small class="text-muted">
                                                    <i class="fas fa-tag me-1"></i>
                                                    <?= htmlspecialchars($fav['category_name']) ?>
                                                </small>
                                            <?php endif; ?>

                                            <h6 class="card-title mt-2 mb-2">
                                                <a href="../item-details.php?slug=<?= htmlspecialchars($fav['slug']) ?>" 
                                                   class="text-decoration-none text-dark">
                                                    <?= htmlspecialchars($fav['title'] ?? 'Untitled') ?>
                                                </a>
                                            </h6>

                                            <?php if ($fav['vendor_name']): ?>
                                                <span class="badge vendor-badge mb-2">
                                                    <i class="fas fa-store me-1"></i>
                                                    <?= htmlspecialchars($fav['vendor_name']) ?>
                                                </span>
                                            <?php endif; ?>

                                            <div class="price-tag mb-2">
                                                ₦<?= number_format($fav['price_per_day'] ?? 0, 2) ?>/day
                                            </div>

                                            <small class="text-muted d-block">
                                                <i class="fas fa-heart me-1 text-danger"></i>
                                                <?= date('M d, Y', strtotime($fav['created_at'])) ?>
                                            </small>
                                        </div>

                                        <div class="card-footer bg-transparent border-0 pt-0">
                                            <div class="d-grid gap-2">
                                                <a href="../item-details.php?slug=<?= htmlspecialchars($fav['slug']) ?>" 
                                                   class="btn btn-outline-primary btn-sm">
                                                    <i class="fas fa-eye me-1"></i>View Details
                                                </a>
                                                <form method="POST" onsubmit="return confirm('Remove?')">
                                                    <input type="hidden" name="item_id" value="<?= $fav['item_id'] ?>">
                                                    <button type="submit" name="remove_favorite" class="btn btn-outline-danger btn-sm w-100">
                                                        <i class="fas fa-heart-broken me-1"></i>Remove
                                                    </button>
                                                </form>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>

                        <?php if ($total_pages > 1): ?>
                            <nav class="mt-4">
                                <ul class="pagination justify-content-center">
                                    <?php if ($page > 1): ?>
                                        <li class="page-item">
                                            <a class="page-link" href="?page=<?= $page - 1 ?>">Previous</a>
                                        </li>
                                    <?php endif; ?>

                                    <?php for ($i = max(1, $page - 2); $i <= min($total_pages, $page + 2); $i++): ?>
                                        <li class="page-item <?= $i === $page ? 'active' : '' ?>">
                                            <a class="page-link" href="?page=<?= $i ?>"><?= $i ?></a>
                                        </li>
                                    <?php endfor; ?>

                                    <?php if ($page < $total_pages): ?>
                                        <li class="page-item">
                                            <a class="page-link" href="?page=<?= $page + 1 ?>">Next</a>
                                        </li>
                                    <?php endif; ?>
                                </ul>
                            </nav>
                        <?php endif; ?>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>

    <?php include '../templates/layouts/customer/footer.php'; ?>
</body>
</html>