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

// Require admin login
requireRole('admin');

$pageTitle = 'Manage Activities - PSAU GAD';
$db = getDB();

// Handle delete action
if (isPost() && isset($_POST['action']) && $_POST['action'] === 'delete') {
    $activityId = (int)$_POST['activity_id'];
    
    try {
        $stmt = $db->prepare("UPDATE activities SET is_active = 0 WHERE activity_id = ?");
        $stmt->execute([$activityId]);
        setFlashMessage('success', 'Activity deleted successfully');
    } catch (Exception $e) {
        setFlashMessage('error', 'Failed to delete activity');
        logError('Activity deletion error: ' . $e->getMessage());
    }
    
    redirect('activities.php');
}

// Get filter parameters
$search = get('search', '');
$status = get('status', 'all');
$category = get('category', 'all');

// Build query
$query = "
    SELECT 
        a.*,
        COUNT(DISTINCT ar.registration_id) as registration_count,
        COUNT(DISTINCT CASE WHEN ar.status = 'approved' THEN ar.registration_id END) as approved_count
    FROM activities a
    LEFT JOIN activity_registrations ar ON a.activity_id = ar.activity_id
    WHERE a.is_active = 1
";

$params = [];

if (!empty($search)) {
    $query .= " AND (a.title LIKE ? OR a.description LIKE ?)";
    $params[] = "%$search%";
    $params[] = "%$search%";
}

if ($status === 'upcoming') {
    $query .= " AND a.activity_date >= CURDATE()";
} elseif ($status === 'past') {
    $query .= " AND a.activity_date < CURDATE()";
}

if ($category !== 'all') {
    $query .= " AND a.category = ?";
    $params[] = $category;
}

$query .= " GROUP BY a.activity_id ORDER BY a.activity_date DESC";

$stmt = $db->prepare($query);
$stmt->execute($params);
$activities = $stmt->fetchAll();

// Get categories for filter
$categories = ['Gender Sensitivity', 'Women Empowerment', 'LGBTQ+ Rights', 'Anti-VAWC', 'Other'];

include '../includes/header.php';
include '../includes/navbar.php';
?>

