<?php
session_start();
require 'function.php';
require 'config.php';

if (!isset($_SESSION['login']) || $_SESSION['role'] !== 'admin') {
    header('location:login.php');
    exit;
}

$user_id = $_SESSION['id'];

// Handle Add Event
if (isset($_POST['add_event'])) {
    $acara = mysqli_real_escape_string($koneksi, $_POST['acara']);
    $tanggal = mysqli_real_escape_string($koneksi, $_POST['tanggal']);
    $jam = mysqli_real_escape_string($koneksi, $_POST['jam']);
    
    $query = "INSERT INTO event_id (acara, tanggal, jam, created_by) VALUES ('$acara', '$tanggal', '$jam', '$user_id')";
    if (mysqli_query($koneksi, $query)) {
        $new_event_id = mysqli_insert_id($koneksi);
        mysqli_query($koneksi, "INSERT INTO user_events (user_id, event_id) VALUES ('$user_id', '$new_event_id')");
        
        // Initialize event with baseline settings (copying from users_id)
        mysqli_query($koneksi, "UPDATE event_id e, users_id u SET 
             e.cover = u.cover, e.iframe = u.iframe, e.bg = u.bg, e.image = u.image, e.font = u.font, 
             e.color = u.color, e.text = u.text, e.size_welcome = u.size_welcome, e.size_tamu = u.size_tamu, e.timer = u.timer
             WHERE e.id = '$new_event_id' AND u.id = '$user_id'");
             
        $_SESSION['sukses'] = "Event created successfully!";
    } else {
        $_SESSION['gagal'] = "Failed to create event.";
    }
    header("Location: manage-events.php"); exit;
}

// Handle Activate Event
if (isset($_GET['activate'])) {
    $act_id = (int)$_GET['activate'];
    $check_access = mysqli_query($koneksi, "SELECT 1 FROM user_events WHERE user_id = '$user_id' AND event_id = '$act_id'");
    if (mysqli_num_rows($check_access) > 0 || $_SESSION['role'] === 'admin') {
        $_SESSION['active_event_id'] = $act_id;
        mysqli_query($koneksi, "UPDATE users_id SET active_event_id = '$act_id' WHERE id = '$user_id'");
        header("Location: dashboard.php");
        exit;
    }
}

// Handle Delete Event
if (isset($_GET['delete'])) {
    $del_id = (int)$_GET['delete'];
    if (mysqli_query($koneksi, "DELETE FROM event_id WHERE id = '$del_id'")) {
        mysqli_query($koneksi, "DELETE FROM user_events WHERE event_id = '$del_id'");
        mysqli_query($koneksi, "DELETE FROM categories WHERE event_id = '$del_id'");
        mysqli_query($koneksi, "DELETE FROM comment_id WHERE event_id = '$del_id'");
        $_SESSION['sukses'] = "Event deleted successfully!";
    }
    header("Location: manage-events.php"); exit;
}

$all_events = query("SELECT e.*, u.username as creator FROM event_id e LEFT JOIN users_id u ON e.created_by = u.id ORDER BY e.id DESC");

require 'header.php';
?>

<div class="container py-4">
    <div class="row mb-4 align-items-center">
        <div class="col-md-6">
             <h3 class="fw-bold text-gradient d-inline-block">Manage Events</h3>
             <p class="text-muted">Create and manage all your check-in events.</p>
        </div>
        <div class="col-md-6 text-md-end">
            <button class="btn btn-primary px-4 shadow-sm" data-bs-toggle="modal" data-bs-target="#AddEventModal">
                <i class="bi bi-plus-circle me-2"></i> Create New Event
            </button>
        </div>
    </div>

    <div class="glass-card">
        <div class="table-responsive">
            <table class="table table-hover align-middle mb-0">
                <thead>
                    <tr>
                        <th width="50">ID</th>
                        <th>Event Name</th>
                        <th>Date</th>
                        <th>Time</th>
                        <th>Created By</th>
                        <th class="text-center" width="200">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if(empty($all_events)): ?>
                        <tr><td colspan="6" class="text-center py-5 text-muted">No events found. Click "Create New Event" to get started.</td></tr>
                    <?php endif; ?>
                    <?php foreach ($all_events as $ev): ?>
                    <tr>
                        <td class="text-muted small">#<?= $ev['id'] ?></td>
                        <td class="fw-bold"><?= $ev['acara'] ?></td>
                        <td><?= $ev['tanggal'] ?></td>
                        <td><?= $ev['jam'] ?></td>
                        <td><span class="badge bg-light text-dark border"><?= $ev['creator'] ?: 'System' ?></span></td>
                        <td class="text-center">
                            <div class="d-flex gap-2 justify-content-center">
                                <a href="manage-events.php?activate=<?= $ev['id'] ?>" class="btn btn-primary btn-sm px-3">
                                    <i class="bi bi-play-fill me-1"></i> Manage
                                </a>
                                <a href="manage-events.php?delete=<?= $ev['id'] ?>" class="btn btn-outline-danger btn-sm p-1 px-2" onclick="return confirm('Delete this event and ALL its guests/categories?');">
                                    <i class="bi bi-trash"></i>
                                </a>
                            </div>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Add Event Modal -->
<div class="modal fade" id="AddEventModal" tabindex="-1" aria-hidden="true" style="z-index: 1060;">
    <div class="modal-dialog">
        <div class="modal-content shadow">
            <div class="modal-header border-0">
                <h5 class="fw-bold"><i class="bi bi-calendar-plus me-2"></i> New Event</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form action="" method="post">
                    <div class="mb-3">
                        <label class="form-label">Event Name</label>
                        <input type="text" class="form-control" name="acara" placeholder="e.g. Wedding of Alex & Sarah" required>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Event Date</label>
                            <input type="text" class="form-control" name="tanggal" placeholder="e.g. 30 Juni 2024" required>
                            <div class="form-text small">Free text (e.g. 30 Juni 2024)</div>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Event Time</label>
                            <input type="text" class="form-control" name="jam" placeholder="e.g. 08:00 WIB" required>
                            <div class="form-text small">e.g. 08:00 WIB</div>
                        </div>
                    </div>
                    <button type="submit" name="add_event" class="btn btn-primary w-100 py-2">Create Event</button>
                </form>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>

<?php if (isset($_SESSION['sukses'])): ?>
<script>swal("Success", "<?= $_SESSION['sukses'] ?>", "success");</script>
<?php unset($_SESSION['sukses']); endif; ?>

<?php if (isset($_SESSION['gagal'])): ?>
<script>swal("Error", "<?= $_SESSION['gagal'] ?>", "error");</script>
<?php unset($_SESSION['gagal']); endif; ?>

</body>
</html>
