<?php
require_once 'includes/config.php';
redirectIfNotLoggedIn();

$userData = getMemberData($pdo, $_SESSION['user_id']);
$error = '';
$success = '';

// Handle event registration
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['register_event'])) {
    $event_id = $_POST['event_id'] ?? 0;
    
    if ($event_id) {
        // Check if already registered
        $stmt = $pdo->prepare("SELECT id FROM event_registrations WHERE event_id = ? AND member_id = ?");
        $stmt->execute([$event_id, $_SESSION['user_id']]);
        
        if ($stmt->rowCount() == 0) {
            $stmt = $pdo->prepare("INSERT INTO event_registrations (event_id, member_id) VALUES (?, ?)");
            $stmt->execute([$event_id, $_SESSION['user_id']]);
            
            // Update current attendees count
            $stmt = $pdo->prepare("UPDATE events SET current_attendees = current_attendees + 1 WHERE id = ?");
            $stmt->execute([$event_id]);
            
            $success = 'Successfully registered for the event!';
        } else {
            $error = 'You are already registered for this event.';
        }
    }
}

// Handle cancellation
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['cancel_registration'])) {
    $event_id = $_POST['event_id'] ?? 0;
    
    if ($event_id) {
        $stmt = $pdo->prepare("DELETE FROM event_registrations WHERE event_id = ? AND member_id = ?");
        $stmt->execute([$event_id, $_SESSION['user_id']]);
        
        $stmt = $pdo->prepare("UPDATE events SET current_attendees = current_attendees - 1 WHERE id = ?");
        $stmt->execute([$event_id]);
        
        $success = 'Registration cancelled successfully!';
    }
}

