<?php
require_once '../config/config.php';
requireRole('secretariat');

$pageTitle = 'Activity Details - Secretariat - PSAU GAD';
$db = getDB();

// Get activity ID
$activityId = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if (!$activityId) {
    $_SESSION['error'] = 'Invalid activity ID.';
    header('Location: activities.php');
    exit;
}

// Get activity details
$stmt = $db->prepare("SELECT * FROM activities WHERE activity_id = ?");
$stmt->execute([$activityId]);
$activity = $stmt->fetch();

if (!$activity) {
    $_SESSION['error'] = 'Activity not found.';
    header('Location: activities.php');
    exit;
}

// Get statistics
$stmt = $db->prepare("
    SELECT 
        COUNT(DISTINCT ar.registration_id) as total_registrations,
        COUNT(DISTINCT CASE WHEN ar.status = 'approved' THEN ar.registration_id END) as approved_count,
        COUNT(DISTINCT CASE WHEN ar.status = 'pending' THEN ar.registration_id END) as pending_count,
        COUNT(DISTINCT CASE WHEN ar.status = 'rejected' THEN ar.registration_id END) as rejected_count,
        COUNT(DISTINCT aa.attendance_id) as total_attendance,
        COUNT(DISTINCT CASE WHEN aa.status = 'present' THEN aa.attendance_id END) as present_count,
        COUNT(DISTINCT CASE WHEN aa.status = 'late' THEN aa.attendance_id END) as late_count,
        COUNT(DISTINCT c.certificate_id) as certificates_issued
    FROM activity_registrations ar
    LEFT JOIN activity_attendance aa ON ar.registration_id = aa.registration_id
    LEFT JOIN certificates c ON ar.activity_id = c.activity_id AND ar.user_id = c.user_id
    WHERE ar.activity_id = ?
");
$stmt->execute([$activityId]);
$stats = $stmt->fetch();

// Get participants list
$stmt = $db->prepare("
    SELECT 
        ar.*,
        u.email,
        ep.first_name,
        ep.last_name,
        ep.gender,
        ep.category,
        ep.contact_number,
        aa.status as attendance_status,
        aa.check_in_time,
        aa.attendance_type,
        c.certificate_id,
        c.certificate_number
    FROM activity_registrations ar
    JOIN users u ON ar.user_id = u.user_id
    JOIN employee_profiles ep ON u.user_id = ep.user_id
    LEFT JOIN activity_attendance aa ON ar.registration_id = aa.registration_id
    LEFT JOIN certificates c ON ar.activity_id = c.activity_id AND ar.user_id = c.user_id
    WHERE ar.activity_id = ?
    ORDER BY ar.registration_date DESC
");
$stmt->execute([$activityId]);
$participants = $stmt->fetchAll();

// Calculate attendance rate
$attendanceRate = $stats['approved_count'] > 0 ? round(($stats['total_attendance'] / $stats['approved_count']) * 100) : 0;

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">
        <!-- Header -->
        <div class="mb-8">
            <div class="flex items-center justify-between">
                <div>
                    <h1 class="text-3xl font-bold text-gray-900 mb-2">
                        <i class="fas fa-calendar-alt text-secretariat mr-2"></i>Activity Details
                    </h1>
                    <p class="text-gray-600">View activity information and participants</p>
                </div>
                <div class="flex gap-3">
                    <a href="activity-form.php?id=<?php echo $activityId; ?>" class="bg-yellow-500 text-white px-6 py-3 rounded-lg hover:bg-yellow-600 transition font-semibold">
                        <i class="fas fa-edit mr-2"></i>Edit Activity
                    </a>
                    <a href="activities.php" class="bg-gray-500 text-white px-6 py-3 rounded-lg hover:bg-gray-600 transition font-semibold">
                        <i class="fas fa-arrow-left mr-2"></i>Back
                    </a>
                </div>
            </div>
        </div>

        <!-- Activity Information -->
        <div class="bg-white rounded-xl shadow-lg p-8 mb-8">
            <h2 class="text-2xl font-bold text-gray-900 mb-6">
                <i class="fas fa-info-circle text-secretariat mr-2"></i><?php echo htmlspecialchars($activity['title']); ?>
            </h2>
            
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                <div>
                    <p class="text-sm text-gray-500 mb-1">Category</p>
                    <p class="font-semibold text-gray-900">
                        <span class="inline-block px-3 py-1 rounded-full text-sm bg-secretariat bg-opacity-10 text-secretariat">
                            <?php echo htmlspecialchars($activity['category']); ?>
                        </span>
                    </p>
                </div>
                <div>
                    <p class="text-sm text-gray-500 mb-1">Date</p>
                    <p class="font-semibold text-gray-900">
                        <i class="fas fa-calendar mr-2 text-secretariat"></i><?php echo formatDate($activity['activity_date']); ?>
                    </p>
                </div>
                <div>
                    <p class="text-sm text-gray-500 mb-1">Time</p>
                    <p class="font-semibold text-gray-900">
                        <i class="fas fa-clock mr-2 text-secretariat"></i><?php echo formatTime($activity['start_time']) . ' - ' . formatTime($activity['end_time']); ?>
                    </p>
                </div>
                <div>
                    <p class="text-sm text-gray-500 mb-1">Venue</p>
                    <p class="font-semibold text-gray-900">
                        <i class="fas fa-map-marker-alt mr-2 text-secretariat"></i><?php echo htmlspecialchars($activity['venue']); ?>
                    </p>
                </div>
                <div>
                    <p class="text-sm text-gray-500 mb-1">Target Participants</p>
                    <p class="font-semibold text-gray-900">
                        <i class="fas fa-users mr-2 text-secretariat"></i><?php echo $activity['target_participants']; ?> participants
                    </p>
                </div>
                <div>
                    <p class="text-sm text-gray-500 mb-1">Budget</p>
                    <p class="font-semibold text-gray-900">
                        <i class="fas fa-peso-sign mr-2 text-secretariat"></i><?php echo number_format($activity['budget'], 2); ?>
                    </p>
                </div>
                <div>
                    <p class="text-sm text-gray-500 mb-1">Quarter</p>
                    <p class="font-semibold text-gray-900">Q<?php echo $activity['quarter']; ?> <?php echo $activity['year']; ?></p>
                </div>
                <div>
                    <p class="text-sm text-gray-500 mb-1">Status</p>
                    <p class="font-semibold">
                        <?php if ($activity['is_active']): ?>
                            <span class="text-green-600"><i class="fas fa-check-circle mr-1"></i>Active</span>
                        <?php else: ?>
                            <span class="text-red-600"><i class="fas fa-times-circle mr-1"></i>Inactive</span>
                        <?php endif; ?>
                    </p>
                </div>
            </div>

            <?php if ($activity['description']): ?>
                <div class="mt-6 pt-6 border-t border-gray-200">
                    <p class="text-sm text-gray-500 mb-2">Description</p>
                    <p class="text-gray-700"><?php echo nl2br(htmlspecialchars($activity['description'])); ?></p>
                </div>
            <?php endif; ?>
        </div>

        <!-- Statistics -->
        <div class="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-8 gap-4 mb-8">
            <div class="bg-white rounded-xl shadow-lg p-4 text-center border-l-4 border-blue-500">
                <p class="text-3xl font-bold text-blue-600"><?php echo $stats['total_registrations']; ?></p>
                <p class="text-xs text-gray-600 mt-1">Total Registrations</p>
            </div>
            <div class="bg-white rounded-xl shadow-lg p-4 text-center border-l-4 border-green-500">
                <p class="text-3xl font-bold text-green-600"><?php echo $stats['approved_count']; ?></p>
                <p class="text-xs text-gray-600 mt-1">Approved</p>
            </div>
            <div class="bg-white rounded-xl shadow-lg p-4 text-center border-l-4 border-yellow-500">
                <p class="text-3xl font-bold text-yellow-600"><?php echo $stats['pending_count']; ?></p>
                <p class="text-xs text-gray-600 mt-1">Pending</p>
            </div>
            <div class="bg-white rounded-xl shadow-lg p-4 text-center border-l-4 border-red-500">
                <p class="text-3xl font-bold text-red-600"><?php echo $stats['rejected_count']; ?></p>
                <p class="text-xs text-gray-600 mt-1">Rejected</p>
            </div>
            <div class="bg-white rounded-xl shadow-lg p-4 text-center border-l-4 border-emerald-500">
                <p class="text-3xl font-bold text-emerald-600"><?php echo $stats['present_count']; ?></p>
                <p class="text-xs text-gray-600 mt-1">Present</p>
            </div>
            <div class="bg-white rounded-xl shadow-lg p-4 text-center border-l-4 border-orange-500">
                <p class="text-3xl font-bold text-orange-600"><?php echo $stats['late_count']; ?></p>
                <p class="text-xs text-gray-600 mt-1">Late</p>
            </div>
            <div class="bg-white rounded-xl shadow-lg p-4 text-center border-l-4 border-purple-500">
                <p class="text-3xl font-bold text-purple-600"><?php echo $attendanceRate; ?>%</p>
                <p class="text-xs text-gray-600 mt-1">Attendance Rate</p>
            </div>
            <div class="bg-white rounded-xl shadow-lg p-4 text-center border-l-4 border-pink-500">
                <p class="text-3xl font-bold text-pink-600"><?php echo $stats['certificates_issued']; ?></p>
                <p class="text-xs text-gray-600 mt-1">Certificates</p>
            </div>
        </div>

        <!-- Participants List -->
        <div class="bg-white rounded-xl shadow-lg overflow-hidden">
            <div class="p-6 bg-secretariat text-white flex items-center justify-between">
                <h2 class="text-xl font-bold">
                    <i class="fas fa-users mr-2"></i>Participants List (<?php echo count($participants); ?>)
                </h2>
                <button onclick="exportToExcel()" class="bg-white text-secretariat px-4 py-2 rounded-lg hover:bg-gray-100 transition font-semibold text-sm">
                    <i class="fas fa-file-excel mr-2"></i>Export to Excel
                </button>
            </div>

            <?php if (empty($participants)): ?>
                <div class="p-12 text-center">
                    <i class="fas fa-users text-gray-300 text-6xl mb-4"></i>
                    <h3 class="text-xl font-bold text-gray-900 mb-2">No Participants Yet</h3>
                    <p class="text-gray-600">No one has registered for this activity yet.</p>
                </div>
            <?php else: ?>
                <div class="overflow-x-auto">
                    <table class="w-full" id="participantsTable">
                        <thead class="bg-gray-50">
                            <tr>
                                <th class="px-6 py-3 text-left text-xs font-semibold text-gray-700 uppercase tracking-wider">#</th>
                                <th class="px-6 py-3 text-left text-xs font-semibold text-gray-700 uppercase tracking-wider">Name</th>
                                <th class="px-6 py-3 text-left text-xs font-semibold text-gray-700 uppercase tracking-wider">Category</th>
                                <th class="px-6 py-3 text-left text-xs font-semibold text-gray-700 uppercase tracking-wider">Gender</th>
                                <th class="px-6 py-3 text-left text-xs font-semibold text-gray-700 uppercase tracking-wider">Registration</th>
                                <th class="px-6 py-3 text-left text-xs font-semibold text-gray-700 uppercase tracking-wider">Status</th>
                                <th class="px-6 py-3 text-left text-xs font-semibold text-gray-700 uppercase tracking-wider">Attendance</th>
                                <th class="px-6 py-3 text-left text-xs font-semibold text-gray-700 uppercase tracking-wider">Certificate</th>
                            </tr>
                        </thead>
                        <tbody class="bg-white divide-y divide-gray-200">
                            <?php foreach ($participants as $index => $participant): ?>
                                <tr class="hover:bg-gray-50">
                                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900"><?php echo $index + 1; ?></td>
                                    <td class="px-6 py-4 whitespace-nowrap">
                                        <div class="font-semibold text-gray-900"><?php echo htmlspecialchars($participant['last_name'] . ', ' . $participant['first_name']); ?></div>
                                        <div class="text-xs text-gray-500"><?php echo htmlspecialchars($participant['email']); ?></div>
                                    </td>
                                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900"><?php echo htmlspecialchars($participant['category']); ?></td>
                                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900"><?php echo htmlspecialchars($participant['gender']); ?></td>
                                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500"><?php echo date('M j, Y', strtotime($participant['registration_date'])); ?></td>
                                    <td class="px-6 py-4 whitespace-nowrap">
                                        <?php if ($participant['status'] === 'approved'): ?>
                                            <span class="px-2 py-1 text-xs font-semibold rounded-full bg-green-100 text-green-800">Approved</span>
                                        <?php elseif ($participant['status'] === 'pending'): ?>
                                            <span class="px-2 py-1 text-xs font-semibold rounded-full bg-yellow-100 text-yellow-800">Pending</span>
                                        <?php else: ?>
                                            <span class="px-2 py-1 text-xs font-semibold rounded-full bg-red-100 text-red-800">Rejected</span>
                                        <?php endif; ?>
                                    </td>
                                    <td class="px-6 py-4 whitespace-nowrap">
                                        <?php if ($participant['attendance_status']): ?>
                                            <?php if ($participant['attendance_status'] === 'present'): ?>
                                                <span class="px-2 py-1 text-xs font-semibold rounded-full bg-emerald-100 text-emerald-800">
                                                    <i class="fas fa-check mr-1"></i>Present
                                                </span>
                                            <?php else: ?>
                                                <span class="px-2 py-1 text-xs font-semibold rounded-full bg-orange-100 text-orange-800">
                                                    <i class="fas fa-clock mr-1"></i>Late
                                                </span>
                                            <?php endif; ?>
                                            <div class="text-xs text-gray-500 mt-1"><?php echo date('g:i A', strtotime($participant['check_in_time'])); ?></div>
                                        <?php else: ?>
                                            <span class="text-gray-400 text-xs">Not attended</span>
                                        <?php endif; ?>
                                    </td>
                                    <td class="px-6 py-4 whitespace-nowrap">
                                        <?php if ($participant['certificate_id']): ?>
                                            <span class="px-2 py-1 text-xs font-semibold rounded-full bg-pink-100 text-pink-800">
                                                <i class="fas fa-certificate mr-1"></i>Issued
                                            </span>
                                        <?php else: ?>
                                            <span class="text-gray-400 text-xs">Not issued</span>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<script>
function exportToExcel() {
    // Simple export to Excel using table2excel or similar
    const table = document.getElementById('participantsTable');
    const html = table.outerHTML;
    const url = 'data:application/vnd.ms-excel,' + encodeURIComponent(html);
    const link = document.createElement('a');
    link.href = url;
    link.download = 'participants_<?php echo preg_replace('/[^a-z0-9]/i', '_', $activity['title']); ?>.xls';
    link.click();
}
</script>

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

