<?php
define('SECURE_ACCESS', true);

$pageTitle = "Start Here";
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/auth.php';
requireLogin();

require_once __DIR__ . '/../includes/header.php';
?>

<style>
/* Modern Premium Event Card Styling */
.event-card {
    border: none;
    border-radius: 16px;
    background: #ffffff;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.03);
    transition: all 0.3s cubic-bezier(0.16, 1, 0.3, 1);
    overflow: hidden;
    display: flex;
    flex-direction: column;
    height: 100%;
    cursor: pointer;
    position: relative;
}
.event-card:hover {
    transform: translateY(-6px);
    box-shadow: 0 12px 30px rgba(13, 110, 253, 0.07), 0 4px 12px rgba(0, 0, 0, 0.02);
}
.event-card-banner {
    position: relative;
    height: 190px;
    overflow: hidden;
    background: #e9ecef;
}
.event-card-img {
    width: 100%;
    height: 100%;
    object-fit: cover;
    transition: transform 0.6s cubic-bezier(0.16, 1, 0.3, 1);
}
.event-card:hover .event-card-img {
    transform: scale(1.06);
}
.event-card-date {
    position: absolute;
    top: 16px;
    right: 16px;
    z-index: 10;
    width: 52px;
    height: 56px;
    background: rgba(255, 255, 255, 0.95);
    backdrop-filter: blur(8px);
    border-radius: 12px;
    box-shadow: 0 4px 10px rgba(0, 0, 0, 0.06);
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
}
.event-card-date .month {
    font-size: 0.62rem;
    font-weight: 800;
    color: #0d6efd;
    text-transform: uppercase;
    line-height: 1;
    letter-spacing: 0.8px;
    margin-bottom: 2px;
}
.event-card-date .day {
    font-size: 1.2rem;
    font-weight: 800;
    color: #1e293b;
    line-height: 1;
}
.event-card-body {
    padding: 20px;
    flex-grow: 1;
    display: flex;
    flex-direction: column;
}
.event-card-title {
    font-size: 1.15rem;
    font-weight: 700;
    line-height: 1.4;
    margin-bottom: 12px;
}
.event-card-title a {
    color: #1e293b;
    text-decoration: none;
    transition: color 0.2s ease;
}
.event-card-title a:hover {
    color: #0d6efd;
}
.event-card-meta {
    font-size: 0.82rem;
    color: #64748b;
    margin-bottom: 8px;
    display: flex;
    align-items: center;
    gap: 8px;
}
.event-card-meta i {
    color: #0d6efd;
    font-size: 0.9rem;
}
.event-card-desc {
    font-size: 0.85rem;
    color: #475569;
    line-height: 1.5;
    margin-top: 10px;
    margin-bottom: 0;
    display: -webkit-box;
    -webkit-line-clamp: 3;
    -webkit-box-orient: vertical;
    overflow: hidden;
    text-overflow: ellipsis;
}
.event-card-footer {
    padding: 15px 20px 20px 20px;
    background: transparent;
    border-top: 1px solid #f1f5f9;
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 8px;
}
</style>

<?php

// Handle filters
$search = trim($_GET['search'] ?? '');
$category = trim($_GET['category'] ?? '');

$query = "SELECT * FROM events WHERE start_date > NOW() AND status = 'published'";
$params = [];

if (!empty($search)) {
    $query .= " AND (title ILIKE ? OR description ILIKE ?)";
    $params[] = "%$search%";
    $params[] = "%$search%";
}

if (!empty($category)) {
    $query .= " AND category = ?";
    $params[] = $category;
}

$query .= " ORDER BY start_date ASC";

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

$total_records = 0;
$total_pages = 0;
$events_list = [];

