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

// Check if user is logged in and is admin
if (!isset($_SESSION['logged_in']) || $_SESSION['logged_in'] !== true || $_SESSION['role'] !== 'admin') {
    header('Location: ../auth/login.php');
    exit();
}

$title = "Manage Activities";

// Handle AJAX deletion
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['ajax_delete'])) {
    header('Content-Type: application/json');
    
    // CSRF check disabled per configuration
    
    $activity_id = intval($_POST['activity_id'] ?? 0);
    
    if ($activity_id <= 0) {
        echo json_encode(['success' => false, 'message' => 'Invalid activity ID']);
        exit();
    }
    
    // Check if activity exists
    $check_sql = "SELECT id, name, date, time_in, time_out FROM activities WHERE id = ?";
    $check_stmt = mysqli_prepare($conn, $check_sql);
    mysqli_stmt_bind_param($check_stmt, "i", $activity_id);
    mysqli_stmt_execute($check_stmt);
    $result = mysqli_stmt_get_result($check_stmt);
    $activity = mysqli_fetch_assoc($result);
    
    if (!$activity) {
        echo json_encode(['success' => false, 'message' => 'Activity not found']);
        exit();
    }
    
    // Check if activity is currently ongoing
    $today = date('Y-m-d');
    $current_time = date('H:i:s');
    
    if ($activity['date'] == $today && 
        $current_time >= $activity['time_in'] && 
        $current_time <= $activity['time_out']) {
        echo json_encode([
            'success' => false, 
            'message' => 'Cannot delete an activity that is currently ongoing. Please wait until it ends.'
        ]);
        exit();
    }
    
    // Start transaction
    mysqli_begin_transaction($conn);
    
    try {
        // Get attendance count for logging
        $attendance_count_sql = "SELECT COUNT(*) as count FROM attendance WHERE activity_id = ?";
        $attendance_stmt = mysqli_prepare($conn, $attendance_count_sql);
        mysqli_stmt_bind_param($attendance_stmt, "i", $activity_id);
        mysqli_stmt_execute($attendance_stmt);
        $attendance_result = mysqli_stmt_get_result($attendance_stmt);
        $attendance_count = mysqli_fetch_assoc($attendance_result)['count'];
        
        // First, delete attendance records
        $delete_attendance_sql = "DELETE FROM attendance WHERE activity_id = ?";
        $stmt1 = mysqli_prepare($conn, $delete_attendance_sql);
        mysqli_stmt_bind_param($stmt1, "i", $activity_id);
        $attendance_deleted = mysqli_stmt_execute($stmt1);
        
        if (!$attendance_deleted) {
            throw new Exception('Failed to delete attendance records');
        }
        
        // Then delete the activity
        $delete_activity_sql = "DELETE FROM activities WHERE id = ?";
        $stmt2 = mysqli_prepare($conn, $delete_activity_sql);
        mysqli_stmt_bind_param($stmt2, "i", $activity_id);
        $activity_deleted = mysqli_stmt_execute($stmt2);
        
        if (!$activity_deleted) {
            throw new Exception('Failed to delete activity');
        }
        
        // Commit transaction
        mysqli_commit($conn);
        
        // Log the deletion
        $log_message = "Activity deleted via AJAX: '{$activity['name']}' (ID: {$activity_id}). ";
        $log_message .= "Deleted {$attendance_count} attendance records.";
        log_action($conn, $_SESSION['user_id'], 'delete_activity', $log_message);
        
        echo json_encode([
            'success' => true, 
            'message' => 'Activity deleted successfully!',
            'deleted_id' => $activity_id,
            'attendance_count' => $attendance_count
        ]);
        
    } catch (Exception $e) {
        mysqli_rollback($conn);
        echo json_encode([
            'success' => false, 
            'message' => 'Error: ' . $e->getMessage()
        ]);
    }
    exit();
}

