<?php
// =============================================================
//  GET /api/v1/reports/student_summary[?date_from=YYYY-MM-DD&date_to=YYYY-MM-DD]
//
//  Mobile equivalent of app/clinical_reports.php — the same four
//  sections (rotation block summary aggregated from
//  student_rotation_details, attendance, unit-level assessment,
//  final/overall assessment), the same scope_helper.php scoping, and
//  the same block-status derivation (Completed/In_Progress/Scheduled
//  from days_completed vs total_days). date_from/date_to filter
//  attendance only, matching the desktop page exactly.
//
//  No client-side export (Excel/PDF/Print) — see nurse_summary.php's
//  own note on that trade-off.
// =============================================================

require_once __DIR__ . '/../_bootstrap.php';
require_once __DIR__ . '/../../../include/scope_helper.php';

if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    Api::error(405, 'MethodNotAllowed', 'Use GET');
}

$account = api_authenticate();
api_require_permission('view_reports');

$dateFrom = trim((string)($_GET['date_from'] ?? ''));
$dateTo   = trim((string)($_GET['date_to'] ?? ''));
if ($dateFrom !== '' && !preg_match('/^\d{4}-\d{2}-\d{2}$/', $dateFrom)) $dateFrom = '';
if ($dateTo !== '' && !preg_match('/^\d{4}-\d{2}-\d{2}$/', $dateTo)) $dateTo = '';

// ── 1. Rotation block summary (aggregated per student per unit block) ───
$scope = scopeStudentWhere('srd', 'u');
$join  = $scope['needs_unit_join'] ? scopeStudentJoin('srd') : '';
$sql = "
    SELECT
        cs.id AS student_id, CONCAT(cs.firstname,' ',cs.surname) AS student_name,
        cs.student_id AS student_number, cs.school_name, cs.level, cs.programme, cs.status AS student_status,
        srd.unit_id, srd.unit_name, srd.supervisor_name,
        cr.batch_name, cr.id AS rotation_id,
        MIN(srd.rotation_date) AS block_start, MAX(srd.rotation_date) AS block_end,
        COUNT(srd.id) AS total_days,
        SUM(CASE WHEN srd.status = 'Completed' THEN 1 ELSE 0 END) AS days_completed
    FROM student_rotation_details srd
    JOIN clinical_students  cs ON srd.clinical_student_id  = cs.id
    JOIN clinical_rotations cr ON srd.clinical_rotation_id = cr.id
    $join
    WHERE cs.status != 'Inactive'
";
if ($scope['sql']) $sql .= " AND {$scope['sql']}";
$sql .= " GROUP BY cs.id, srd.unit_id, cr.id ORDER BY cs.firstname, cs.surname, srd.sequence_order";
$stmt = $conn->prepare($sql);
if ($scope['types']) $stmt->bind_param($scope['types'], ...$scope['params']);
$stmt->execute();
$schedules = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close();

foreach ($schedules as &$s) {
    if ((int)$s['days_completed'] >= (int)$s['total_days'] && (int)$s['total_days'] > 0) {
        $s['block_status'] = 'Completed';
    } elseif ((int)$s['days_completed'] > 0) {
        $s['block_status'] = 'In_Progress';
    } else {
        $s['block_status'] = 'Scheduled';
    }
}
unset($s);

// ── 2. Attendance ────────────────────────────────────────────────────────
$attScope = scopeStudentWhere('ca', 'u2');
$attJoin  = $attScope['needs_unit_join'] ? "JOIN units u2 ON ca.unit_id = u2.id" : '';
$attSql = "
    SELECT
        ca.id, ca.attendance_date, ca.status, ca.remarks, ca.unit_name,
        CONCAT(cs.firstname,' ',cs.surname) AS student_name,
        cs.student_id AS student_number, cs.school_name,
        cr.batch_name,
        CONCAT(u.firstname,' ',u.surname) AS marked_by_name
    FROM clinical_attendance ca
    JOIN clinical_students  cs ON ca.clinical_student_id  = cs.id
    JOIN clinical_rotations cr ON ca.clinical_rotation_id = cr.id
    LEFT JOIN users u ON ca.marked_by = u.id
    $attJoin
    WHERE 1=1
";
$attTypes  = $attScope['types'];
$attParams = $attScope['params'];
if ($attScope['sql']) $attSql .= " AND {$attScope['sql']}";
if ($dateFrom !== '') { $attSql .= " AND ca.attendance_date >= ?"; $attParams[] = $dateFrom; $attTypes .= 's'; }
if ($dateTo !== '')   { $attSql .= " AND ca.attendance_date <= ?"; $attParams[] = $dateTo;   $attTypes .= 's'; }
$attSql .= " ORDER BY ca.attendance_date DESC, cs.firstname";
$stmt = $conn->prepare($attSql);
if ($attTypes) $stmt->bind_param($attTypes, ...$attParams);
$stmt->execute();
$attendance = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close();