try {
    if ($pdo) {
        // Count query
        $count_query = "SELECT COUNT(*) FROM events WHERE start_date > NOW() AND status = 'published'";
        if (!empty($search)) {
            $count_query .= " AND (title ILIKE ? OR description ILIKE ?)";
        }
        if (!empty($category)) {
            $count_query .= " AND category = ?";
        }
        $stmt_count = $pdo->prepare($count_query);
        $stmt_count->execute($params);
        $total_records = (int)$stmt_count->fetchColumn() ?: 0;
        $total_pages = ceil($total_records / $limit);

        // Fetch paginated query
        $paginated_query = $query . " LIMIT $limit OFFSET $offset";
        $stmt_list = $pdo->prepare($paginated_query);
        $stmt_list->execute($params);
        $events_list = $stmt_list->fetchAll(PDO::FETCH_ASSOC) ?: [];
    }
} catch (PDOException $e) {
    // Ignore
}

// Fetch categories for filter dropdown
$categories = [];
try {
    if ($pdo) {
        $categories = $pdo->query("SELECT DISTINCT category FROM events WHERE category IS NOT NULL AND category != '' AND status = 'published'")->fetchAll(PDO::FETCH_COLUMN) ?: [];
    }
} catch (PDOException $e) {
    // Ignore
}
?>