// Generate CSRF token for this page
$csrf_token = bin2hex(random_bytes(32));
$_SESSION['csrf_token'] = $csrf_token;

// Get all activities with related data
$activities = [];
$sql = "SELECT a.*, u.full_name as created_by_name, 
               c.code as course_code, c.name as course_name,
               d.code as department_code, d.name as department_name
        FROM activities a
        LEFT JOIN users u ON a.created_by = u.id
        LEFT JOIN courses c ON a.course_id = c.id
        LEFT JOIN departments d ON a.department_id = d.id
        ORDER BY a.date DESC, a.time_in ASC";
$result = query($conn, $sql);
while ($row = mysqli_fetch_assoc($result)) {
    $activities[] = $row;
}

// Statistics calculation
$today = date('Y-m-d');
$upcoming_count = 0;
$ongoing_count = 0;
$past_count = 0;

foreach ($activities as $activity) {
    $activity_date = $activity['date'];
    $current_time = date('H:i:s');
    $activity_start = $activity['time_in'];
    $activity_end = $activity['time_out'];
    
    if ($activity_date > $today) {
        $upcoming_count++;
    } elseif ($activity_date == $today && $current_time >= $activity_start && $current_time <= $activity_end) {
        $ongoing_count++;
    } elseif ($activity_date < $today || ($activity_date == $today && $current_time > $activity_end)) {
        $past_count++;
    }
}

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

<!-- Page Header -->
<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h1 class="h3 mb-2">Manage Activities</h1>
        <p class="text-muted">Schedule and manage activities, events, and classes.</p>
    </div>
    <div>
        <a href="add_activity.php" class="btn btn-primary">
            <i class="bi bi-calendar-plus me-2"></i> Schedule New Activity
        </a>
    </div>
</div>

<!-- Message Alert -->
<?php if (isset($_SESSION['success_message'])): ?>
    <div class="alert alert-success alert-dismissible fade show" role="alert">
        <?php echo $_SESSION['success_message']; ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
    <?php unset($_SESSION['success_message']); ?>
<?php endif; ?>

<?php if (isset($_SESSION['error_message'])): ?>
    <div class="alert alert-danger alert-dismissible fade show" role="alert">
        <?php echo $_SESSION['error_message']; ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
    <?php unset($_SESSION['error_message']); ?>
<?php endif; ?>

<div id="messageAlert" class="alert" style="display: none;"></div>

<!-- Statistics Cards -->
<div class="row mb-4">
    <div class="col-xl-3 col-md-6 mb-4">
        <div class="card stat-card border-left-primary">
            <div class="card-body">
                <div class="row align-items-center">
                    <div class="col-8">
                        <div class="text-uppercase text-primary mb-1">Total Activities</div>
                        <div class="h2 font-weight-bold" id="totalCount"><?php echo count($activities); ?></div>
                        <div class="text-muted">All scheduled</div>
                    </div>
                    <div class="col-4 text-end">
                        <i class="bi bi-calendar-check-fill text-primary" style="font-size: 3rem; opacity: 0.7;"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="col-xl-3 col-md-6 mb-4">
        <div class="card stat-card border-left-success">
            <div class="card-body">
                <div class="row align-items-center">
                    <div class="col-8">
                        <div class="text-uppercase text-success mb-1">Upcoming</div>
                        <div class="h2 font-weight-bold"><?php echo $upcoming_count; ?></div>
                        <div class="text-muted">Future activities</div>
                    </div>
                    <div class="col-4 text-end">
                        <i class="bi bi-calendar-event-fill text-success" style="font-size: 3rem; opacity: 0.7;"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="col-xl-3 col-md-6 mb-4">
        <div class="card stat-card border-left-info">
            <div class="card-body">
                <div class="row align-items-center">
                    <div class="col-8">
                        <div class="text-uppercase text-info mb-1">Ongoing</div>
                        <div class="h2 font-weight-bold"><?php echo $ongoing_count; ?></div>
                        <div class="text-muted">Happening now</div>
                    </div>
                    <div class="col-4 text-end">
                        <i class="bi bi-clock-history text-info" style="font-size: 3rem; opacity: 0.7;"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="col-xl-3 col-md-6 mb-4">
        <div class="card stat-card border-left-warning">
            <div class="card-body">
                <div class="row align-items-center">
                    <div class="col-8">
                        <div class="text-uppercase text-warning mb-1">Past Activities</div>
                        <div class="h2 font-weight-bold"><?php echo $past_count; ?></div>
                        <div class="text-muted">Completed</div>
                    </div>
                    <div class="col-4 text-end">
                        <i class="bi bi-calendar-x-fill text-warning" style="font-size: 3rem; opacity: 0.7;"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Activity Tabs -->
