<?php
session_start();
require_once 'config.php';

// Check if logged in
$logged_in = isset($_SESSION['admin_logged_in']) && $_SESSION['admin_logged_in'] === true;

if (!$logged_in) {
    header('Location: admin.php');
    exit;
}

// Handle delete event
if (isset($_GET['delete']) && isset($_GET['event'])) {
    $event_slug = preg_replace('/[^a-z0-9-]/', '', strtolower(trim($_GET['event'])));
    
    $conn = getDBConnection();
    $stmt = $conn->prepare("SELECT id FROM events WHERE event_slug = ?");
    $stmt->bind_param("s", $event_slug);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows === 1) {
        // Delete event directory and files
        $event_dir = __DIR__ . '/events/' . $event_slug;
        if (is_dir($event_dir)) {
            $files = glob($event_dir . '/*');
            foreach ($files as $file) {
                if (is_file($file)) {
                    unlink($file);
                }
            }
            rmdir($event_dir);
        }
        
        // Delete from database
        $stmt->close();
        $stmt = $conn->prepare("DELETE FROM events WHERE event_slug = ?");
        $stmt->bind_param("s", $event_slug);
        $stmt->execute();
        $stmt->close();
        
        header('Location: admin_events.php?deleted=1');
        exit;
    }
    $stmt->close();
    $conn->close();
}

// Handle cleanup of expired events (run on page load) - 7 days after event_date
$conn = getDBConnection();
$now = new DateTime();

// Get all events with event_date
$cleanup_stmt = $conn->prepare("SELECT id, event_slug, event_date FROM events WHERE event_date IS NOT NULL");
$cleanup_stmt->execute();
$cleanup_result = $cleanup_stmt->get_result();

// Delete expired events and their files
while ($event = $cleanup_result->fetch_assoc()) {
    $event_date = new DateTime($event['event_date']);
    $expiry_date = (clone $event_date)->modify('+7 days');
    
    // Check if expired (7 days after event_date)
    if ($expiry_date < $now) {
        $event_slug = $event['event_slug'];
        $event_id = $event['id'];
        
        // Delete event directory and files
        $event_dir = __DIR__ . '/events/' . $event_slug;
        if (is_dir($event_dir)) {
            $files = glob($event_dir . '/*');
            foreach ($files as $file) {
                if (is_file($file)) {
                    @unlink($file);
                }
            }
            @rmdir($event_dir);
        }
        
        // Delete from database
        $delete_stmt = $conn->prepare("DELETE FROM events WHERE id = ?");
        $delete_stmt->bind_param("i", $event_id);
        $delete_stmt->execute();
        $delete_stmt->close();
    }
}

$cleanup_stmt->close();

// Get filter parameters
$filter_type = $_GET['filter_type'] ?? '';
$filter_user = $_GET['filter_user'] ?? '';

// Build query with filters (we'll filter expired events in PHP based on event_date + 7 days)
$query = "SELECT e.id, e.event_slug, e.event_name, e.event_type, e.celebrant1, e.celebrant2, e.event_date, e.user_id, e.created_at, 
          u.username, u.email 
          FROM events e 
          LEFT JOIN users u ON e.user_id = u.id 
          WHERE 1=1";
$params = [];
$types = "";

if (!empty($filter_type)) {
    $query .= " AND e.event_type = ?";
    $params[] = $filter_type;
    $types .= "s";
}

if (!empty($filter_user)) {
    $query .= " AND e.user_id = ?";
    $params[] = intval($filter_user);
    $types .= "i";
}

$query .= " ORDER BY e.created_at DESC";

$stmt = $conn->prepare($query);
if (!empty($types)) {
    $stmt->bind_param($types, ...$params);
}
$stmt->execute();
$result = $stmt->get_result();

