<?php
require __DIR__ . '/../includes/bootstrap.php';
require_login();

$pdo = db();
$errors = [];

$courses = $pdo->query('SELECT id, name FROM courses WHERE status = 1 ORDER BY name')->fetchAll();
$departments = $pdo->query('SELECT id, name FROM departments WHERE status = 1 ORDER BY name')->fetchAll();

if (is_post()) {
    if (!validate_csrf_token($_POST['csrf_token'] ?? null)) {
        $errors[] = 'Invalid session token.';
    } else {
        $action = $_POST['action'] ?? 'create';

        if ($action === 'delete') {
            $id = (int) ($_POST['id'] ?? 0);
            $pdo->prepare('DELETE FROM activities WHERE id = :id')->execute(['id' => $id]);
            add_flash('success', 'Activity removed.');
            redirect('admin/activities.php');
        }

        $payload = [
            'name' => trim($_POST['name'] ?? ''),
            'date' => $_POST['date'] ?? null,
            'time_in' => $_POST['time_in'] ?? null,
            'time_out' => $_POST['time_out'] ?? null,
            'location' => trim($_POST['location'] ?? ''),
            'required_students' => $_POST['required_students'] ?? 'all',
            'course_id' => $_POST['required_students'] === 'specific_course' ? (int) ($_POST['course_id'] ?? 0) : null,
            'department_id' => $_POST['required_students'] === 'specific_department' ? (int) ($_POST['department_id'] ?? 0) : null,
            'description' => trim($_POST['description'] ?? ''),
            'status' => (int) ($_POST['status'] ?? 1),
            'created_by' => current_user()['id'],
        ];

        if ($payload['name'] === '' || !$payload['date']) {
            $errors[] = 'Activity name and date are required.';
        }

        if (!$errors) {
            if ($action === 'update') {
                $updatePayload = $payload;
                $updatePayload['id'] = (int) ($_POST['id'] ?? 0);
                unset($updatePayload['created_by']);
                $stmt = $pdo->prepare(
                    'UPDATE activities SET name = :name, date = :date, time_in = :time_in, time_out = :time_out,
                        location = :location, required_students = :required_students, course_id = :course_id,
                        department_id = :department_id, description = :description, status = :status
                     WHERE id = :id'
                );
                $stmt->execute($updatePayload);
                add_flash('success', 'Activity updated.');
            } else {
                $stmt = $pdo->prepare(
                    'INSERT INTO activities (name, date, time_in, time_out, location, required_students,
                        course_id, department_id, description, status, created_by)
                     VALUES (:name, :date, :time_in, :time_out, :location, :required_students,
                        :course_id, :department_id, :description, :status, :created_by)'
                );
                $stmt->execute($payload);
                add_flash('success', 'Activity scheduled.');
            }

            redirect('admin/activities.php');
        }
    }
}

$activities = $pdo->query(
    'SELECT a.*, c.name AS course_name, d.name AS department_name, u.full_name AS creator
     FROM activities a
     LEFT JOIN courses c ON a.course_id = c.id
     LEFT JOIN departments d ON a.department_id = d.id
     LEFT JOIN users u ON a.created_by = u.id
     ORDER BY a.date DESC, a.time_in DESC'
)->fetchAll();