<div class="card shadow mb-4">
    <div class="card-header">
        <ul class="nav nav-tabs card-header-tabs" id="activityTabs" role="tablist">
            <li class="nav-item" role="presentation">
                <button class="nav-link active" id="upcoming-tab" data-bs-toggle="tab" 
                        data-bs-target="#upcoming" type="button" role="tab">
                    <i class="bi bi-calendar-event me-1"></i> Upcoming
                    <span class="badge bg-primary ms-1" id="upcomingBadge"><?php echo $upcoming_count; ?></span>
                </button>
            </li>
            <li class="nav-item" role="presentation">
                <button class="nav-link" id="ongoing-tab" data-bs-toggle="tab" 
                        data-bs-target="#ongoing" type="button" role="tab">
                    <i class="bi bi-clock-history me-1"></i> Ongoing
                    <span class="badge bg-success ms-1"><?php echo $ongoing_count; ?></span>
                </button>
            </li>
            <li class="nav-item" role="presentation">
                <button class="nav-link" id="past-tab" data-bs-toggle="tab" 
                        data-bs-target="#past" type="button" role="tab">
                    <i class="bi bi-calendar-x me-1"></i> Past
                    <span class="badge bg-secondary ms-1"><?php echo $past_count; ?></span>
                </button>
            </li>
            <li class="nav-item" role="presentation">
                <button class="nav-link" id="all-tab" data-bs-toggle="tab" 
                        data-bs-target="#all" type="button" role="tab">
                    <i class="bi bi-list-ul me-1"></i> All Activities
                    <span class="badge bg-info ms-1"><?php echo count($activities); ?></span>
                </button>
            </li>
        </ul>
    </div>
    <div class="card-body">
        <div class="tab-content" id="activityTabsContent">
            <!-- Upcoming Activities Tab -->
            <div class="tab-pane fade show active" id="upcoming" role="tabpanel">
                <div class="table-responsive">
                    <table class="table table-hover mb-0" id="upcomingTable">
                        <thead class="table-light">
                            <tr>
                                <th>Activity</th>
                                <th>Date & Time</th>
                                <th>Location</th>
                                <th>Participants</th>
                                <th>Status</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php 
                            $has_upcoming = false;
                            foreach ($activities as $activity): 
                                if ($activity['date'] > $today || ($activity['date'] == $today && date('H:i:s') < $activity['time_in'])): 
                                    $has_upcoming = true;
                            ?>
                            <tr id="activityRow-<?php echo $activity['id']; ?>">
                                <td>
                                    <strong><?php echo htmlspecialchars($activity['name']); ?></strong><br>
                                    <small class="text-muted"><?php echo htmlspecialchars($activity['description'] ? substr($activity['description'], 0, 50) . '...' : 'No description'); ?></small>
                                </td>
                                <td>
                                    <div class="fw-bold"><?php echo date('M d, Y', strtotime($activity['date'])); ?></div>
                                    <small class="text-muted">
                                        <?php echo date('h:i A', strtotime($activity['time_in'])); ?> - 
                                        <?php echo date('h:i A', strtotime($activity['time_out'])); ?>
                                    </small>
                                </td>
                                <td>
                                    <span class="badge bg-light text-dark">
                                        <i class="bi bi-geo-alt me-1"></i> <?php echo htmlspecialchars($activity['location']); ?>
                                    </span>
                                </td>
                                <td>
                                    <?php 
                                    switch($activity['required_students']) {
                                        case 'all': echo '<span class="badge bg-info">All Students</span>'; break;
                                        case 'specific_course': 
                                            echo '<span class="badge bg-warning">' . htmlspecialchars($activity['course_code'] ?? 'Specific Course') . '</span>'; 
                                            break;
                                        case 'specific_department': 
                                            echo '<span class="badge bg-primary">' . htmlspecialchars($activity['department_name'] ?? 'Specific Department') . '</span>'; 
                                            break;
                                    }
                                    ?>
                                </td>
                                <td>
                                    <?php if ($activity['status'] == 1): ?>
                                        <span class="badge bg-success">Active</span>
                                    <?php else: ?>
                                        <span class="badge bg-danger">Inactive</span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <div class="btn-group btn-group-sm">
                                        <a href="view_activity.php?id=<?php echo $activity['id']; ?>" class="btn btn-info" title="View">
                                            <i class="bi bi-eye"></i>
                                        </a>
                                        <a href="edit_activity.php?id=<?php echo $activity['id']; ?>" class="btn btn-warning" title="Edit">
                                            <i class="bi bi-pencil"></i>
                                        </a>
                                        <button type="button" class="btn btn-danger delete-activity-btn" 
                                                data-id="<?php echo $activity['id']; ?>" 
                                                data-name="<?php echo htmlspecialchars($activity['name']); ?>" 
                                                title="Delete">
                                            <i class="bi bi-trash"></i>
                                        </button>
                                    </div>
                                </td>
                            </tr>
                            <?php endif; endforeach; ?>
                            
                            <?php if (!$has_upcoming): ?>
                                <tr id="noUpcomingRow">
                                    <td colspan="6" class="text-center py-4">
                                        <i class="bi bi-calendar-x text-muted" style="font-size: 3rem;"></i>
                                        <p class="mt-2">No upcoming activities scheduled</p>
                                    </td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
            
            <!-- Ongoing Activities Tab -->
            <div class="tab-pane fade" id="ongoing" role="tabpanel">
                <div class="table-responsive">
                    <table class="table table-hover mb-0" id="ongoingTable">
                        <thead class="table-light">
                            <tr>
                                <th>Activity</th>
                                <th>Time</th>
                                <th>Location</th>
                                <th>Duration</th>
                                <th>Participants</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php 
                            $has_ongoing = false;
                            foreach ($activities as $activity): 
                                $current_time = date('H:i:s');
                                if ($activity['date'] == $today && 
                                    $current_time >= $activity['time_in'] && 
                                    $current_time <= $activity['time_out']): 
                                    $has_ongoing = true;
                                    
                                    // Calculate time remaining
                                    $end_time = strtotime($activity['time_out']);
                                    $remaining = $end_time - time();
                                    $hours = floor($remaining / 3600);
                                    $minutes = floor(($remaining % 3600) / 60);
                            ?>
                            <tr id="activityRow-<?php echo $activity['id']; ?>">
                                <td>
                                    <strong><?php echo htmlspecialchars($activity['name']); ?></strong><br>
                                    <small class="text-muted"><?php echo htmlspecialchars($activity['description'] ? substr($activity['description'], 0, 50) . '...' : 'No description'); ?></small>
                                </td>
                                <td>
                                    <div class="fw-bold"><?php echo date('h:i A', strtotime($activity['time_in'])); ?> - <?php echo date('h:i A', strtotime($activity['time_out'])); ?></div>
                                    <small class="text-muted">Ends in <?php echo $hours . 'h ' . $minutes . 'm'; ?></small>
                                </td>
                                <td>
                                    <span class="badge bg-light text-dark">
                                        <i class="bi bi-geo-alt me-1"></i> <?php echo htmlspecialchars($activity['location']); ?>
                                    </span>
                                </td>
                                <td>
                                    <?php 
                                    $start = strtotime($activity['time_in']);
                                    $end = strtotime($activity['time_out']);
                                    $duration = round(($end - $start) / 3600, 1);
                                    echo '<span class="badge bg-info">' . $duration . ' hours</span>';
                                    ?>
                                </td>
                                <td>
                                    <?php 
                                    switch($activity['required_students']) {
                                        case 'all': echo '<span class="badge bg-info">All Students</span>'; break;
                                        case 'specific_course': 
                                            echo '<span class="badge bg-warning">' . htmlspecialchars($activity['course_code'] ?? 'Specific Course') . '</span>'; 
                                            break;
                                        case 'specific_department': 
                                            echo '<span class="badge bg-primary">' . htmlspecialchars($activity['department_name'] ?? 'Specific Department') . '</span>'; 
                                            break;
                                    }
                                    ?>
                                </td>
                                <td>
                                    <div class="btn-group btn-group-sm">
                                        <a href="view_activity.php?id=<?php echo $activity['id']; ?>" class="btn btn-info" title="View">
                                            <i class="bi bi-eye"></i>
                                        </a>
                                        <a href="../admin/attendance.php" class="btn btn-success" title="Take Attendance">
                                            <i class="bi bi-qr-code-scan"></i>
                                        </a>
                                        <a href="reports.php?activity_id=<?php echo $activity['id']; ?>" class="btn btn-primary" title="View Report">
                                            <i class="bi bi-file-earmark-text"></i>
                                        </a>
                                    </div>
                                </td>
                            </tr>
                            <?php endif; endforeach; ?>
                            
                            <?php if (!$has_ongoing): ?>
                                <tr id="noOngoingRow">
                                    <td colspan="6" class="text-center py-4">
                                        <i class="bi bi-clock text-muted" style="font-size: 3rem;"></i>
                                        <p class="mt-2">No ongoing activities at the moment</p>
                                    </td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
            
            <!-- Past Activities Tab -->
            <div class="tab-pane fade" id="past" role="tabpanel">
                <div class="table-responsive">
                    <table class="table table-hover mb-0" id="pastTable">
                        <thead class="table-light">
                            <tr>
                                <th>Activity</th>
                                <th>Date</th>
                                <th>Time</th>
                                <th>Location</th>
                                <th>Attendance</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php 
                            $has_past = false;
                            foreach ($activities as $activity): 
                                if ($activity['date'] < $today || ($activity['date'] == $today && date('H:i:s') > $activity['time_out'])): 
                                    $has_past = true;
                                    
                                    // Get attendance count for this activity
                                    $attendance_sql = "SELECT COUNT(*) as count FROM attendance WHERE activity_id = " . $activity['id'];
                                    $attendance_result = query($conn, $attendance_sql);
                                    $attendance_count = mysqli_fetch_assoc($attendance_result)['count'];
                            ?>
                            <tr id="activityRow-<?php echo $activity['id']; ?>">
                                <td>
                                    <strong><?php echo htmlspecialchars($activity['name']); ?></strong><br>
                                    <small class="text-muted"><?php echo htmlspecialchars($activity['description'] ? substr($activity['description'], 0, 50) . '...' : 'No description'); ?></small>
                                </td>
                                <td>
                                    <div class="fw-bold"><?php echo date('M d, Y', strtotime($activity['date'])); ?></div>
                                    <small class="text-muted"><?php echo date('l', strtotime($activity['date'])); ?></small>
                                </td>
                                <td>
                                    <small class="text-muted">
                                        <?php echo date('h:i A', strtotime($activity['time_in'])); ?> - 
                                        <?php echo date('h:i A', strtotime($activity['time_out'])); ?>
                                    </small>
                                </td>
                                <td>
                                    <span class="badge bg-light text-dark">
                                        <i class="bi bi-geo-alt me-1"></i> <?php echo htmlspecialchars($activity['location']); ?>
                                    </span>
                                </td>
                                <td>
                                    <span class="badge bg-<?php echo $attendance_count > 0 ? 'success' : 'secondary'; ?>">
                                        <?php echo $attendance_count; ?> attended
                                    </span>
                                </td>
                                <td>
                                    <div class="btn-group btn-group-sm">
                                        <a href="view_activity.php?id=<?php echo $activity['id']; ?>" class="btn btn-info" title="View">
                                            <i class="bi bi-eye"></i>
                                        </a>
                                        <a href="reports.php?activity_id=<?php echo $activity['id']; ?>" class="btn btn-primary" title="View Report">
                                            <i class="bi bi-file-earmark-text"></i>
                                        </a>
                                        <a href="edit_activity.php?id=<?php echo $activity['id']; ?>" class="btn btn-warning" title="Edit">
                                            <i class="bi bi-pencil"></i>
                                        </a>
                                    </div>
                                </td>
                            </tr>
                            <?php endif; endforeach; ?>
                            
                            <?php if (!$has_past): ?>
                                <tr id="noPastRow">
                                    <td colspan="6" class="text-center py-4">
                                        <i class="bi bi-calendar-check text-muted" style="font-size: 3rem;"></i>
                                        <p class="mt-2">No past activities found</p>
                                    </td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
            
            <!-- All Activities Tab -->
            <div class="tab-pane fade" id="all" role="tabpanel">
                <div class="table-responsive">
                    <table class="table table-hover mb-0" id="allTable">
                        <thead class="table-light">
                            <tr>
                                <th>Activity</th>
                                <th>Date & Time</th>
                                <th>Location</th>
                                <th>Participants</th>
                                <th>Created By</th>
                                <th>Status</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody id="allActivitiesBody">
                            <?php if (empty($activities)): ?>
                                <tr id="noActivitiesRow">
                                    <td colspan="7" class="text-center py-4">
                                        <i class="bi bi-calendar-x text-muted" style="font-size: 3rem;"></i>
                                        <p class="mt-2">No activities found. Schedule your first activity!</p>
                                    </td>
                                </tr>
                            <?php else: ?>
                                <?php foreach ($activities as $activity): ?>
                                <tr id="activityRow-<?php echo $activity['id']; ?>">
                                    <td>
                                        <strong><?php echo htmlspecialchars($activity['name']); ?></strong><br>
                                        <small class="text-muted"><?php echo htmlspecialchars($activity['description'] ? substr($activity['description'], 0, 50) . '...' : 'No description'); ?></small>
                                    </td>
                                    <td>
                                        <div class="fw-bold"><?php echo date('M d, Y', strtotime($activity['date'])); ?></div>
                                        <small class="text-muted">
                                            <?php echo date('h:i A', strtotime($activity['time_in'])); ?> - 
                                            <?php echo date('h:i A', strtotime($activity['time_out'])); ?>
                                        </small>
                                    </td>
                                    <td>
                                        <span class="badge bg-light text-dark">
                                            <i class="bi bi-geo-alt me-1"></i> <?php echo htmlspecialchars($activity['location']); ?>
                                        </span>
                                    </td>
                                    <td>
                                        <?php 
                                        switch($activity['required_students']) {
                                            case 'all': echo '<span class="badge bg-info">All Students</span>'; break;
                                            case 'specific_course': 
                                                echo '<span class="badge bg-warning">' . htmlspecialchars($activity['course_code'] ?? 'Specific Course') . '</span>'; 
                                                break;
                                            case 'specific_department': 
                                                echo '<span class="badge bg-primary">' . htmlspecialchars($activity['department_name'] ?? 'Specific Department') . '</span>'; 
                                                break;
                                        }
                                        ?>
                                    </td>
                                    <td>
                                        <small><?php echo htmlspecialchars($activity['created_by_name']); ?></small><br>
                                        <small class="text-muted"><?php echo date('M d, Y', strtotime($activity['created_at'])); ?></small>
                                    </td>
                                    <td>
                                        <?php if ($activity['status'] == 1): ?>
                                            <span class="badge bg-success">Active</span>
                                        <?php else: ?>
                                            <span class="badge bg-danger">Inactive</span>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <div class="btn-group btn-group-sm">
                                            <a href="view_activity.php?id=<?php echo $activity['id']; ?>" class="btn btn-info" title="View">
                                                <i class="bi bi-eye"></i>
                                            </a>
                                            <a href="edit_activity.php?id=<?php echo $activity['id']; ?>" class="btn btn-warning" title="Edit">
                                                <i class="bi bi-pencil"></i>
                                            </a>
                                            <button type="button" class="btn btn-danger delete-activity-btn" 
                                                    data-id="<?php echo $activity['id']; ?>" 
                                                    data-name="<?php echo htmlspecialchars($activity['name']); ?>" 
                                                    title="Delete">
                                                <i class="bi bi-trash"></i>
                                            </button>
                                        </div>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
    <div class="card-footer">
        <div class="row">
            <div class="col-md-6">
                <small class="text-muted">
                    Showing <span id="activitiesCount"><?php echo count($activities); ?></span> activity(s)
                </small>
            </div>
            <div class="col-md-6 text-md-end">
                <small class="text-muted">
                    Today: <?php echo date('F j, Y'); ?>
                </small>
            </div>
        </div>
    </div>
