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

$eventId = $_GET['id'] ?? 0;
$error = '';
$success = '';

if (!$eventId) {
    header('Location: events.php');
    exit;
}

// Get event details
$stmt = $pdo->prepare("SELECT * FROM events WHERE id = ?");
$stmt->execute([$eventId]);
$event = $stmt->fetch();

if (!$event) {
    header('Location: events.php');
    exit;
}

// Handle Edit Event
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['update_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);
    $status = $_POST['status'] ?? 'upcoming';
    
    if (empty($title) || empty($event_date)) {
        $error = 'Please fill all required fields';
    } else {
        $banner_image = $event['banner_image'];
        if (isset($_FILES['banner_image']) && $_FILES['banner_image']['error'] == 0) {
            $uploadResult = uploadFile($_FILES['banner_image']);
            if (isset($uploadResult['success'])) {
                if ($banner_image && file_exists(UPLOAD_PATH . $banner_image)) {
                    unlink(UPLOAD_PATH . $banner_image);
                }
                $banner_image = $uploadResult['filename'];
            }
        }
        
        $stmt = $pdo->prepare("UPDATE events SET title = ?, description = ?, event_date = ?, event_time = ?, venue = ?, address = ?, max_attendees = ?, banner_image = ?, status = ? WHERE id = ?");
        if ($stmt->execute([$title, $description, $event_date, $event_time, $venue, $address, $max_attendees ?: null, $banner_image, $status, $eventId])) {
            $success = 'Event updated successfully';
            // Refresh event data
            $stmt = $pdo->prepare("SELECT * FROM events WHERE id = ?");
            $stmt->execute([$eventId]);
            $event = $stmt->fetch();
        } else {
            $error = 'Failed to update event';
        }
    }
}

