<?php
session_start();
if (!isset($_SESSION['admin_logged_in'])) {
    header('Location: index.php');
    exit();
}
require_once('../db.php');

$message = "";
$error = "";

$upload_dir = '../uploads/events/';
if (!file_exists($upload_dir)) {
    mkdir($upload_dir, 0777, true);
}

// Handle Delete
if (isset($_GET['delete'])) {
    $id = intval($_GET['delete']);
    $res = $conn->query("SELECT image FROM event_gallery WHERE id = $id");
    if ($row = $res->fetch_assoc()) {
        $img_file = $row['image'];
        if ($img_file && file_exists($upload_dir . $img_file) && !str_starts_with($img_file, 'http')) {
            @unlink($upload_dir . $img_file);
        }
    }
    $conn->query("DELETE FROM event_gallery WHERE id = $id");
    $message = "Event photo deleted successfully!";
}

// Handle Status Toggle
if (isset($_GET['toggle_status'])) {
    $id = intval($_GET['toggle_status']);
    $conn->query("UPDATE event_gallery SET status = IF(status=1, 0, 1) WHERE id = $id");
    header("Location: manage_events.php");
    exit();
}

// Handle Add / Edit
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $id = isset($_POST['id']) ? intval($_POST['id']) : 0;
    $title = trim($_POST['title'] ?? '');
    $order_num = intval($_POST['order_num'] ?? 0);

    if (empty($title)) {
        $title = "School Event";
    }

    $image_name = "";
    if (!empty($_FILES['image']['name'])) {
        $ext = strtolower(pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION));
        $allowed = ['jpg', 'jpeg', 'png', 'webp', 'gif'];
        if (in_array($ext, $allowed)) {
            $image_name = 'event_' . time() . '_' . rand(100, 999) . '.' . $ext;
            move_uploaded_file($_FILES['image']['tmp_name'], $upload_dir . $image_name);

            if ($id > 0) {
                $old_res = $conn->query("SELECT image FROM event_gallery WHERE id = $id");
                if ($old = $old_res->fetch_assoc()) {
                    if ($old['image'] && file_exists($upload_dir . $old['image'])) {
                        @unlink($upload_dir . $old['image']);
                    }
                }
            }
        } else {
            $error = "Invalid image file format! Use JPG, PNG, WEBP, or GIF.";
        }
    }

    if (empty($error)) {
        if ($id > 0) {
            if ($image_name !== "") {
                $stmt = $conn->prepare("UPDATE event_gallery SET title=?, image=?, order_num=? WHERE id=?");
                $stmt->bind_param("ssii", $title, $image_name, $order_num, $id);
            } else {
                $stmt = $conn->prepare("UPDATE event_gallery SET title=?, order_num=? WHERE id=?");
                $stmt->bind_param("sii", $title, $order_num, $id);
            }
            $stmt->execute();
            $message = "Event updated successfully!";
        } else {
            if ($image_name === "") {
                $error = "Please upload an event image!";
            } else {
                $stmt = $conn->prepare("INSERT INTO event_gallery (title, image, order_num, status) VALUES (?, ?, ?, 1)");
                $stmt->bind_param("ssi", $title, $image_name, $order_num);
                $stmt->execute();
                $message = "New event photo added successfully!";
            }
        }
    }
}