$now = new DateTime();
if ($result && $result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        // Filter out expired events (7 days after event_date)
        if (!empty($row['event_date'])) {
            $event_date = new DateTime($row['event_date']);
            $expiry_date = (clone $event_date)->modify('+7 days');
            if ($expiry_date >= $now) {
                $events[] = $row;
            }
        } else {
            // Events without event_date don't expire (or use created_at as fallback)
            // For now, include them
            $events[] = $row;
        }
    }
}
$stmt->close();
$conn->close();

// Success messages
$deleted_success = isset($_GET['deleted']) && $_GET['deleted'] == '1';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Existing Events - Evently</title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" integrity="sha512-iecdLmaskl7CVkqkXNQ/ZH/XLlvWZOJyj7Yy7tcenmpD1ypASozpmT/E0iPtmFIB46ZmdtAc9eNBvH0H/ZpiBw==" crossorigin="anonymous" referrerpolicy="no-referrer" />
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        html, body {
            height: 100%;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
            background-color: #000000;
            color: #333;
            padding: 0;
            margin: 0;
            min-height: 100vh;
            display: flex;
            flex-direction: column;
        }

        .navbar {
            background-color: #ffffff;
            padding: 15px 20px;
            border-bottom: 1px solid #e0e0e0;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .navbar-brand {
            color: #000000;
            font-family: 'Inter', sans-serif;
            font-size: 20px;
            font-weight: 700;
            text-decoration: none;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .navbar-brand img {
            height: 30px;
            width: auto;
        }

        .navbar-nav {
            display: flex;
            gap: 20px;
            align-items: center;
        }

        .navbar-nav a {
            color: #000000;
            text-decoration: none;
            font-size: 14px;
            transition: opacity 0.2s;
        }

        .navbar-nav a:hover {
            opacity: 0.7;
        }

        .navbar-nav span {
            color: #000000;
        }

        .hamburger {
            display: none;
            flex-direction: column;
            cursor: pointer;
            padding: 5px;
            gap: 4px;
        }

        .hamburger span {
            width: 25px;
            height: 3px;
            background-color: #000000;
            transition: all 0.3s;
        }

        .hamburger.active span:nth-child(1) {
            transform: rotate(45deg) translate(5px, 5px);
        }

        .hamburger.active span:nth-child(2) {
            opacity: 0;
        }

        .hamburger.active span:nth-child(3) {
            transform: rotate(-45deg) translate(7px, -6px);
        }

        @media (max-width: 768px) {
            .hamburger {
                display: flex;
            }

            .navbar-nav {
                position: fixed;
                top: 60px;
                left: 0;
                right: 0;
                background-color: #ffffff;
                flex-direction: column;
                padding: 20px;
                border-bottom: 1px solid #e0e0e0;
                box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
                transform: translateY(-100%);
                opacity: 0;
                visibility: hidden;
                transition: all 0.3s ease;
                z-index: 1000;
            }

            .navbar-nav.active {
                transform: translateY(0);
                opacity: 1;
                visibility: visible;
            }

            .navbar-nav a,
            .navbar-nav span {
                padding: 12px 0;
                border-bottom: 1px solid #f0f0f0;
                width: 100%;
            }

            .navbar-nav a:last-child,
            .navbar-nav span:last-child {
                border-bottom: none;
            }
        }

        .content-wrapper {
            padding: 20px;
            flex: 1;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            background-color: #ffffff;
            border-radius: 0;
            padding: 40px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
        }

        h1 {
            font-size: 28px;
            font-weight: 400;
            margin-bottom: 30px;
            color: #2c3e50;
        }

        .nav-links {
            margin-bottom: 20px;
        }

        .nav-links a {
            color: #2c3e50;
            text-decoration: none;
            margin-right: 15px;
            font-size: 14px;
        }

        .nav-links a:hover {
            text-decoration: underline;
        }

        .alert {
            padding: 15px;
            border-radius: 0;
            margin-bottom: 20px;
        }

        .alert-success {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }

        .events-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }

        .events-table th,
        .events-table td {
            padding: 12px;
            text-align: left;
            border-bottom: 1px solid #e0e0e0;
        }

        .events-table th {
            background-color: #f8f9fa;
            font-weight: 500;
            color: #495057;
            font-size: 14px;
        }

        .events-table tr:hover {
            background-color: #f8f9fa;
        }

        .events-table td {
            vertical-align: middle;
        }

        .event-link {
            color: #2c3e50;
            font-size: 13px;
            word-break: break-all;
            text-decoration: none;
        }

        .event-link:hover {
            text-decoration: underline;
        }

        .event-name {
            font-weight: 500;
            color: #2c3e50;
        }

        .event-date {
            font-size: 13px;
            color: #6c757d;
        }

        .qr-code {
            text-align: center;
        }

        .qr-code img {
            border: 1px solid #e0e0e0;
            padding: 8px;
            background: white;
            border-radius: 4px;
            width: 80px;
            height: 80px;
        }

        .qr-link {
            font-size: 12px;
            color: #2c3e50;
            text-decoration: none;
            margin-top: 5px;
            display: inline-block;
        }

        .qr-link:hover {
            text-decoration: underline;
        }

        .event-actions {
            display: flex;
            gap: 8px;
            justify-content: center;
        }

        .btn-edit {
            background-color: #667eea;
            color: white;
        }

        .btn-danger {
            background-color: #dc3545;
            color: white;
        }

        .btn-secondary {
            background-color: #6c757d;
            color: white;
        }

        .event-actions a {
            padding: 8px 12px;
            font-size: 16px;
            border-radius: 4px;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            width: 36px;
            height: 36px;
            transition: transform 0.2s, opacity 0.2s;
        }

        .event-actions a:hover {
            transform: scale(1.1);
            opacity: 0.9;
        }

        .event-actions a:active {
            transform: scale(0.95);
        }

        .event-actions a i {
            font-size: 16px;
        }

        .footer {
            background-color: #ffffff;
            padding: 20px;
            border-top: 1px solid #e0e0e0;
            text-align: center;
            color: #666;
            font-size: 14px;
            margin-top: auto;
        }

        @media (max-width: 768px) {
            .container {
                padding: 15px;
            }

            .events-table {
                font-size: 12px;
            }

            .events-table th,
            .events-table td {
                padding: 8px 6px;
            }

            .events-table th:nth-child(5),
            .events-table th:nth-child(6),
            .events-table td:nth-child(5),
            .events-table td:nth-child(6) {
                display: none;
            }

            .event-actions {
                flex-direction: column;
                gap: 5px;
            }

            .event-actions a {
                width: 100%;
            }

            h1 {
                font-size: 24px;
            }

            .content-wrapper {
                padding: 10px;
            }
        }
    </style>