// Get registered attendees
$stmt = $pdo->prepare("SELECT er.*, m.fullname, m.email, m.phone, m.membership_number 
                      FROM event_registrations er 
                      JOIN members m ON er.member_id = m.id 
                      WHERE er.event_id = ? 
                      ORDER BY er.registration_date DESC");
$stmt->execute([$eventId]);
$attendees = $stmt->fetchAll();

$registeredCount = count($attendees);
$statusBadge = [
    'upcoming' => 'success',
    'ongoing' => 'info',
    'completed' => 'secondary',
    'cancelled' => 'danger'
];
?>

<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 Event: <?php echo htmlspecialchars($event['title']); ?></h1>
    <div>
        <a href="events.php" class="btn btn-secondary">
            <i class="fas fa-arrow-left me-2"></i>Back to Events
        </a>
    </div>
</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="row">
    <div class="col-md-5">
        <div class="card">
            <div class="card-header bg-primary text-white">
                <h5 class="mb-0"><i class="fas fa-edit me-2"></i>Edit Event Details</h5>
            </div>
            <div class="card-body">
                <form method="POST" enctype="multipart/form-data">
                    <div class="row">
                        <div class="col-12">
                            <div class="mb-3">
                                <label class="form-label">Event Title *</label>
                                <input type="text" class="form-control" name="title" value="<?php echo htmlspecialchars($event['title']); ?>" required>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Event Date *</label>
                                <input type="date" class="form-control" name="event_date" value="<?php echo $event['event_date']; ?>" required>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Event Time</label>
                                <input type="time" class="form-control" name="event_time" value="<?php echo $event['event_time']; ?>">
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Venue</label>
                                <input type="text" class="form-control" name="venue" value="<?php echo htmlspecialchars($event['venue']); ?>">
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Address</label>
                                <textarea class="form-control" name="address" rows="2"><?php echo htmlspecialchars($event['address']); ?></textarea>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Max Attendees</label>
                                <input type="number" class="form-control" name="max_attendees" value="<?php echo $event['max_attendees']; ?>" placeholder="Unlimited">
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Status</label>
                                <select class="form-control" name="status">
                                    <option value="upcoming" <?php echo $event['status'] == 'upcoming' ? 'selected' : ''; ?>>Upcoming</option>
                                    <option value="ongoing" <?php echo $event['status'] == 'ongoing' ? 'selected' : ''; ?>>Ongoing</option>
                                    <option value="completed" <?php echo $event['status'] == 'completed' ? 'selected' : ''; ?>>Completed</option>
                                    <option value="cancelled" <?php echo $event['status'] == 'cancelled' ? 'selected' : ''; ?>>Cancelled</option>
                                </select>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Banner Image</label>
                                <?php if ($event['banner_image']): ?>
                                    <div class="mb-2">
                                        <img src="<?php echo UPLOAD_URL . $event['banner_image']; ?>" style="max-height: 100px;">
                                    </div>
                                <?php endif; ?>
                                <input type="file" class="form-control" name="banner_image" accept="image/*">
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Description</label>
                                <textarea class="form-control" name="description" rows="4"><?php echo htmlspecialchars($event['description']); ?></textarea>
                            </div>
                        </div>
                    </div>
                    <button type="submit" name="update_event" class="btn btn-primary w-100">Update Event</button>
                </form>
            </div>
        </div>
    </div>
    
    <div class="col-md-7">
        <div class="card">
            <div class="card-header bg-success text-white">
                <h5 class="mb-0"><i class="fas fa-users me-2"></i>Registered Attendees (<?php echo $registeredCount; ?>)</h5>
            </div>
            <div class="card-body">
                <?php if (count($attendees) > 0): ?>
                    <div class="table-responsive">
                        <table class="table table-striped" id="attendeesTable">
                            <thead>
                                <tr>
                                    <th>Name</th>
                                    <th>Membership No</th>
                                    <th>Email</th>
                                    <th>Phone</th>
                                    <th>Registered On</th>
                                    <th>Action</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($attendees as $attendee): ?>
                                <tr>
                                    <td><?php echo htmlspecialchars($attendee['fullname']); ?></td>
                                    <td><?php echo $attendee['membership_number']; ?></td>
                                    <td><?php echo $attendee['email']; ?></td>
                                    <td><?php echo $attendee['phone'] ?: 'N/A'; ?></td>
                                    <td><?php echo formatDate($attendee['registration_date'], 'd M Y h:i A'); ?></td>
                                    <td>
                                        <button class="btn btn-sm btn-danger" onclick="removeAttendee(<?php echo $attendee['id']; ?>, <?php echo $eventId; ?>)">
                                            <i class="fas fa-user-minus"></i>
                                        </button>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php else: ?>
                    <p class="text-center text-muted">No attendees registered yet.</p>
                <?php endif; ?>
            </div>
        </div>
        
        <!-- Event Stats -->
        <div class="card mt-4">
            <div class="card-header bg-info text-white">
                <h5 class="mb-0"><i class="fas fa-chart-bar me-2"></i>Event Statistics</h5>
            </div>
            <div class="card-body">
                <div class="row text-center">
                    <div class="col-md-4">
                        <h3><?php echo $registeredCount; ?></h3>
                        <p>Registered</p>
                    </div>
                    <div class="col-md-4">
                        <h3><?php echo $event['max_attendees'] ?: '∞'; ?></h3>
                        <p>Capacity</p>
                    </div>
                    <div class="col-md-4">
                        <h3><?php echo $event['max_attendees'] ? round(($registeredCount / $event['max_attendees']) * 100) . '%' : 'N/A'; ?></h3>
                        <p>Fill Rate</p>
                    </div>
                </div>
                <div class="progress mt-2" style="height: 10px;">
                    <div class="progress-bar bg-success" style="width: <?php echo $event['max_attendees'] ? ($registeredCount / $event['max_attendees']) * 100 : 0; ?>%"></div>
                </div>
            </div>
        </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() {
    $('#attendeesTable').DataTable({
        pageLength: 10,
        order: [[4, 'desc']]
    });
});

function removeAttendee(registrationId, eventId) {
    if (confirm('Are you sure you want to remove this attendee from the event?')) {
        window.location.href = 'event_remove.php?id=' + registrationId + '&event_id=' + eventId;
    }
}
</script>

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