<?php
declare(strict_types=1);
session_start();
require_once '../../config.php';
require_once dirname(__DIR__) . '/helpers.php';
header('Content-Type: application/json');
if (!isset($_SESSION['parent_id'])) { http_response_code(401); echo json_encode(['success'=>false]); exit; }
$conn = portalGetConnection();
if (!$conn instanceof mysqli) { echo json_encode(['success'=>false]); exit; }
$studentId = (int) ($_POST['student_id'] ?? 0);
$term = trim((string) ($_POST['term'] ?? ''));
$year = trim((string) ($_POST['academic_year'] ?? ''));
$parentId = (int) $_SESSION['parent_id'];
if (!portalParentOwnsStudent($conn, $parentId, $studentId)) {
    echo json_encode(['success'=>false, 'message'=>'Unauthorized']); exit;
}
$scores = [];
$reportDetails = null;
$examResults = [];
$scoreStmt = $conn->prepare(
    "SELECT sub.subject_name, sc.class_score, sc.exam_score, sc.total, sc.grade, sc.remark
     FROM scores sc
     LEFT JOIN subjects sub ON sub.id = sc.subject_id
     WHERE sc.student_id = ? AND sc.term = ? AND sc.academic_year = ?
     ORDER BY sub.subject_name ASC"
);
$scoreStmt->bind_param('iss', $studentId, $term, $year);
$scoreStmt->execute();
$scoreResult = $scoreStmt->get_result();
while ($row = $scoreResult->fetch_assoc()) { $scores[] = $row; }
$scoreStmt->close();
$detailsStmt = $conn->prepare("SELECT * FROM report_details WHERE student_id = ? AND term = ? AND academic_year = ? LIMIT 1");
$detailsStmt->bind_param('iss', $studentId, $term, $year);
$detailsStmt->execute();
$reportDetails = $detailsStmt->get_result()->fetch_assoc();
$detailsStmt->close();
$examStmt = $conn->prepare(
    "SELECT ep.title, ep.term, er.score, er.grade
     FROM exam_results er
     INNER JOIN exam_papers ep ON ep.id = er.paper_id
     WHERE er.student_id = ?
     ORDER BY er.submitted_at DESC"
);
$examStmt->bind_param('i', $studentId);
$examStmt->execute();
$examResult = $examStmt->get_result();
while ($row = $examResult->fetch_assoc()) { $examResults[] = $row; }
$examStmt->close();
echo json_encode(['success'=>true, 'scores'=>$scores, 'report_details'=>$reportDetails, 'exam_results'=>$examResults]);