</head>
<body>
    <nav class="navbar">
        <a href="admin.php" class="navbar-brand">
            <img src="assets/img/logo.svg" alt="Evently">
            <span>Evently - Admin Panel</span>
        </a>
        <div class="navbar-nav">
            <a href="admin.php">Upload Event</a>
            <a href="admin_events.php">View Events</a>
            <a href="admin_password.php">Change Password</a>
            <span><?php echo htmlspecialchars($_SESSION['admin_username'] ?? 'Admin'); ?></span>
            <a href="admin.php?logout=1">Logout</a>
        </div>
    </nav>
    <div class="content-wrapper">
        <div class="container">
            <h1>Existing Events</h1>
            
            <?php if ($deleted_success): ?>
                <div class="alert alert-success">Event deleted successfully!</div>
            <?php endif; ?>
            
            <!-- Filters -->
            <div style="margin-bottom: 20px; padding: 15px; background-color: #f8f9fa; border: 1px solid #e0e0e0;">
                <form method="GET" style="display: flex; gap: 15px; align-items: end; flex-wrap: wrap;">
                    <div style="flex: 1; min-width: 200px;">
                        <label for="filter_type" style="display: block; margin-bottom: 5px; font-size: 14px; font-weight: 500; color: #495057;">Filter by Event Type:</label>
                        <select id="filter_type" name="filter_type" style="width: 100%; padding: 8px; border: 1px solid #ced4da; border-radius: 0; font-size: 14px;">
                            <option value="">All Types</option>
                            <option value="Wedding" <?php echo $filter_type === 'Wedding' ? 'selected' : ''; ?>>Wedding</option>
                            <option value="Funeral" <?php echo $filter_type === 'Funeral' ? 'selected' : ''; ?>>Funeral</option>
                            <option value="Memorial" <?php echo $filter_type === 'Memorial' ? 'selected' : ''; ?>>Memorial Service</option>
                            <option value="Anniversary" <?php echo $filter_type === 'Anniversary' ? 'selected' : ''; ?>>Anniversary</option>
                            <option value="Birthday" <?php echo $filter_type === 'Birthday' ? 'selected' : ''; ?>>Birthday</option>
                            <option value="Graduation" <?php echo $filter_type === 'Graduation' ? 'selected' : ''; ?>>Graduation</option>
                            <option value="Baptism" <?php echo $filter_type === 'Baptism' ? 'selected' : ''; ?>>Baptism</option>
                            <option value="Other" <?php echo $filter_type === 'Other' ? 'selected' : ''; ?>>Other</option>
                        </select>
                    </div>
                    <div style="flex: 1; min-width: 200px;">
                        <label for="filter_user" style="display: block; margin-bottom: 5px; font-size: 14px; font-weight: 500; color: #495057;">Filter by User:</label>
                        <select id="filter_user" name="filter_user" style="width: 100%; padding: 8px; border: 1px solid #ced4da; border-radius: 0; font-size: 14px;">
                            <option value="">All Users</option>
                            <?php
                            // Get all users for filter dropdown
                            $users_conn = getDBConnection();
                            $users_query = $users_conn->query("SELECT DISTINCT u.id, u.username, u.email FROM users u INNER JOIN events e ON u.id = e.user_id ORDER BY u.username");
                            while ($user = $users_query->fetch_assoc()): ?>
                                <option value="<?php echo $user['id']; ?>" <?php echo $filter_user == $user['id'] ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($user['username'] . ' (' . $user['email'] . ')'); ?>
                                </option>
                            <?php endwhile; 
                            $users_conn->close(); ?>
                            <option value="0" <?php echo $filter_user === '0' ? 'selected' : ''; ?>>Admin/System Events</option>
                        </select>
                    </div>
                    <div>
                        <button type="submit" style="padding: 8px 20px; background-color: #000000; color: #ffffff; border: none; border-radius: 0; font-size: 14px; cursor: pointer;">Filter</button>
                        <a href="admin_events.php" style="padding: 8px 20px; background-color: #6c757d; color: #ffffff; text-decoration: none; border-radius: 0; font-size: 14px; display: inline-block; margin-left: 10px;">Clear</a>
                    </div>
                </form>
            </div>
            
            <?php if (empty($events)): ?>
                <p style="color: #6c757d; margin-top: 20px;">No events found.</p>
            <?php else: ?>
                <?php 
                $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http';
                $host = $_SERVER['HTTP_HOST'];
                $base_url = $protocol . '://' . $host . dirname($_SERVER['SCRIPT_NAME']);
                ?>
                <table class="events-table">
                    <thead>
                        <tr>
                            <th>Event Name</th>
                            <th>Type</th>
                            <th>Names</th>
                            <th>Event Date</th>
                            <th>Uploaded By</th>
                            <th>Expires</th>
                            <th>Link</th>
                            <th>Actions</th>
                            <th>QR Code</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($events as $event): 
                            $event_url = $base_url . '/index.php?event=' . urlencode($event['event_slug']);
                            $qr_url = 'https://api.qrserver.com/v1/create-qr-code/?size=100x100&data=' . urlencode($event_url);
                            
                            // Calculate expiry date (7 days after event_date)
                            $now = new DateTime();
                            if (!empty($event['event_date'])) {
                                $event_date = new DateTime($event['event_date']);
                                $expiry_date = (clone $event_date)->modify('+7 days');
                                $days_remaining = $now->diff($expiry_date)->days;
                                $is_expired = $expiry_date < $now;
                            } else {
                                // Events without event_date don't expire
                                $expiry_date = null;
                                $days_remaining = null;
                                $is_expired = false;
                            }
                        ?>
                            <tr>
                                <td class="event-name"><?php echo htmlspecialchars($event['event_name']); ?></td>
                                <td><?php echo htmlspecialchars($event['event_type'] ?? 'Other'); ?></td>
                                <td>
                                    <?php echo htmlspecialchars($event['celebrant1']); ?>
                                    <?php if (!empty($event['celebrant2'])): ?>
                                        & <?php echo htmlspecialchars($event['celebrant2']); ?>
                                    <?php endif; ?>
                                </td>
                                <td class="event-date">
                                    <?php if ($event['event_date']): ?>
                                        <?php echo date('M j, Y', strtotime($event['event_date'])); ?>
                                    <?php else: ?>
                                        <span style="color: #adb5bd;">—</span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <?php if ($event['user_id'] == 0): ?>
                                        <span style="color: #6c757d; font-size: 13px;">Admin/System</span>
                                    <?php else: ?>
                                        <div style="font-size: 13px;">
                                            <div style="font-weight: 500; color: #2c3e50;"><?php echo htmlspecialchars($event['username'] ?? 'Unknown'); ?></div>
                                            <div style="color: #6c757d; font-size: 12px;"><?php echo htmlspecialchars($event['email'] ?? ''); ?></div>
                                        </div>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <?php if (empty($event['event_date'])): ?>
                                        <span style="color: #6c757d; font-size: 13px;">No expiry</span>
                                    <?php elseif ($is_expired): ?>
                                        <span style="color: #dc3545; font-size: 13px; font-weight: 500;">Expired</span>
                                    <?php else: ?>
                                        <div style="font-size: 13px;">
                                            <div style="color: #28a745; font-weight: 500;"><?php echo $days_remaining; ?> day<?php echo $days_remaining != 1 ? 's' : ''; ?> left</div>
                                            <div style="color: #6c757d; font-size: 12px;"><?php echo $expiry_date->format('M j, Y'); ?></div>
                                        </div>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <a href="index.php?event=<?php echo urlencode($event['event_slug']); ?>" class="event-link" target="_blank">
                                        View Event
                                    </a>
                                </td>
                                <td>
                                    <div class="event-actions">
                                        <a href="admin.php?edit=1&event=<?php echo urlencode($event['event_slug']); ?>" class="btn-edit" title="Edit Event"><i class="fas fa-edit"></i></a>
                                        <a href="?delete=1&event=<?php echo urlencode($event['event_slug']); ?>" class="btn-danger" onclick="return confirm('Are you sure you want to delete this event? This action cannot be undone.');" title="Delete Event"><i class="fas fa-trash"></i></a>
                                        <a href="index.php?event=<?php echo urlencode($event['event_slug']); ?>" class="btn-secondary" target="_blank" title="View Event"><i class="fas fa-eye"></i></a>
                                    </div>
                                </td>
                                <td>
                                    <div class="qr-code">
                                        <img src="<?php echo htmlspecialchars($qr_url); ?>" alt="QR Code">
                                        <br>
                                        <a href="qr_generator.php?event=<?php echo urlencode($event['event_slug']); ?>&size=500" target="_blank" class="qr-link">Download</a>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            <?php endif; ?>
        </div>
    </div>
    <footer class="footer">
        <p>&copy; <?php echo date('Y'); ?> Evently. All rights reserved.</p>
    </footer>
</body>
</html>