<div class="min-h-screen bg-gray-50 py-8">
    <div class="container mx-auto px-4">
        <!-- Page Header -->
        <div class="flex items-center justify-between mb-8">
            <div>
                <h1 class="text-3xl font-bold text-gray-900 mb-2">
                    <i class="fas fa-calendar-alt text-admin mr-3"></i>
                    Manage Activities
                </h1>
                <p class="text-gray-600">Create, edit, and manage GAD activities</p>
            </div>
            <a href="activity-form.php" class="bg-admin text-white px-6 py-3 rounded-lg hover:bg-admin-dark transition font-semibold">
                <i class="fas fa-plus mr-2"></i> Create Activity
            </a>
        </div>

        <?php displayFlashMessage(); ?>

        <!-- Filters -->
        <div class="bg-white rounded-xl shadow-lg p-6 mb-8">
            <form method="GET" class="grid grid-cols-1 md:grid-cols-4 gap-4">
                <!-- Search -->
                <div>
                    <label class="block text-sm font-semibold text-gray-700 mb-2">Search</label>
                    <input type="text" 
                           name="search" 
                           value="<?php echo htmlspecialchars($search); ?>"
                           placeholder="Search activities..."
                           class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-admin focus:border-transparent">
                </div>

                <!-- Status Filter -->
                <div>
                    <label class="block text-sm font-semibold text-gray-700 mb-2">Status</label>
                    <select name="status" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-admin focus:border-transparent">
                        <option value="all" <?php echo $status === 'all' ? 'selected' : ''; ?>>All Activities</option>
                        <option value="upcoming" <?php echo $status === 'upcoming' ? 'selected' : ''; ?>>Upcoming</option>
                        <option value="past" <?php echo $status === 'past' ? 'selected' : ''; ?>>Past</option>
                    </select>
                </div>

                <!-- Category Filter -->
                <div>
                    <label class="block text-sm font-semibold text-gray-700 mb-2">Category</label>
                    <select name="category" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-admin focus:border-transparent">
                        <option value="all" <?php echo $category === 'all' ? 'selected' : ''; ?>>All Categories</option>
                        <?php foreach ($categories as $cat): ?>
                            <option value="<?php echo $cat; ?>" <?php echo $category === $cat ? 'selected' : ''; ?>>
                                <?php echo $cat; ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <!-- Submit -->
                <div class="flex items-end">
                    <button type="submit" class="w-full bg-admin text-white px-4 py-2 rounded-lg hover:bg-admin-dark transition">
                        <i class="fas fa-filter mr-2"></i> Filter
                    </button>
                </div>
            </form>
        </div>

        <!-- Activities List -->
        <div class="bg-white rounded-xl shadow-lg overflow-hidden">
            <?php if (empty($activities)): ?>
                <div class="text-center py-16">
                    <i class="fas fa-calendar-times text-6xl text-gray-300 mb-4"></i>
                    <h3 class="text-xl font-semibold text-gray-600 mb-2">No Activities Found</h3>
                    <p class="text-gray-500 mb-6">Start by creating your first activity</p>
                    <a href="activity-form.php" class="inline-block bg-admin text-white px-6 py-3 rounded-lg hover:bg-admin-dark transition">
                        <i class="fas fa-plus mr-2"></i> Create Activity
                    </a>
                </div>
            <?php else: ?>
                <div class="overflow-x-auto">
                    <table class="w-full">
                        <thead class="bg-gray-50 border-b border-gray-200">
                            <tr>
                                <th class="px-6 py-4 text-left text-xs font-semibold text-gray-600 uppercase tracking-wider">Activity</th>
                                <th class="px-6 py-4 text-left text-xs font-semibold text-gray-600 uppercase tracking-wider">Date & Time</th>
                                <th class="px-6 py-4 text-left text-xs font-semibold text-gray-600 uppercase tracking-wider">Venue</th>
                                <th class="px-6 py-4 text-left text-xs font-semibold text-gray-600 uppercase tracking-wider">Registrations</th>
                                <th class="px-6 py-4 text-left text-xs font-semibold text-gray-600 uppercase tracking-wider">Status</th>
                                <th class="px-6 py-4 text-right text-xs font-semibold text-gray-600 uppercase tracking-wider">Actions</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-gray-200">
                            <?php foreach ($activities as $activity): ?>
                                <?php
                                $isPast = strtotime($activity['activity_date']) < time();
                                $isToday = date('Y-m-d') === $activity['activity_date'];
                                ?>
                                <tr class="hover:bg-gray-50 transition">
                                    <td class="px-6 py-4">
                                        <div>
                                            <h4 class="font-semibold text-gray-900">
                                                <?php echo htmlspecialchars($activity['title']); ?>
                                            </h4>
                                            <p class="text-sm text-gray-600">
                                                <?php echo htmlspecialchars(substr($activity['description'], 0, 60)); ?>...
                                            </p>
                                        </div>
                                    </td>
                                    <td class="px-6 py-4">
                                        <div class="text-sm">
                                            <p class="font-semibold text-gray-900">
                                                <i class="fas fa-calendar mr-1 text-admin"></i>
                                                <?php echo formatDate($activity['activity_date']); ?>
                                            </p>
                                            <p class="text-gray-600">
                                                <i class="fas fa-clock mr-1 text-admin"></i>
                                                <?php echo formatTime($activity['start_time']); ?> - 
                                                <?php echo formatTime($activity['end_time']); ?>
                                            </p>
                                        </div>
                                    </td>
                                    <td class="px-6 py-4">
                                        <p class="text-sm text-gray-900">
                                            <i class="fas fa-map-marker-alt mr-1 text-admin"></i>
                                            <?php echo htmlspecialchars($activity['venue']); ?>
                                        </p>
                                    </td>
                                    <td class="px-6 py-4">
                                        <div class="text-sm">
                                            <p class="font-semibold text-gray-900">
                                                <?php echo $activity['approved_count']; ?> / <?php echo $activity['target_participants']; ?>
                                            </p>
                                            <p class="text-gray-600">
                                                <?php echo $activity['registration_count']; ?> total
                                            </p>
                                        </div>
                                    </td>
                                    <td class="px-6 py-4">
                                        <?php if ($isToday): ?>
                                            <span class="px-3 py-1 rounded-full text-xs font-semibold bg-green-100 text-green-700">
                                                <i class="fas fa-circle text-xs mr-1"></i> Today
                                            </span>
                                        <?php elseif ($isPast): ?>
                                            <span class="px-3 py-1 rounded-full text-xs font-semibold bg-gray-100 text-gray-700">
                                                <i class="fas fa-check-circle mr-1"></i> Completed
                                            </span>
                                        <?php else: ?>
                                            <span class="px-3 py-1 rounded-full text-xs font-semibold bg-blue-100 text-blue-700">
                                                <i class="fas fa-clock mr-1"></i> Upcoming
                                            </span>
                                        <?php endif; ?>
                                    </td>
                                    <td class="px-6 py-4 text-right">
                                        <div class="flex items-center justify-end space-x-2">
                                            <a href="activity-details.php?id=<?php echo $activity['activity_id']; ?>" 
                                               class="text-blue-600 hover:text-blue-800 transition"
                                               title="View Details">
                                                <i class="fas fa-eye"></i>
                                            </a>
                                            <a href="activity-form.php?id=<?php echo $activity['activity_id']; ?>" 
                                               class="text-green-600 hover:text-green-800 transition"
                                               title="Edit">
                                                <i class="fas fa-edit"></i>
                                            </a>
                                            <button onclick="confirmDelete(<?php echo $activity['activity_id']; ?>, '<?php echo htmlspecialchars($activity['title']); ?>')"
                                                    class="text-red-600 hover:text-red-800 transition"
                                                    title="Delete">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                        </div>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<!-- Delete Confirmation Form -->
<form id="deleteForm" method="POST" style="display: none;">
    <input type="hidden" name="action" value="delete">
    <input type="hidden" name="activity_id" id="deleteActivityId">
</form>

<?php
$additionalJS = "
<script>
function confirmDelete(activityId, activityTitle) {
    if (confirm('Are you sure you want to delete \"' + activityTitle + '\"?\\n\\nThis action cannot be undone.')) {
        document.getElementById('deleteActivityId').value = activityId;
        document.getElementById('deleteForm').submit();
    }
}
</script>
";

include '../includes/footer.php';
?>

