<?php
// =============================================================
//  GET /api/v1/analytics/dashboard[?from=YYYY-MM-DD&to=YYYY-MM-DD]
//
//  An "at a glance" summary for the mobile Admin/Chief Preceptor
//  oversight view, drawn from the same queries as app/analytics.php's
//  desktop dashboard. Now a complete port of all eight of that page's
//  chart sections — confirmed by an actual count of its <canvas>
//  elements, correcting an earlier, unverified "17 sections" figure in
//  this file's own header comment (the real count is 8: two doughnuts,
//  an attendance trend line, two horizontal bars, a department-load
//  bar, a lessons bar, and a grade-distribution bar).
// =============================================================

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

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

$account = api_authenticate();
api_require_staff_role($account, ['Admin', 'Chief_Preceptor']);

$from = trim((string)($_GET['from'] ?? ''));
$to   = trim((string)($_GET['to']   ?? ''));
if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $from)) $from = date('Y-m-d', strtotime('-30 days'));
if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $to))   $to   = date('Y-m-d');

$totalNurses   = (int)$conn->query("SELECT COUNT(*) c FROM rotation_nurses WHERE status = 'Active'")->fetch_assoc()['c'];
$totalStudents = (int)$conn->query("SELECT COUNT(*) c FROM clinical_students WHERE status = 'Active'")->fetch_assoc()['c'];
$nurseInProgress   = (int)$conn->query("SELECT COUNT(DISTINCT rotation_nurse_id) c FROM nurse_rotation_schedules WHERE status = 'In_Progress'")->fetch_assoc()['c'];
$studentInProgress = (int)$conn->query("SELECT COUNT(DISTINCT clinical_student_id) c FROM student_rotation_details WHERE status = 'Ongoing'")->fetch_assoc()['c'];

$nurseAttendance = [];
$stmt = $conn->prepare("SELECT status, COUNT(*) c FROM nurse_attendance WHERE attendance_date BETWEEN ? AND ? GROUP BY status");
$stmt->bind_param('ss', $from, $to);
$stmt->execute();
foreach ($stmt->get_result()->fetch_all(MYSQLI_ASSOC) as $row) $nurseAttendance[$row['status']] = (int)$row['c'];
$stmt->close();

$studentAttendance = [];
$stmt = $conn->prepare("SELECT status, COUNT(*) c FROM clinical_attendance WHERE attendance_date BETWEEN ? AND ? GROUP BY status");
$stmt->bind_param('ss', $from, $to);
$stmt->execute();
foreach ($stmt->get_result()->fetch_all(MYSQLI_ASSOC) as $row) $studentAttendance[$row['status']] = (int)$row['c'];
$stmt->close();

$nurseVerdicts = [];
foreach ($conn->query("SELECT final_verdict, COUNT(*) c FROM nurse_assessments WHERE final_verdict IS NOT NULL GROUP BY final_verdict")->fetch_all(MYSQLI_ASSOC) as $row) {
    $nurseVerdicts[$row['final_verdict']] = (int)$row['c'];
}
$studentVerdicts = [];
foreach ($conn->query("SELECT final_verdict, COUNT(*) c FROM clinical_final_assessments WHERE final_verdict IS NOT NULL GROUP BY final_verdict")->fetch_all(MYSQLI_ASSOC) as $row) {
    $studentVerdicts[$row['final_verdict']] = (int)$row['c'];
}

