<?php
/**
 * API: get_teacher_ai_report.php
 * Returns the latest AI performance report for a teacher's assigned class/section.
 * Reads from ai_performance_reports (persisted by AIEngine::persistResults).
 */
header('Content-Type: application/json');

include('../includes/session1.php');
include('../includes/dbconnection.php');

if (empty($_SESSION['sid'])) {
    http_response_code(403);
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

$teacher_id = (int) $_SESSION['sid'];

// Resolve teacher's class/section from teacher_assignments
$stmt = $con->prepare("
    SELECT cs.class, cs.section
    FROM teacher_assignments ta
    JOIN class_section cs ON ta.class_id = cs.id
    WHERE ta.teacher_id = ? AND ta.is_class_teacher = 1
    LIMIT 1
");
$stmt->bind_param("i", $teacher_id);
$stmt->execute();
$row = $stmt->get_result()->fetch_assoc();

if (!$row) {
    echo json_encode(['success' => false, 'message' => 'Not assigned as class teacher.']);
    exit;
}

$class = $con->real_escape_string($row['class']);
$section = $con->real_escape_string($row['section']);

// Fetch latest session_id for this class from ai_performance_reports
$sessionRow = $con->query("
    SELECT session_id, term_id
    FROM ai_performance_reports
    WHERE class = '{$class}' AND section = '{$section}'
    ORDER BY generated_at DESC
    LIMIT 1
")->fetch_assoc();

if (!$sessionRow) {
    echo json_encode([
        'success' => true,
        'data' => ['students' => [], 'summary' => null, 'message' => 'No AI report generated yet for this class. Ask the admin to generate a report first.']
    ]);
    exit;
}

$sessionId = (int) $sessionRow['session_id'];
$termId = (int) $sessionRow['term_id'];

// Fetch all student AI records for this class/section/session/term
$sql = "
    SELECT
        ap.student_id,
        s.studentName,
        s.studentno,
        s.gender,
        ap.exam_score,
        ap.test_score,
        ap.class_performance,
        ap.weekly_assessment,
        ap.performance_score   AS base_score,
        ap.trend_score,
        ap.ai_band,
        ap.risk_level,
        ap.strength_subjects,
        ap.improvement_subjects,
        ap.parent_recommendation,
        ap.generated_at
    FROM ai_performance_reports ap
    INNER JOIN students s ON s.id = ap.student_id
    WHERE ap.class   = '{$class}'
      AND ap.section = '{$section}'
      AND ap.session_id = {$sessionId}
      AND ap.term_id    = {$termId}
    ORDER BY ap.performance_score DESC
";

$result = $con->query($sql);
$students = [];

while ($r = $result->fetch_assoc()) {
    $r['strength_subjects'] = json_decode($r['strength_subjects'], true) ?? [];
    $r['improvement_subjects'] = json_decode($r['improvement_subjects'], true) ?? [];
    $students[] = $r;
}

// Build summary stats
$total = count($students);
$passing = count(array_filter($students, fn($s) => (float) $s['base_score'] >= 50));
$atRisk = array_filter($students, fn($s) => !empty($s['risk_level']));
$critical = array_filter($students, fn($s) => $s['risk_level'] === 'Critical');
$high = array_filter($students, fn($s) => $s['risk_level'] === 'High');
$moderate = array_filter($students, fn($s) => $s['risk_level'] === 'Moderate');
$avgScore = $total > 0 ? array_sum(array_column($students, 'base_score')) / $total : 0;
$passRate = $total > 0 ? ($passing / $total) * 100 : 0;

// Subject averages for this class
$subjectTotals = [];
foreach ($students as $s) {
    foreach ($s['improvement_subjects'] as $sub) {
        $subj = $sub['subject'] ?? '';
        if ($subj) {
            $subjectTotals[$subj] = ($subjectTotals[$subj] ?? 0) + 1;
        }
    }
}
// Most commonly flagged improvement subjects
arsort($subjectTotals);
$topWeakSubjects = array_slice(array_keys($subjectTotals), 0, 3);

$summary = [
    'class' => $class,
    'section' => $section,
    'total_students' => $total,
    'average_score' => round($avgScore, 1),
    'pass_rate' => round($passRate, 1),
    'at_risk_count' => count($atRisk),
    'critical_count' => count($critical),
    'high_count' => count($high),
    'moderate_count' => count($moderate),
    'weak_subjects' => $topWeakSubjects,
    'generated_at' => $students[0]['generated_at'] ?? null,
];

echo json_encode([
    'success' => true,
    'data' => [
        'students' => $students,
        'summary' => $summary,
    ]
]);