// Fetch all events
$events = $conn->query("SELECT * FROM event_gallery ORDER BY order_num ASC, id ASC");
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Events Gallery | BSPS Admin</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css">
    <style>
        :root { --primary: #0b3b60; --accent: #f5a623; --dark: #1e293b; }
        body { background: #f8fafc; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; }
        .sidebar { height: 100vh; width: 260px; position: fixed; background: var(--dark); color: #fff; padding-top: 20px; overflow-y: auto; }
        .sidebar a { color: rgba(255,255,255,0.7); text-decoration: none; padding: 13px 25px; display: block; transition: 0.3s; font-size: 14.5px; }
        .sidebar a:hover, .sidebar a.active { color: #fff; background: #0b3b60; border-left: 4px solid var(--accent); }
        .main-content { margin-left: 260px; padding: 35px; }
        .card { border: none; border-radius: 12px; box-shadow: 0 4px 18px rgba(0,0,0,0.06); }
        .event-thumb { width: 90px; height: 65px; object-fit: cover; border-radius: 8px; border: 2px solid #e2e8f0; }
    </style>
</head>
<body>
    <div class="sidebar">
        <div class="px-4 mb-4">
            <h4 class="fw-bold text-white mb-0">BSPS ADMIN</h4>
            <span class="small text-secondary">Control Panel</span>
        </div>
        <a href="dashboard.php"><i class="fas fa-home me-2"></i> Dashboard</a>
        <a href="manage_applications.php"><i class="fas fa-envelope-open-text me-2"></i> Applications Box</a>
        <a href="manage_schools.php"><i class="fas fa-school me-2"></i> Our Schools (Campuses)</a>
        <a href="manage_leadership.php"><i class="fas fa-users-cog me-2"></i> Board Leadership</a>
        <a href="manage_director.php"><i class="fas fa-user-tie me-2"></i> Director's Desk</a>
        <a href="manage_events.php" class="active"><i class="fas fa-calendar-alt me-2"></i> Events Gallery</a>
        <a href="manage_important_sites.php"><i class="fas fa-globe me-2"></i> Important Sites</a>
        <a href="manage_slider.php"><i class="fas fa-images me-2"></i> Manage Slider</a>
        <a href="manage_gallery.php"><i class="fas fa-photo-video me-2"></i> Manage Gallery</a>
        <a href="../index.php" target="_blank"><i class="fas fa-external-link-alt me-2"></i> Visit Website</a>
        <div class="mt-5 px-3">
            <a href="logout.php" class="btn btn-outline-danger w-100 text-start py-2"><i class="fas fa-sign-out-alt me-2"></i> Logout</a>
        </div>
    </div>

    <div class="main-content">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <div>
                <h2 class="fw-bold text-dark mb-1">Our Events Gallery</h2>
                <p class="text-muted mb-0">Manage the 5-photo mosaic grid displayed in the center of the leadership section.</p>
            </div>
            <button class="btn btn-primary px-4 py-2" data-bs-toggle="modal" data-bs-target="#eventModal" onclick="resetForm()">
                <i class="fas fa-plus me-2"></i> Add Event Photo
            </button>
        </div>

        <?php if($message): ?>
            <div class="alert alert-success alert-dismissible fade show" role="alert">
                <i class="fas fa-check-circle me-2"></i> <?php echo $message; ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

        <?php if($error): ?>
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                <i class="fas fa-exclamation-triangle me-2"></i> <?php echo $error; ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

        <div class="card p-3">
            <div class="table-responsive">
                <table class="table table-hover align-middle mb-0">
                    <thead class="table-light">
                        <tr>
                            <th width="80">Order</th>
                            <th width="110">Image</th>
                            <th>Event Title</th>
                            <th>Status</th>
                            <th class="text-end" width="160">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if($events && $events->num_rows > 0): ?>
                            <?php while($row = $events->fetch_assoc()): 
                                $img_src = (str_starts_with($row['image'], 'http') || str_starts_with($row['image'], 'images/')) 
                                    ? $row['image'] 
                                    : (file_exists('../uploads/events/' . $row['image']) ? '../uploads/events/' . $row['image'] : '../images/' . $row['image']);
                            ?>
                            <tr>
                                <td><span class="badge bg-secondary"><?php echo $row['order_num']; ?></span></td>
                                <td>
                                    <img src="<?php echo htmlspecialchars($img_src); ?>" alt="<?php echo htmlspecialchars($row['title']); ?>" class="event-thumb">
                                </td>
                                <td>
                                    <strong class="text-dark"><?php echo htmlspecialchars($row['title']); ?></strong>
                                </td>
                                <td>
                                    <a href="?toggle_status=<?php echo $row['id']; ?>" class="badge <?php echo $row['status'] == 1 ? 'bg-success' : 'bg-warning text-dark'; ?> text-decoration-none" title="Click to toggle">
                                        <?php echo $row['status'] == 1 ? '<i class="fas fa-check-circle me-1"></i> Active' : '<i class="fas fa-pause-circle me-1"></i> Inactive'; ?>
                                    </a>
                                </td>
                                <td class="text-end">
                                    <button class="btn btn-sm btn-outline-primary me-1" 
                                            onclick='editEvent(<?php echo json_encode($row); ?>, "<?php echo htmlspecialchars($img_src); ?>")'
                                            title="Edit">
                                        <i class="fas fa-edit"></i>
                                    </button>
                                    <a href="?delete=<?php echo $row['id']; ?>" 
                                       class="btn btn-sm btn-outline-danger" 
                                       onclick="return confirm('Are you sure you want to remove this event photo?');"
                                       title="Delete">
                                        <i class="fas fa-trash-alt"></i>
                                    </a>
                                </td>
                            </tr>
                            <?php endwhile; ?>
                        <?php else: ?>
                            <tr>
                                <td colspan="5" class="text-center py-4 text-muted">No event photos found. Click "Add Event Photo" to upload.</td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- Add/Edit Event Modal -->
    <div class="modal fade" id="eventModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <form method="POST" enctype="multipart/form-data">
                    <input type="hidden" name="id" id="event_id" value="0">
                    <div class="modal-header">
                        <h5 class="modal-title fw-bold" id="modalTitle">Add Event Photo</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <div class="mb-3">
                            <label class="form-label fw-semibold">Event Title / Tag</label>
                            <input type="text" name="title" id="event_title" class="form-control" placeholder="e.g. Annual Function, Award Ceremony" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label fw-semibold">Grid Order (1 to 5)</label>
                            <input type="number" name="order_num" id="event_order" class="form-control" value="1" min="1" max="10">
                            <small class="text-muted">1 is main large photo, 2-5 are side photos.</small>
                        </div>
                        <div class="mb-3">
                            <label class="form-label fw-semibold">Event Photo <span class="text-danger">*</span></label>
                            <input type="file" name="image" id="event_image" class="form-control" accept="image/*" onchange="previewImage(this)">
                            <div class="mt-2 text-center" id="preview_wrap" style="display:none;">
                                <img id="preview_img" src="" style="width: 120px; height: 80px; object-fit: cover; border-radius: 8px; border: 2px solid #cbd5e1;">
                                <p class="small text-muted mt-1 mb-0">Image Preview</p>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-primary px-4"><i class="fas fa-save me-1"></i> Save Event</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        function resetForm() {
            document.getElementById('event_id').value = '0';
            document.getElementById('event_title').value = '';
            document.getElementById('event_order').value = '1';
            document.getElementById('event_image').value = '';
            document.getElementById('preview_wrap').style.display = 'none';
            document.getElementById('modalTitle').innerText = 'Add Event Photo';
        }

        function editEvent(data, imgSrc) {
            document.getElementById('event_id').value = data.id;
            document.getElementById('event_title').value = data.title;
            document.getElementById('event_order').value = data.order_num;
            document.getElementById('event_image').value = '';
            
            if (imgSrc) {
                document.getElementById('preview_img').src = imgSrc;
                document.getElementById('preview_wrap').style.display = 'block';
            }
            document.getElementById('modalTitle').innerText = 'Edit Event Photo';
            var myModal = new bootstrap.Modal(document.getElementById('eventModal'));
            myModal.show();
        }

        function previewImage(input) {
            if (input.files && input.files[0]) {
                var reader = new FileReader();
                reader.onload = function(e) {
                    document.getElementById('preview_img').src = e.target.result;
                    document.getElementById('preview_wrap').style.display = 'block';
                }
                reader.readAsDataURL(input.files[0]);
            }
        }
    </script>
</body>
</html>