// Mirrors app/analytics.php's Chart 1 exactly.
$nurseStatusData = [];
foreach ($conn->query("
    SELECT status, COUNT(DISTINCT rotation_nurse_id) AS cnt
    FROM nurse_rotation_schedules
    GROUP BY status
")->fetch_all(MYSQLI_ASSOC) as $row) {
    $nurseStatusData[$row['status']] = (int)$row['cnt'];
}

// Mirrors app/analytics.php's Chart 2 exactly, including its 'Not_started'
// fallback for a NULL/empty rotation_status.
$studentStatusData = [];
foreach ($conn->query("SELECT rotation_status, COUNT(*) AS cnt FROM clinical_students WHERE status='Active' GROUP BY rotation_status")->fetch_all(MYSQLI_ASSOC) as $row) {
    $key = $row['rotation_status'] ?: 'Not_started';
    $studentStatusData[$key] = (int)$row['cnt'];
}

// Mirrors app/analytics.php's Chart 6 exactly — active nurses currently
// rotating, grouped by department.
$deptLoad = [];
foreach ($conn->query("
    SELECT COALESCE(department_name, 'Unassigned') AS dept, COUNT(DISTINCT rotation_nurse_id) AS cnt
    FROM nurse_rotation_schedules
    WHERE status = 'In_Progress'
    GROUP BY department_name
    ORDER BY cnt DESC
")->fetch_all(MYSQLI_ASSOC) as $row) {
    $deptLoad[] = ['label' => $row['dept'], 'count' => (int)$row['cnt']];
}

// Mirrors app/analytics.php's Chart 3 exactly — daily % present over the
// same [from, to] range as the attendance breakdown above, one series per
// role. The desktop page interpolates $f_from/$f_to directly into SQL
// (flagged in its own comment as depending on validDateOrDefault() to stay
// safe); bind_param() here removes that risk entirely rather than porting it.
$nurseTrend = [];
$stmt = $conn->prepare("
    SELECT attendance_date,
           SUM(CASE WHEN status='Present' THEN 1 ELSE 0 END) AS present_ct,
           COUNT(*) AS total_ct
    FROM nurse_attendance
    WHERE attendance_date BETWEEN ? AND ?
    GROUP BY attendance_date
    ORDER BY attendance_date
");
$stmt->bind_param('ss', $from, $to);
$stmt->execute();
foreach ($stmt->get_result()->fetch_all(MYSQLI_ASSOC) as $row) {
    $rate = $row['total_ct'] > 0 ? round(($row['present_ct'] / $row['total_ct']) * 100, 1) : 0;
    $nurseTrend[] = ['date' => $row['attendance_date'], 'rate' => $rate];
}
$stmt->close();

$studentTrend = [];
$stmt = $conn->prepare("
    SELECT attendance_date,
           SUM(CASE WHEN status='Present' THEN 1 ELSE 0 END) AS present_ct,
           COUNT(*) AS total_ct
    FROM clinical_attendance
    WHERE attendance_date BETWEEN ? AND ?
    GROUP BY attendance_date
    ORDER BY attendance_date
");
$stmt->bind_param('ss', $from, $to);
$stmt->execute();
foreach ($stmt->get_result()->fetch_all(MYSQLI_ASSOC) as $row) {
    $rate = $row['total_ct'] > 0 ? round(($row['present_ct'] / $row['total_ct']) * 100, 1) : 0;
    $studentTrend[] = ['date' => $row['attendance_date'], 'rate' => $rate];
}
$stmt->close();

// Mirrors app/analytics.php's Chart 4 exactly.
$nurseBySpecialty = [];
foreach ($conn->query("
    SELECT COALESCE(specialty_name, 'Unassigned') AS specialty, COUNT(*) AS cnt
    FROM rotation_nurses
    WHERE status = 'Active'
    GROUP BY specialty_name
    ORDER BY cnt DESC
")->fetch_all(MYSQLI_ASSOC) as $row) {
    $nurseBySpecialty[] = ['label' => $row['specialty'], 'count' => (int)$row['cnt']];
}

// Mirrors app/analytics.php's Chart 5 exactly.
$studentBySchool = [];
foreach ($conn->query("
    SELECT COALESCE(school_name, 'Unassigned') AS school, COUNT(*) AS cnt
    FROM clinical_students
    WHERE status = 'Active'
    GROUP BY school_name
    ORDER BY cnt DESC
")->fetch_all(MYSQLI_ASSOC) as $row) {
    $studentBySchool[] = ['label' => $row['school'], 'count' => (int)$row['cnt']];
}

// Mirrors app/analytics.php's Chart 8 (grade distribution) exactly — same
// fixed grade order, same "only known grades counted" behaviour.
$gradeOrder = ['Excellent', 'Very Good', 'Good', 'Fair', 'Poor'];
$nurseGrades = array_fill_keys($gradeOrder, 0);
foreach ($conn->query("SELECT final_grade, COUNT(*) AS cnt FROM nurse_assessments WHERE final_grade IS NOT NULL GROUP BY final_grade")->fetch_all(MYSQLI_ASSOC) as $row) {
    if (isset($nurseGrades[$row['final_grade']])) $nurseGrades[$row['final_grade']] = (int)$row['cnt'];
}
$studentGrades = array_fill_keys($gradeOrder, 0);
foreach ($conn->query("SELECT final_grade, COUNT(*) AS cnt FROM clinical_final_assessments WHERE final_grade IS NOT NULL GROUP BY final_grade")->fetch_all(MYSQLI_ASSOC) as $row) {
    if (isset($studentGrades[$row['final_grade']])) $studentGrades[$row['final_grade']] = (int)$row['cnt'];
}

// Mirrors app/analytics.php's Chart 7 (lessons pending vs submitted)
// exactly, including its two genuinely different conventions: nurse_lessons
// has its own 'status' column, while clinical_lessons has none — a lesson
// there counts as submitted once submitted_at is set, matching
// app/clinical_lessons.php's own convention.
$lessons = ['nurse_pending' => 0, 'nurse_submitted' => 0, 'student_pending' => 0, 'student_submitted' => 0];
foreach ($conn->query("SELECT status, COUNT(*) AS c FROM nurse_lessons GROUP BY status")->fetch_all(MYSQLI_ASSOC) as $row) {
    if (in_array($row['status'], ['Pending', 'pending'], true)) $lessons['nurse_pending'] += (int)$row['c'];
    else $lessons['nurse_submitted'] += (int)$row['c'];
}
$lessons['student_submitted'] = (int)$conn->query("SELECT COUNT(*) AS c FROM clinical_lessons WHERE submitted_at IS NOT NULL")->fetch_assoc()['c'];
$lessons['student_pending']   = (int)$conn->query("SELECT COUNT(*) AS c FROM clinical_lessons WHERE submitted_at IS NULL")->fetch_assoc()['c'];

Api::success([
    'range' => ['from' => $from, 'to' => $to],
    'headline' => [
        'total_nurses'          => $totalNurses,
        'total_students'        => $totalStudents,
        'nurses_in_progress'    => $nurseInProgress,
        'students_in_progress'  => $studentInProgress,
    ],
    'attendance' => [
        'nurses'   => $nurseAttendance,
        'students' => $studentAttendance,
    ],
    'final_verdicts' => [
        'nurses'   => $nurseVerdicts,
        'students' => $studentVerdicts,
    ],
    'rotation_status' => [
        'nurses'   => $nurseStatusData,
        'students' => $studentStatusData,
    ],
    'department_load' => $deptLoad,
    'attendance_trend' => [
        'nurses'   => $nurseTrend,
        'students' => $studentTrend,
    ],
    'nurse_by_specialty' => $nurseBySpecialty,
    'student_by_school'  => $studentBySchool,
    'grade_distribution' => [
        'grade_order' => $gradeOrder,
        'nurses'      => array_values($nurseGrades),
        'students'    => array_values($studentGrades),
    ],
    'lessons' => $lessons,
]);