// ── 3. Unit-level assessment ─────────────────────────────────────────────
$assessScope = scopeStudentWhere('ca2', 'u3');
$assessJoin  = $assessScope['needs_unit_join'] ? "JOIN units u3 ON ca2.unit_id = u3.id" : '';
$assessSql = "
    SELECT
        ca2.id, ca2.unit_name, ca2.assessment_date, ca2.total_score,
        ca2.max_possible_score, ca2.percentage_score, ca2.grade, ca2.eval_status,
        CONCAT(cs.firstname,' ',cs.surname) AS student_name,
        cs.student_id AS student_number, cs.school_name,
        cr.batch_name,
        CONCAT(u.firstname,' ',u.surname) AS assessor_name
    FROM clinical_assessments ca2
    JOIN clinical_students  cs ON ca2.clinical_student_id  = cs.id
    JOIN clinical_rotations cr ON ca2.clinical_rotation_id = cr.id
    LEFT JOIN users u ON ca2.submitted_by = u.id
    $assessJoin
    WHERE ca2.eval_status IN ('submitted','locked')
";
if ($assessScope['sql']) $assessSql .= " AND {$assessScope['sql']}";
$assessSql .= " ORDER BY ca2.created_at DESC";
$stmt = $conn->prepare($assessSql);
if ($assessScope['types']) $stmt->bind_param($assessScope['types'], ...$assessScope['params']);
$stmt->execute();
$assessments = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close();

// ── 4. Final/overall assessment ──────────────────────────────────────────
// Scoped by the same visible-student-id list the schedule section already
// resolved, exactly like app/clinical_reports.php does — final
// assessments are per-student, not per-unit, so there's no direct
// unit/department column on this table to scope through directly.
$finalSql = "
    SELECT
        cfa.id, cfa.total_score_all_units, cfa.average_percentage,
        cfa.final_grade, cfa.final_verdict, cfa.preceptor_name, cfa.created_at,
        CONCAT(cs.firstname,' ',cs.surname) AS student_name,
        cs.student_id AS student_number, cs.school_name, cs.level, cs.programme,
        cr.batch_name
    FROM clinical_final_assessments cfa
    JOIN clinical_students  cs ON cfa.clinical_student_id  = cs.id
    JOIN clinical_rotations cr ON cfa.clinical_rotation_id = cr.id
    WHERE 1=1
";
if (!isFullAccess()) {
    $visibleStudentIds = array_values(array_unique(array_column($schedules, 'student_id')));
    if (!empty($visibleStudentIds)) {
        $placeholders = implode(',', array_fill(0, count($visibleStudentIds), '?'));
        $finalSql .= " AND cs.id IN ($placeholders)";
        $finalTypes  = str_repeat('i', count($visibleStudentIds));
        $finalParams = $visibleStudentIds;
    } else {
        $finalSql .= " AND 1=0";
        $finalTypes  = '';
        $finalParams = [];
    }
} else {
    $finalTypes  = '';
    $finalParams = [];
}
$finalSql .= " ORDER BY cfa.created_at DESC";
$stmt = $conn->prepare($finalSql);
if ($finalTypes) $stmt->bind_param($finalTypes, ...$finalParams);
$stmt->execute();
$finals = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close();

// ── Stats — same derivations as app/clinical_reports.php ────────────────
$totalStudents = count(array_unique(array_column($schedules, 'student_id')));

$schedInProgress = count(array_filter($schedules, fn($s) => $s['block_status'] === 'In_Progress'));
$schedCompleted  = count(array_filter($schedules, fn($s) => $s['block_status'] === 'Completed'));
$schedScheduled  = count(array_filter($schedules, fn($s) => $s['block_status'] === 'Scheduled'));

$attTotal   = count($attendance);
$attPresent = count(array_filter($attendance, fn($a) => $a['status'] === 'Present'));
$attAbsent  = count(array_filter($attendance, fn($a) => $a['status'] === 'Absent'));
$attLate    = count(array_filter($attendance, fn($a) => $a['status'] === 'Late'));
$attRate    = $attTotal > 0 ? round(($attPresent / $attTotal) * 100, 1) : 0;

$assessTotal   = count($assessments);
$assessExcel   = count(array_filter($assessments, fn($a) => $a['grade'] === 'Excellent'));
$assessPoor    = count(array_filter($assessments, fn($a) => $a['grade'] === 'Poor'));
$avgScoreArr   = array_filter(array_column($assessments, 'percentage_score'), fn($v) => $v !== null);
$avgScore      = !empty($avgScoreArr) ? round(array_sum($avgScoreArr) / count($avgScoreArr), 1) : 0;

$finalPass  = count(array_filter($finals, fn($f) => $f['final_verdict'] === 'Pass'));
$finalFail  = count(array_filter($finals, fn($f) => $f['final_verdict'] === 'Fail'));
$finalDefer = count(array_filter($finals, fn($f) => $f['final_verdict'] === 'Defer'));

Api::success([
    'schedules'   => $schedules,
    'attendance'  => $attendance,
    'assessments' => $assessments,
    'finals'      => $finals,
    'stats' => [
        'total_students'    => $totalStudents,
        'sched_in_progress' => $schedInProgress,
        'sched_completed'   => $schedCompleted,
        'sched_scheduled'   => $schedScheduled,
        'att_total'         => $attTotal,
        'att_present'       => $attPresent,
        'att_absent'        => $attAbsent,
        'att_late'          => $attLate,
        'att_rate'          => $attRate,
        'assess_total'      => $assessTotal,
        'assess_excellent'  => $assessExcel,
        'assess_poor'       => $assessPoor,
        'avg_score'         => $avgScore,
        'final_pass'        => $finalPass,
        'final_fail'        => $finalFail,
        'final_defer'       => $finalDefer,
    ],
    'scope' => getScopeLabel(),
]);
