<?php
require_once '../includes/config.php';
require_once 'header.php';

$error = '';
$success = '';

// Handle Add Event
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['add_event'])) {
    $title = trim($_POST['title'] ?? '');
    $description = trim($_POST['description'] ?? '');
    $event_date = $_POST['event_date'] ?? '';
    $event_time = $_POST['event_time'] ?? '';
    $venue = trim($_POST['venue'] ?? '');
    $address = trim($_POST['address'] ?? '');
    $max_attendees = intval($_POST['max_attendees'] ?? 0);
    
    if (empty($title) || empty($event_date)) {
        $error = 'Please fill all required fields';
    } else {
        $banner_image = '';
        if (isset($_FILES['banner_image']) && $_FILES['banner_image']['error'] == 0) {
            $uploadResult = uploadFile($_FILES['banner_image']);
            if (isset($uploadResult['success'])) {
                $banner_image = $uploadResult['filename'];
            }
        }
        
        $stmt = $pdo->prepare("INSERT INTO events (title, description, event_date, event_time, venue, address, max_attendees, banner_image) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
        if ($stmt->execute([$title, $description, $event_date, $event_time, $venue, $address, $max_attendees ?: null, $banner_image])) {
            $success = 'Event added successfully';
        } else {
            $error = 'Failed to add event';
        }
    }
}

// Handle Delete Event
if (isset($_GET['delete'])) {
    $id = $_GET['delete'];
    $stmt = $pdo->prepare("DELETE FROM events WHERE id = ?");
    if ($stmt->execute([$id])) {
        $success = 'Event deleted successfully';
    } else {
        $error = 'Failed to delete event';
    }
}

// Get all events
$stmt = $pdo->query("SELECT * FROM events ORDER BY event_date DESC");
$events = $stmt->fetchAll();
?>

<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
    <h1 class="h2"><i class="fas fa-calendar-alt me-2"></i>Manage Events</h1>
    <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addEventModal">
        <i class="fas fa-plus me-2"></i>Add New Event
    </button>
</div>

<?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; ?>

<div class="card">
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-striped table-hover" id="eventsTable">
                <thead class="table-dark">
                    <tr>
                        <th>ID</th>
                        <th>Image</th>
                        <th>Title</th>
                        <th>Date</th>
                        <th>Venue</th>
                        <th>Attendees</th>
                        <th>Status</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($events as $event): ?>
                        <?php
                        $stmt = $pdo->prepare("SELECT COUNT(*) as count FROM event_registrations WHERE event_id = ?");
                        $stmt->execute([$event['id']]);
                        $registered = $stmt->fetch()['count'];
                        
                        $today = date('Y-m-d');
                        if ($event['event_date'] > $today) {
                            $status = '<span class="badge bg-success">Upcoming</span>';
                        } elseif ($event['event_date'] == $today) {
                            $status = '<span class="badge bg-info">Today</span>';
                        } else {
                            $status = '<span class="badge bg-secondary">Past</span>';
                        }
                        ?>
                        <tr>
                            <td><?php echo $event['id']; ?></td>
                            <td>
                                <?php if ($event['banner_image']): ?>
                                    <img src="<?php echo UPLOAD_URL . $event['banner_image']; ?>" style="width: 50px; height: 50px; object-fit: cover;">
                                <?php else: ?>
                                    <i class="fas fa-calendar fa-2x text-muted"></i>
                                <?php endif; ?>
                            </td>
                            <td><?php echo htmlspecialchars($event['title']); ?></td>
                            <td><?php echo formatDate($event['event_date']); ?></td>
                            <td><?php echo htmlspecialchars($event['venue']); ?></td>
                            <td><?php echo $registered; ?> / <?php echo $event['max_attendees'] ?: '∞'; ?></td>
                            <td><?php echo $status; ?></td>
                            <td>
                                <a href="event_manage.php?id=<?php echo $event['id']; ?>" class="btn btn-sm btn-info">
                                    <i class="fas fa-users"></i>
                                </a>
                                <button class="btn btn-sm btn-warning" onclick="editEvent(<?php echo $event['id']; ?>)">
                                    <i class="fas fa-edit"></i>
                                </button>
                                <a href="?delete=<?php echo $event['id']; ?>" class="btn btn-sm btn-danger" onclick="return confirm('Are you sure?')">
                                    <i class="fas fa-trash"></i>
                                </a>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Add Event Modal -->
<div class="modal fade" id="addEventModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title"><i class="fas fa-plus me-2"></i>Add New Event</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST" enctype="multipart/form-data">
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">Event Title *</label>
                                <input type="text" class="form-control" name="title" required>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Event Date *</label>
                                <input type="date" class="form-control" name="event_date" required>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Event Time</label>
                                <input type="time" class="form-control" name="event_time">
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Venue</label>
                                <input type="text" class="form-control" name="venue">
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">Max Attendees</label>
                                <input type="number" class="form-control" name="max_attendees" placeholder="Leave empty for unlimited">
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Banner Image</label>
                                <input type="file" class="form-control" name="banner_image" accept="image/*">
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Address</label>
                                <textarea class="form-control" name="address" rows="3"></textarea>
                            </div>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Description</label>
                        <textarea class="form-control" name="description" rows="4"></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" name="add_event" class="btn btn-primary">Add Event</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script src="https://cdn.datatables.net/1.11.5/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.11.5/js/dataTables.bootstrap5.min.js"></script>
<script>
$(document).ready(function() {
    $('#eventsTable').DataTable({
        pageLength: 25,
        order: [[3, 'desc']]
    });
});

function editEvent(id) {
    window.location.href = 'event_manage.php?id=' + id;
}
</script>

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