// Get all events
$stmt = $pdo->prepare("SELECT e.*, 
                      (SELECT COUNT(*) FROM event_registrations WHERE event_id = e.id) as registered_count,
                      (SELECT COUNT(*) FROM event_registrations WHERE event_id = e.id AND member_id = ?) as is_registered
                      FROM events e 
                      WHERE e.event_date >= CURDATE() 
                      ORDER BY e.event_date ASC");
$stmt->execute([$_SESSION['user_id']]);
$upcomingEvents = $stmt->fetchAll();

$stmt = $pdo->prepare("SELECT e.*, 
                      (SELECT COUNT(*) FROM event_registrations WHERE event_id = e.id) as registered_count,
                      (SELECT COUNT(*) FROM event_registrations WHERE event_id = e.id AND member_id = ?) as is_registered
                      FROM events e 
                      WHERE e.event_date < CURDATE() 
                      ORDER BY e.event_date DESC LIMIT 10");
$stmt->execute([$_SESSION['user_id']]);
$pastEvents = $stmt->fetchAll();

// Get user's registered events
$stmt = $pdo->prepare("SELECT e.*, er.registration_date 
                      FROM events e 
                      JOIN event_registrations er ON e.id = er.event_id 
                      WHERE er.member_id = ? AND e.event_date >= CURDATE()
                      ORDER BY e.event_date ASC");
$stmt->execute([$_SESSION['user_id']]);
$myEvents = $stmt->fetchAll();
?>

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

<div class="row">
    <div class="col-12">
        <div class="card">
            <div class="card-header bg-primary text-white">
                <h4 class="mb-0"><i class="fas fa-calendar-alt me-2"></i>Events & Activities</h4>
            </div>
            <div class="card-body">
                <?php if ($error): ?>
                    <div class="alert alert-danger"><?php echo $error; ?></div>
                <?php endif; ?>
                
                <?php if ($success): ?>
                    <div class="alert alert-success"><?php echo $success; ?></div>
                <?php endif; ?>
                
                <!-- Stats Row -->
                <div class="row mb-4">
                    <div class="col-md-4">
                        <div class="alert alert-primary text-center">
                            <h3><?php echo count($upcomingEvents); ?></h3>
                            <p class="mb-0">Upcoming Events</p>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="alert alert-success text-center">
                            <h3><?php echo count($myEvents); ?></h3>
                            <p class="mb-0">My Registrations</p>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="alert alert-secondary text-center">
                            <h3><?php echo count($pastEvents); ?></h3>
                            <p class="mb-0">Past Events</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- My Registered Events -->
<?php if (count($myEvents) > 0): ?>
<div class="row mt-4">
    <div class="col-12">
        <div class="card">
            <div class="card-header bg-success text-white">
                <h5 class="mb-0"><i class="fas fa-ticket-alt me-2"></i>My Registered Events</h5>
            </div>
            <div class="card-body">
                <div class="row">
                    <?php foreach ($myEvents as $event): ?>
                    <div class="col-md-6 mb-3">
                        <div class="card border-success">
                            <div class="card-header bg-success text-white">
                                <h6 class="mb-0"><?php echo htmlspecialchars($event['title']); ?></h6>
                            </div>
                            <div class="card-body">
                                <p><i class="fas fa-calendar"></i> <?php echo formatDate($event['event_date']); ?></p>
                                <p><i class="fas fa-clock"></i> <?php echo $event['event_time']; ?></p>
                                <p><i class="fas fa-map-marker-alt"></i> <?php echo htmlspecialchars($event['venue']); ?></p>
                                <small class="text-muted">Registered on: <?php echo formatDate($event['registration_date'], 'd M Y h:i A'); ?></small>
                                <form method="POST" class="mt-2">
                                    <input type="hidden" name="event_id" value="<?php echo $event['id']; ?>">
                                    <button type="submit" name="cancel_registration" class="btn btn-warning btn-sm" 
                                            onclick="return confirm('Are you sure you want to cancel?')">
                                        <i class="fas fa-times"></i> Cancel Registration
                                    </button>
                                </form>
                            </div>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>
    </div>
</div>
<?php endif; ?>

<!-- Upcoming Events -->
<div class="row mt-4">
    <div class="col-12">
        <div class="card">
            <div class="card-header bg-info text-white">
                <h5 class="mb-0"><i class="fas fa-calendar-week me-2"></i>Upcoming Events</h5>
            </div>
            <div class="card-body">
                <?php if (count($upcomingEvents) > 0): ?>
                    <div class="row">
                        <?php foreach ($upcomingEvents as $event): ?>
                        <div class="col-md-6 mb-3">
                            <div class="card h-100">
                                <?php if ($event['banner_image']): ?>
                                    <img src="<?php echo UPLOAD_URL . $event['banner_image']; ?>" class="card-img-top" style="height: 180px; object-fit: cover;">
                                <?php endif; ?>
                                <div class="card-body">
                                    <h5 class="card-title"><?php echo htmlspecialchars($event['title']); ?></h5>
                                    <p class="card-text">
                                        <i class="fas fa-calendar"></i> <?php echo formatDate($event['event_date']); ?><br>
                                        <i class="fas fa-clock"></i> <?php echo $event['event_time']; ?><br>
                                        <i class="fas fa-map-marker-alt"></i> <?php echo htmlspecialchars($event['venue']); ?><br>
                                        <i class="fas fa-users"></i> Registered: <?php echo $event['registered_count']; ?> / <?php echo $event['max_attendees'] ?: 'Unlimited'; ?>
                                    </p>
                                    <p class="card-text"><?php echo substr(htmlspecialchars($event['description']), 0, 100); ?>...</p>
                                </div>
                                <div class="card-footer">
                                    <?php if ($event['is_registered']): ?>
                                        <span class="badge bg-success">Registered</span>
                                        <form method="POST" class="d-inline">
                                            <input type="hidden" name="event_id" value="<?php echo $event['id']; ?>">
                                            <button type="submit" name="cancel_registration" class="btn btn-warning btn-sm">
                                                Cancel
                                            </button>
                                        </form>
                                    <?php else: ?>
                                        <?php if (!$event['max_attendees'] || $event['registered_count'] < $event['max_attendees']): ?>
                                            <form method="POST">
                                                <input type="hidden" name="event_id" value="<?php echo $event['id']; ?>">
                                                <button type="submit" name="register_event" class="btn btn-primary btn-sm">
                                                    Register Now
                                                </button>
                                            </form>
                                        <?php else: ?>
                                            <span class="badge bg-danger">Full</span>
                                        <?php endif; ?>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                <?php else: ?>
                    <p class="text-center text-muted">No upcoming events at the moment.</p>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<!-- Past Events -->
<?php if (count($pastEvents) > 0): ?>
<div class="row mt-4">
    <div class="col-12">
        <div class="card">
            <div class="card-header bg-secondary text-white">
                <h5 class="mb-0"><i class="fas fa-history me-2"></i>Past Events</h5>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-striped">
                        <thead>
                            <tr>
                                <th>Event</th>
                                <th>Date</th>
                                <th>Venue</th>
                                <th>Status</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($pastEvents as $event): ?>
                            <tr>
                                <td><?php echo htmlspecialchars($event['title']); ?></td>
                                <td><?php echo formatDate($event['event_date']); ?></td>
                                <td><?php echo htmlspecialchars($event['venue']); ?></td>
                                <td>
                                    <?php if ($event['is_registered']): ?>
                                        <span class="badge bg-success">Attended</span>
                                    <?php else: ?>
                                        <span class="badge bg-secondary">Missed</span>
                                    <?php endif; ?>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>
<?php endif; ?>

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