<div class="container-fluid px-md-5 py-4">
    <div class="row g-4 mb-4">
        <div class="col-12 col-lg-8">
            <h1 class="fw-bold text-dark h2 mb-1">Start Here</h1>
            <p class="text-secondary mb-0">Browse scheduled conferences, training workshops, and speaking events.</p>
        </div>
        <div class="col-12 col-lg-4 d-flex align-items-center justify-content-lg-end">
        </div>
    </div>

    <!-- Filters Section -->
    <div class="card border-0 shadow-sm mb-5 p-4 bg-white">
        <form method="GET" action="public_events">
            <div class="row g-3">
                <div class="col-12 col-md-6 col-lg-5">
                    <div class="input-group">
                        <span class="input-group-text bg-light text-secondary"><i class="bi bi-search"></i></span>
                        <input type="text" name="search" class="form-control" placeholder="Search events by title or keyword..." value="<?php echo htmlspecialchars($search); ?>">
                    </div>
                </div>
                <div class="col-12 col-md-4 col-lg-4">
                    <select name="category" class="form-select">
                        <option value="">-- All Categories --</option>
                        <?php foreach ($categories as $cat): ?>
                            <option value="<?php echo htmlspecialchars($cat); ?>" <?php echo $category === $cat ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars($cat); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-12 col-md-2 col-lg-3 d-grid">
                    <button type="submit" class="btn btn-primary fw-bold"><i class="bi bi-funnel-fill me-1"></i> Filter</button>
                </div>
            </div>
        </form>
    </div>

    <!-- Events List Grid -->
    <?php if (empty($events_list)): ?>
        <div class="text-center py-5 border rounded-3 bg-white shadow-sm">
            <div class="d-inline-flex p-3 bg-light rounded-circle mb-3">
                <i class="bi bi-calendar-x fs-1 text-muted"></i>
            </div>
            <h4 class="fw-bold text-dark">No Events Found</h4>
            <p class="text-secondary small max-w-480 mx-auto">We couldn't find any upcoming conferences matching your filter constraints. Adjust your parameters and try again!</p>
            <a href="public_events" class="btn btn-primary fw-bold btn-sm mt-2">Clear Filters</a>
        </div>
    <?php else: ?>
        <div class="row g-4">
            <?php foreach ($events_list as $event): ?>
                <?php
                $banner_img = !empty($event['banner_url']) ? $event['banner_url'] : 'https://images.unsplash.com/photo-1540575467063-178a50c2df87?w=600&auto=format&fit=crop';
                $start_ts = strtotime($event['start_date']);
                $day = date('d', $start_ts);
                $month = date('M', $start_ts);
                ?>
                <div class="col-12 col-md-6 col-lg-4">
                    <div class="event-card" onclick="if(!event.target.closest('a') && !event.target.closest('button')) { window.location.href='public_event/<?php echo $event['id']; ?>'; }">
                        <!-- Banner Image with Badges -->
                        <div class="event-card-banner">
                            <img src="<?php echo htmlspecialchars($banner_img); ?>" class="event-card-img" alt="<?php echo htmlspecialchars($event['title']); ?>">
                            
                            <!-- Premium Calendar Badge -->
                            <div class="event-card-date">
                                <span class="month"><?php echo $month; ?></span>
                                <span class="day"><?php echo $day; ?></span>
                            </div>

                            <!-- Status and Price Overlay Badges -->
                            <div class="position-absolute top-0 start-0 p-3 d-flex flex-column gap-1.5" style="z-index: 2;">
                                <span class="badge text-white font-monospace text-uppercase" style="background: rgba(0, 0, 0, 0.55); backdrop-filter: blur(8px); font-size: 0.65rem; border: 1px solid rgba(255, 255, 255, 0.15);">
                                    <?php echo strtoupper($event['event_type']); ?>
                                </span>
                            </div>
                        </div>

                        <!-- Card Body -->
                        <div class="event-card-body">
                            <span class="badge bg-primary-subtle text-primary mb-2 font-monospace align-self-start" style="font-size: 0.72rem;"><?php echo htmlspecialchars($event['category'] ?? 'Event'); ?></span>
                            
                            <h5 class="event-card-title">
                                <a href="public_event/<?php echo $event['id']; ?>">
                                    <?php echo htmlspecialchars($event['title']); ?>
                                </a>
                            </h5>
                            
                            <div class="event-card-meta">
                                <i class="bi bi-calendar3"></i>
                                <span><?php echo date('M d, Y', strtotime($event['start_date'])); ?></span>
                            </div>

                            <div class="event-card-meta">
                                <i class="bi bi-geo-alt"></i>
                                <span class="text-truncate" style="max-width: 250px;"><?php echo htmlspecialchars($event['location'] ?? 'Virtual'); ?></span>
                            </div>

                            <p class="event-card-desc">
                                <?php echo htmlspecialchars(strip_tags($event['description'])); ?>
                            </p>
                        </div>

                        <!-- Card Footer Actions -->
                        <div class="event-card-footer">
                            <span class="fw-bold text-dark fs-5">
                                <?php echo (float)$event['price'] > 0 ? '₹' . number_format($event['price'], 2) : '<span class="text-success fw-bold">FREE</span>'; ?>
                            </span>
                            <a href="public_event/<?php echo $event['id']; ?>" class="btn btn-outline-primary btn-sm px-3 fw-bold rounded-pill">
                                <i class="bi bi-info-circle me-1"></i> Details
                            </a>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>

        <!-- Pagination -->
        <?php if ($total_pages > 1): ?>
            <div class="d-flex flex-column flex-md-row justify-content-between align-items-center mt-5 gap-3">
                <div class="small text-secondary font-monospace">
                    Showing <?php echo $offset + 1; ?> to <?php echo min($offset + $limit, $total_records); ?> of <?php echo $total_records; ?> events
                </div>
                <nav aria-label="Page navigation">
                    <ul class="pagination pagination-sm mb-0">
                        <li class="page-item <?php echo $page <= 1 ? 'disabled' : ''; ?>">
                            <a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, ['page' => $page - 1])); ?>"><i class="bi bi-chevron-left"></i></a>
                        </li>
                        <?php
                        $start = max(1, $page - 2);
                        $end = min($total_pages, $page + 2);
                        for ($i = $start; $i <= $end; $i++):
                        ?>
                            <li class="page-item <?php echo $page === $i ? 'active' : ''; ?>">
                                <a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, ['page' => $i])); ?>"><?php echo $i; ?></a>
                            </li>
                        <?php endfor; ?>
                        <li class="page-item <?php echo $page >= $total_pages ? 'disabled' : ''; ?>">
                            <a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, ['page' => $page + 1])); ?>"><i class="bi bi-chevron-right"></i></a>
                        </li>
                    </ul>
                </nav>
            </div>
        <?php endif; ?>
    <?php endif; ?>
</div>

<?php
include __DIR__ . '/../includes/footer.php';
?>