</div>

<!-- Delete Confirmation Modal -->
<div class="modal fade" id="deleteModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Confirm Delete</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <p>Are you sure you want to delete activity "<span id="deleteActivityName"></span>"?</p>
                <p class="text-danger"><small>This will also delete all attendance records for this activity.</small></p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-danger" id="confirmDeleteBtn">Delete</button>
            </div>
        </div>
    </div>
</div>

<?php 
$page_scripts = '
<script>
$(document).ready(function() {
    let currentActivityId = null;
    
    // Initialize DataTables
    const upcomingTable = $("#upcomingTable").DataTable({
        pageLength: 10,
        lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
        order: [[1, "asc"]],
        responsive: true,
        columnDefs: [
            { orderable: false, targets: [5] }
        ]
    });
    
    const ongoingTable = $("#ongoingTable").DataTable({
        pageLength: 10,
        lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
        order: [[1, "asc"]],
        responsive: true,
        columnDefs: [
            { orderable: false, targets: [5] }
        ]
    });
    
    const pastTable = $("#pastTable").DataTable({
        pageLength: 10,
        lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
        order: [[1, "desc"]],
        responsive: true,
        columnDefs: [
            { orderable: false, targets: [5] }
        ]
    });
    
    const allTable = $("#allTable").DataTable({
        pageLength: 10,
        lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
        order: [[1, "desc"]],
        responsive: true,
        columnDefs: [
            { orderable: false, targets: [6] }
        ]
    });
    
    // Delete button click
    $(document).on("click", ".delete-activity-btn", function() {
        currentActivityId = $(this).data("id");
        const activityName = $(this).data("name");
        
        $("#deleteActivityName").text(activityName);
        $("#deleteModal").modal("show");
    });
    
    // Confirm delete
    $("#confirmDeleteBtn").click(function() {
        if (!currentActivityId) return;
        
        const $btn = $(this);
        const originalText = $btn.html();
        $btn.html(\'<i class="bi bi-hourglass-split"></i> Deleting...\').prop("disabled", true);
        
        $.ajax({
            url: "manage_activities.php",
            method: "POST",
            data: {
                ajax_delete: true,
                activity_id: currentActivityId,
                csrf_token: "' . $csrf_token . '"
            },
            dataType: "json",
            success: function(response) {
                $btn.html(originalText).prop("disabled", false);
                $("#deleteModal").modal("hide");
                
                if (response.success) {
                    // Remove row from all tables
                    $("#activityRow-" + currentActivityId).fadeOut(300, function() {
                        $(this).remove();
                        
                        // Update counters
                        updateCounters();
                        
                        // Show success message
                        showMessage(response.message, "success");
                    });
                } else {
                    showMessage(response.message, "danger");
                }
            },
            error: function(xhr, status, error) {
                $btn.html(originalText).prop("disabled", false);
                showMessage("Error deleting activity. Please try again.", "danger");
                console.error("Delete error:", error);
            }
        });
    });
    
    function updateCounters() {
        // Get current counts
        const totalRows = $("#allActivitiesBody tr:not(#noActivitiesRow)").length;
        const upcomingRows = $("#upcomingTable tbody tr:not(#noUpcomingRow)").length;
        const ongoingRows = $("#ongoingTable tbody tr:not(#noOngoingRow)").length;
        const pastRows = $("#pastTable tbody tr:not(#noPastRow)").length;
        
        // Update counters
        $("#activitiesCount").text(totalRows);
        $("#totalCount").text(totalRows);
        $("#upcomingBadge").text(upcomingRows);
        
        // Update badges
        $("#upcoming-tab .badge").text(upcomingRows);
        $("#ongoing-tab .badge").text(ongoingRows);
        $("#past-tab .badge").text(pastRows);
        $("#all-tab .badge").text(totalRows);
        
        // Show/hide empty messages
        if (upcomingRows === 0 && $("#noUpcomingRow").length === 0) {
            $("#upcomingTable tbody").append(\'<tr id="noUpcomingRow"><td colspan="6" class="text-center py-4"><i class="bi bi-calendar-x text-muted" style="font-size: 3rem;"></i><p class="mt-2">No upcoming activities scheduled</p></td></tr>\');
        }
        
        if (ongoingRows === 0 && $("#noOngoingRow").length === 0) {
            $("#ongoingTable tbody").append(\'<tr id="noOngoingRow"><td colspan="6" class="text-center py-4"><i class="bi bi-clock text-muted" style="font-size: 3rem;"></i><p class="mt-2">No ongoing activities at the moment</p></td></tr>\');
        }
        
        if (pastRows === 0 && $("#noPastRow").length === 0) {
            $("#pastTable tbody").append(\'<tr id="noPastRow"><td colspan="6" class="text-center py-4"><i class="bi bi-calendar-check text-muted" style="font-size: 3rem;"></i><p class="mt-2">No past activities found</p></td></tr>\');
        }
        
        if (totalRows === 0 && $("#noActivitiesRow").length === 0) {
            $("#allActivitiesBody").append(\'<tr id="noActivitiesRow"><td colspan="7" class="text-center py-4"><i class="bi bi-calendar-x text-muted" style="font-size: 3rem;"></i><p class="mt-2">No activities found. Schedule your first activity!</p></td></tr>\');
        }
    }
    
    function showMessage(message, type) {
        const $alert = $("#messageAlert");
        $alert.removeClass("alert-success alert-danger alert-warning alert-info")
              .addClass("alert-" + type)
              .html(\'<i class="bi me-2"></i>\' + message + \'<button type="button" class="btn-close" data-bs-dismiss="alert"></button>\')
              .find("i").addClass(type === "success" ? "bi-check-circle" : "bi-exclamation-circle").end()
              .show();
        
        // Auto-hide after 5 seconds
        setTimeout(() => {
            $alert.fadeOut();
        }, 5000);
    }
    
    // Auto-refresh ongoing tab
    setInterval(function() {
        const activeTab = document.querySelector("#activityTabs .nav-link.active");
        if (activeTab && activeTab.id === "ongoing-tab") {
            location.reload();
        }
    }, 60000);
    
    // Initialize counters
    updateCounters();
});
</script>
';

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