<?php
/** Student leadership & extracurricular history — AJAX. */
if (session_status() === PHP_SESSION_NONE) session_start();
header('Content-Type: application/json');

require_once __DIR__ . '/../config.php';
if (!isset($_SESSION['user_id'])) { http_response_code(401); echo json_encode(['success' => false, 'message' => 'Not signed in.']); exit; }
requireModule('student_activities', true);
require_once __DIR__ . '/../includes/student_activities_lib.php';

$conn = getDBConnection();
sa_ensure_tables($conn);
$uid    = (int) $_SESSION['user_id'];
$role   = $_SESSION['role'] ?? '';
$canEdit = in_array($role, ['admin', 'headteacher', 'supervisor', 'director', 'registrar'], true);
$action = $_POST['action'] ?? $_GET['action'] ?? '';

function sa_out($p){ echo json_encode($p); exit; }

switch ($action) {

    case 'search_students': {
        $q = trim($_GET['q'] ?? $_POST['q'] ?? '');
        $like = '%' . $q . '%';
        $stmt = $conn->prepare("SELECT id, student_id, first_name, last_name, class
            FROM students WHERE status='active' AND (CONCAT(first_name,' ',last_name) LIKE ? OR student_id LIKE ? OR class LIKE ?)
            ORDER BY first_name, last_name LIMIT 25");
        $stmt->bind_param('sss', $like, $like, $like); $stmt->execute();
        $res = $stmt->get_result(); $rows = [];
        while ($r = $res->fetch_assoc()) {
            $rows[] = ['id' => $r['id'], 'label' => $r['first_name'] . ' ' . $r['last_name'] . ' — ' . $r['class'] . ' (' . $r['student_id'] . ')'];
        }
        $stmt->close();
        sa_out(['success' => true, 'data' => $rows]);
    }

    case 'get': {
        $sid = (int) ($_GET['student_id'] ?? $_POST['student_id'] ?? 0);
        if (!$sid) sa_out(['success' => false, 'message' => 'No student selected.']);
        $s = $conn->prepare("SELECT id, student_id, first_name, last_name, class FROM students WHERE id=?");
        $s->bind_param('i', $sid); $s->execute();
        $stu = $s->get_result()->fetch_assoc(); $s->close();
        if (!$stu) sa_out(['success' => false, 'message' => 'Student not found.']);
        sa_out([
            'success'    => true,
            'student'    => $stu,
            'leadership' => sa_leadership_for($conn, $sid),
            'activities' => sa_activities_for($conn, $sid),
            'can_edit'   => $canEdit,
        ]);
    }

    case 'add_leadership': {
        if (!$canEdit) sa_out(['success' => false, 'message' => 'Not permitted.']);
        $sid   = (int) ($_POST['student_id'] ?? 0);
        $roleT = trim($_POST['role'] ?? '');
        $year  = trim($_POST['academic_year'] ?? '');
        $term  = trim($_POST['term'] ?? '') ?: null;
        $start = trim($_POST['start_date'] ?? '') ?: null;
        $end   = trim($_POST['end_date'] ?? '') ?: null;
        $note  = trim($_POST['note'] ?? '') ?: null;
        if (!$sid || $roleT === '' || $year === '') sa_out(['success' => false, 'message' => 'Role and academic year are required.']);
        $stmt = $conn->prepare("INSERT INTO student_leadership (student_id, role, academic_year, term, start_date, end_date, note, created_by)
                                VALUES (?,?,?,?,?,?,?,?)");
        $stmt->bind_param('issssssi', $sid, $roleT, $year, $term, $start, $end, $note, $uid);
        $stmt->execute(); $stmt->close();
        sa_out(['success' => true, 'message' => 'Leadership role recorded.']);
    }

    case 'delete_leadership': {
        if (!$canEdit) sa_out(['success' => false, 'message' => 'Not permitted.']);
        $id = (int) ($_POST['id'] ?? 0);
        $conn->query("DELETE FROM student_leadership WHERE id=" . $id);
        sa_out(['success' => true, 'message' => 'Removed.']);
    }

    case 'add_activity': {
        if (!$canEdit) sa_out(['success' => false, 'message' => 'Not permitted.']);
        $sid    = (int) ($_POST['student_id'] ?? 0);
        $name   = trim($_POST['activity_name'] ?? '');
        $type   = $_POST['activity_type'] ?? 'club';
        $year   = trim($_POST['academic_year'] ?? '');
        $pos    = trim($_POST['position'] ?? '') ?: null;
        $ach    = trim($_POST['achievement'] ?? '') ?: null;
        if (!in_array($type, ['sport', 'club', 'society', 'other'], true)) $type = 'club';
        if (!$sid || $name === '' || $year === '') sa_out(['success' => false, 'message' => 'Activity name and academic year are required.']);
        $stmt = $conn->prepare("INSERT INTO student_activities (student_id, activity_name, activity_type, academic_year, position, achievement, created_by)
                                VALUES (?,?,?,?,?,?,?)");
        $stmt->bind_param('isssssi', $sid, $name, $type, $year, $pos, $ach, $uid);
        $stmt->execute(); $stmt->close();
        sa_out(['success' => true, 'message' => 'Activity recorded.']);
    }

    case 'delete_activity': {
        if (!$canEdit) sa_out(['success' => false, 'message' => 'Not permitted.']);
        $id = (int) ($_POST['id'] ?? 0);
        $conn->query("DELETE FROM student_activities WHERE id=" . $id);
        sa_out(['success' => true, 'message' => 'Removed.']);
    }

    default:
        sa_out(['success' => false, 'message' => 'Unknown action.']);
}
