<?php
// =============================================================
//  GET /api/v1/reports/nurse_summary[?date_from=YYYY-MM-DD&date_to=YYYY-MM-DD]
//
//  Mobile equivalent of app/nurse_reports.php — the same three sections
//  (rotation schedule, attendance, assessment results), the same
//  scope_helper.php scoping (Admin/Chief_Preceptor see everyone,
//  Preceptor/Nurse_Manager their department, In_Charge their unit(s)),
//  and the same stats computed from the fetched rows rather than a
//  separate COUNT query. date_from/date_to filter attendance only,
//  matching the desktop page exactly — schedule and assessment sections
//  are not date-filtered there either.
//
//  Unlike the desktop page, there is no client-side export (Excel/PDF/
//  Print via DataTables Buttons) — that's a desktop-shaped feature with
//  no clean mobile equivalent, and out of scope for this endpoint.
// =============================================================

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 schedule ────────────────────────────────────────────────
$scope = scopeNurseWhere('nrs');
$sql = "
    SELECT
        rn.id AS nurse_id, CONCAT(rn.firstname,' ',rn.surname) AS nurse_name,
        rn.student_id AS nurse_number, rn.specialty_name, rn.school_name, rn.status AS nurse_status,
        nrs.id AS schedule_id, nrs.unit_name, nrs.department_name,
        nrs.start_week, nrs.end_week, nrs.status AS schedule_status,
        nr.start_date, nr.id AS rotation_id
    FROM rotation_nurses rn
    JOIN nurse_rotations nr ON nr.nurse_id = rn.id
    JOIN nurse_rotation_schedules nrs ON nrs.nurse_rotation_id = nr.id
    WHERE rn.status != 'Cancelled'
";
if ($scope['sql']) $sql .= " AND {$scope['sql']}";
$sql .= " ORDER BY rn.firstname, rn.surname, nrs.start_week";
$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();

// ── 2. Attendance ────────────────────────────────────────────────────────
$attScope = scopeNurseWhere('na');
$attSql = "
    SELECT
        na.id, na.attendance_date, na.status, na.remarks,
        na.unit_name, na.department_name,
        CONCAT(rn.firstname,' ',rn.surname) AS nurse_name,
        rn.student_id AS nurse_number, rn.specialty_name,
        CONCAT(u.firstname,' ',u.surname) AS marked_by_name
    FROM nurse_attendance na
    JOIN rotation_nurses rn ON na.rotation_nurse_id = rn.id
    LEFT JOIN users u ON na.marked_by = u.id
    WHERE 1=1
";
$attTypes  = $attScope['types'];
$attParams = $attScope['params'];
if ($attScope['sql']) $attSql .= " AND {$attScope['sql']}";
if ($dateFrom !== '') { $attSql .= " AND na.attendance_date >= ?"; $attParams[] = $dateFrom; $attTypes .= 's'; }
if ($dateTo !== '')   { $attSql .= " AND na.attendance_date <= ?"; $attParams[] = $dateTo;   $attTypes .= 's'; }
$attSql .= " ORDER BY na.attendance_date DESC, rn.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. Assessment results ───────────────────────────────────────────────
$assessScope = scopeNurseWhere('nrs2');
$assessSql = "
    SELECT
        na.id, na.overall_status, na.is_locked,
        na.stage1_status, na.s1_percentage, na.s1_grade,
        na.stage2_status, na.s2_percentage, na.s2_grade,
        na.stage3_status, na.s3_percentage, na.s3_grade,
        na.final_percentage, na.final_grade, na.final_verdict,
        na.created_at,
        CONCAT(rn.firstname,' ',rn.surname) AS nurse_name,
        rn.student_id AS nurse_number, rn.specialty_name, rn.school_name,
        nrs2.unit_name, nrs2.department_name
    FROM nurse_assessments na
    JOIN rotation_nurses rn ON na.rotation_nurse_id = rn.id
    JOIN nurse_rotation_schedules nrs2 ON na.nurse_rotation_schedule_id = nrs2.id
    WHERE 1=1
";
if ($assessScope['sql']) $assessSql .= " AND {$assessScope['sql']}";
$assessSql .= " ORDER BY na.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();

// ── Stats — same derivations as app/nurse_reports.php ───────────────────
$totalNurses = count(array_unique(array_column($schedules, 'nurse_id')));

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

$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);
$assessPass     = count(array_filter($assessments, fn($a) => $a['final_verdict'] === 'Pass'));
$assessFail     = count(array_filter($assessments, fn($a) => $a['final_verdict'] === 'Fail'));
$assessComplete = count(array_filter($assessments, fn($a) => $a['overall_status'] === 'completed'));
$avgScoreArr    = array_filter(array_column($assessments, 'final_percentage'), fn($v) => $v !== null);
$avgScore       = !empty($avgScoreArr) ? round(array_sum($avgScoreArr) / count($avgScoreArr), 1) : 0;

Api::success([
    'schedules'   => $schedules,
    'attendance'  => $attendance,
    'assessments' => $assessments,
    'stats' => [
        'total_nurses'      => $totalNurses,
        'sched_in_progress' => $schedInProgress,
        'sched_completed'   => $schedCompleted,
        'sched_scheduled'   => $schedScheduled,
        'sched_missed'      => $schedMissed,
        'att_total'         => $attTotal,
        'att_present'       => $attPresent,
        'att_absent'        => $attAbsent,
        'att_late'          => $attLate,
        'att_rate'          => $attRate,
        'assess_total'      => $assessTotal,
        'assess_pass'       => $assessPass,
        'assess_fail'       => $assessFail,
        'assess_complete'   => $assessComplete,
        'avg_score'         => $avgScore,
    ],
    'scope' => getScopeLabel(),
]);