render_header('Activities', ['active' => 'activities']);
?>
<div class="card shadow-sm">
    <div class="card-header bg-white d-flex justify-content-between align-items-center">
        <div>
            <h5 class="mb-0">Activities</h5>
            <small class="text-muted"><?= count($activities) ?> scheduled</small>
        </div>
        <div class="d-flex gap-2 align-items-center">
            <?php if ($errors): ?>
                <span class="text-danger small"><?= sanitize(implode(' ', $errors)) ?></span>
            <?php endif; ?>
            <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#activityModal" data-mode="create">
                Schedule Activity
            </button>
        </div>
    </div>
    <div class="card-body">
        <?php if (!$activities): ?>
            <p class="text-muted mb-0 text-center">No activities scheduled.</p>
        <?php else: ?>
            <div class="table-responsive">
                <table class="table align-middle">
                    <thead>
                    <tr>
                        <th>Name</th>
                        <th>Date</th>
                        <th>Audience</th>
                        <th>Location</th>
                        <th>Status</th>
                        <th class="text-end">Actions</th>
                    </tr>
                    </thead>
                    <tbody>
                    <?php foreach ($activities as $activity): ?>
                        <?php
                        $recordPayload = encode_record([
                            'id' => (int) $activity['id'],
                            'name' => $activity['name'],
                            'date' => $activity['date'],
                            'time_in' => $activity['time_in'],
                            'time_out' => $activity['time_out'],
                            'location' => $activity['location'],
                            'required_students' => $activity['required_students'],
                            'course_id' => $activity['course_id'],
                            'department_id' => $activity['department_id'],
                            'description' => $activity['description'],
                            'status' => (int) $activity['status'],
                        ]);
                        $timeIn = $activity['time_in'] !== null ? substr($activity['time_in'], 0, 5) : '—';
                        $timeOut = $activity['time_out'] !== null ? substr($activity['time_out'], 0, 5) : '—';
                        ?>
                        <tr>
                            <td>
                                <strong><?= sanitize($activity['name']) ?></strong><br>
                                <span class="text-muted-sm">Created by <?= sanitize($activity['creator'] ?? 'N/A') ?></span>
                            </td>
                            <td>
                                <?= format_date($activity['date']) ?><br>
                                <span class="text-muted-sm"><?= sanitize($timeIn) ?> — <?= sanitize($timeOut) ?></span>
                            </td>
                            <td>
                                <?php
                                $audience = match ($activity['required_students']) {
                                    'specific_course' => $activity['course_name'] ?? 'Course',
                                    'specific_department' => $activity['department_name'] ?? 'Department',
                                    default => 'All Students',
                                };
                                ?>
                                <?= sanitize($audience) ?>
                            </td>
                            <td><?= sanitize($activity['location']) ?></td>
                            <td>
                                <span class="badge <?= $activity['status'] ? 'bg-success-subtle text-success' : 'bg-secondary' ?>">
                                    <?= $activity['status'] ? 'Active' : 'Inactive' ?>
                                </span>
                            </td>
                            <td class="text-end">
                                <button class="btn btn-sm btn-outline-primary"
                                        data-bs-toggle="modal"
                                        data-bs-target="#activityModal"
                                        data-mode="edit"
                                        data-record="<?= sanitize($recordPayload) ?>">
                                    Edit
                                </button>
                                <button class="btn btn-sm btn-outline-danger"
                                        data-bs-toggle="modal"
                                        data-bs-target="#deleteActivityModal"
                                        data-record-name="<?= sanitize($activity['name']) ?>"
                                        data-record-ref="<?= sanitize(format_date($activity['date'])) ?>"
                                        data-id="<?= (int) $activity['id'] ?>">
                                    Delete
                                </button>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php endif; ?>
    </div>
</div>

<!-- Activity modal -->
<div class="modal fade" id="activityModal" tabindex="-1" aria-hidden="true"
     data-create-title="Schedule Activity" data-edit-title="Edit Activity"
     data-create-submit="Schedule Activity" data-edit-submit="Save Changes">
    <div class="modal-dialog modal-lg modal-dialog-scrollable">
        <div class="modal-content">
            <form method="post" class="needs-validation" novalidate>
                <div class="modal-header">
                    <h5 class="modal-title" data-modal-title>Schedule Activity</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <input type="hidden" name="csrf_token" value="<?= sanitize(ensure_csrf_token()) ?>">
                    <input type="hidden" name="action" value="create">
                    <input type="hidden" name="id" value="">
                    <div class="row g-3">
                        <div class="col-12">
                            <label class="form-label">Name</label>
                            <input type="text" name="name" class="form-control" required>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">Date</label>
                            <input type="date" name="date" class="form-control" required>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">Time In</label>
                            <input type="time" name="time_in" class="form-control">
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">Time Out</label>
                            <input type="time" name="time_out" class="form-control">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Location</label>
                            <input type="text" name="location" class="form-control">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Required Participants</label>
                            <select name="required_students" class="form-select">
                                <option value="all" selected>All Students</option>
                                <option value="specific_course">Specific Course</option>
                                <option value="specific_department">Specific Department</option>
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Course Filter</label>
                            <select name="course_id" class="form-select">
                                <option value="" selected>—</option>
                                <?php foreach ($courses as $course): ?>
                                    <option value="<?= $course['id'] ?>"><?= sanitize($course['name']) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Department Filter</label>
                            <select name="department_id" class="form-select">
                                <option value="" selected>—</option>
                                <?php foreach ($departments as $department): ?>
                                    <option value="<?= $department['id'] ?>"><?= sanitize($department['name']) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-12">
                            <label class="form-label">Description</label>
                            <textarea name="description" class="form-control" rows="2"></textarea>
                        </div>
                        <div class="col-12">
                            <label class="form-label">Status</label>
                            <select name="status" class="form-select">
                                <option value="1" selected>Active</option>
                                <option value="0">Inactive</option>
                            </select>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Schedule Activity</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Delete confirmation modal -->
<div class="modal fade" id="deleteActivityModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <form method="post">
                <div class="modal-header">
                    <h5 class="modal-title">Delete Activity</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <input type="hidden" name="csrf_token" value="<?= sanitize(ensure_csrf_token()) ?>">
                    <input type="hidden" name="action" value="delete">
                    <input type="hidden" name="id" value="">
                    <p class="mb-1">Are you sure you want to delete this activity?</p>
                    <p class="fw-semibold mb-0" data-delete-name>Activity Name</p>
                    <small class="text-muted" data-delete-id data-label="Date">Date: —</small>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-danger">Delete</button>
                </div>
            </form>
        </div>
    </div>
</div>
<?php
render_footer();
