<?php
// =============================================================
//  include/RotationScheduleHelpers.php
//
//  "My schedule, with live/computed status" — extracted from
//  app/nurse/my_schedule.php and app/student/my_rotation.php so the
//  mobile API (api/v1/rotations/nurse_mine.php / student_mine.php) and
//  those two web pages share one implementation instead of the API
//  growing a second, inevitably-drifting copy of the same date-math and
//  status-derivation logic. Pure reads (plus the same date-driven status
//  auto-advance the student page already performs) — no new behavior.
// =============================================================

/**
 * A rotation nurse's full schedule (all department/unit blocks), each
 * enriched with computed date_from/date_to and a live_status derived from
 * today's date rather than the possibly-stale stored status.
 */
function getNurseScheduleWithLiveStatus(mysqli $conn, int $nurseId): array
{
    $stmt = $conn->prepare("
        SELECT
            nrs.id, nrs.department_name, nrs.unit_name,
            nrs.start_week, nrs.end_week, nrs.duration_weeks, nrs.status,
            nr.start_date, nr.end_date, nr.id AS rotation_id
        FROM nurse_rotation_schedules nrs
        JOIN nurse_rotations nr ON nrs.nurse_rotation_id = nr.id
        WHERE nrs.rotation_nurse_id = ?
        ORDER BY nrs.start_week ASC
    ");
    $stmt->bind_param('i', $nurseId);
    $stmt->execute();
    $schedules = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $stmt->close();

    $today = date('Y-m-d');
    foreach ($schedules as &$s) {
        if ($s['start_date']) {
            $origin         = strtotime($s['start_date']);
            $s['date_from'] = date('Y-m-d', $origin + ($s['start_week'] - 1) * 7 * 86400);
            $s['date_to']   = date('Y-m-d', $origin + ($s['end_week'] * 7 * 86400) - 86400);
            if ($s['date_to'] < $today)       $s['live_status'] = 'Completed';
            elseif ($s['date_from'] > $today) $s['live_status'] = 'Upcoming';
            else                              $s['live_status'] = 'In_Progress';
        } else {
            $s['date_from'] = $s['date_to'] = null;
            $s['live_status'] = $s['status'];
        }
    }
    unset($s);

    return $schedules;
}

/**
 * A clinical student's full schedule (all unit blocks, grouped by day-row
 * into blocks server-side via SQL aggregation), each enriched with a
 * live status and lesson/assessment progress — same shape
 * app/student/my_rotation.php builds for its own display.
 *
 * Advances day-row statuses (Pending→Ongoing→Completed) based on today's
 * date first, same as the web page always has, so the mobile view is
 * never looking at stale status either.
 */
function getStudentScheduleWithLiveStatus(mysqli $conn, int $studentId): array
{
    $today = date('Y-m-d');

    $adv1 = $conn->prepare("
        UPDATE student_rotation_details
        SET status = 'Completed', updated_at = NOW()
        WHERE clinical_student_id = ? AND status IN ('Ongoing','Pending') AND rotation_date < ?
    ");
    $adv1->bind_param('is', $studentId, $today);
    $adv1->execute();
    $adv1->close();

    $adv2 = $conn->prepare("
        UPDATE student_rotation_details
        SET status = 'Ongoing', updated_at = NOW()
        WHERE clinical_student_id = ? AND status = 'Pending' AND rotation_date = ?
    ");
    $adv2->bind_param('is', $studentId, $today);
    $adv2->execute();
    $adv2->close();

    $stmt = $conn->prepare("
        SELECT
            srd.unit_id, srd.unit_name, srd.supervisor_name, srd.sequence_order,
            MIN(srd.rotation_date) AS date_from,
            MAX(srd.rotation_date) AS date_to,
            COUNT(srd.id)          AS total_days,
            SUM(CASE WHEN srd.status = 'Completed' THEN 1 ELSE 0 END) AS done_days,
            SUM(CASE WHEN srd.status = 'Ongoing'   THEN 1 ELSE 0 END) AS active_days,
            MAX(CASE WHEN srd.status = 'Ongoing'   THEN 3
                     WHEN srd.status = 'Pending'   THEN 2
                     WHEN srd.status = 'Completed' THEN 1
                     ELSE 0 END) AS status_rank,
            cr.id AS rotation_id, cr.batch_name, cr.start_date AS batch_start, cr.end_date AS batch_end,
            COUNT(DISTINCT cl.id) AS lesson_count,
            MAX(cl.submitted_at)  AS lessons_submitted_at,
            MAX(CASE WHEN ca.id IS NOT NULL THEN 1 ELSE 0 END) AS is_assessed,
            MAX(ca.grade) AS assessment_grade,
            MAX(ca.percentage_score) AS assessment_pct
        FROM student_rotation_details srd
        JOIN clinical_rotations cr ON srd.clinical_rotation_id = cr.id
        LEFT JOIN clinical_lessons cl
               ON cl.clinical_student_id = srd.clinical_student_id
              AND cl.clinical_rotation_id = srd.clinical_rotation_id
              AND cl.unit_id = srd.unit_id
        LEFT JOIN clinical_assessments ca
               ON ca.clinical_student_id = srd.clinical_student_id
              AND ca.clinical_rotation_id = srd.clinical_rotation_id
              AND ca.unit_id = srd.unit_id
              AND ca.eval_status IN ('submitted','locked')
        WHERE srd.clinical_student_id = ? AND srd.status != 'Cancelled'
        GROUP BY srd.unit_id, srd.unit_name, srd.supervisor_name, srd.sequence_order,
                 cr.id, cr.batch_name, cr.start_date, cr.end_date
        ORDER BY srd.sequence_order ASC, date_from ASC
    ");
    $stmt->bind_param('i', $studentId);
    $stmt->execute();
    $raw = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $stmt->close();

    foreach ($raw as &$b) {
        if ((int)$b['status_rank'] === 3)  $b['live'] = 'Ongoing';
        elseif ($b['date_to'] < $today)    $b['live'] = 'Completed';
        elseif ($b['date_from'] > $today)  $b['live'] = 'Upcoming';
        else                               $b['live'] = 'Ongoing';
        $b['progress_pct'] = $b['total_days'] > 0 ? round(($b['done_days'] / $b['total_days']) * 100) : 0;
        $b['has_lessons']  = $b['lesson_count'] >= 10;
    }
    unset($b);

    return $raw;
}

/** Groups getStudentScheduleWithLiveStatus()'s flat rows by rotation batch — same grouping my_rotation.php displays by. */
function groupStudentScheduleByBatch(array $rows): array
{
    $byBatch = [];
    foreach ($rows as $b) {
        $key = $b['rotation_id'];
        if (!isset($byBatch[$key])) {
            $byBatch[$key] = [
                'rotation_id' => $key,
                'batch_name'  => $b['batch_name'],
                'batch_start' => $b['batch_start'],
                'batch_end'   => $b['batch_end'],
                'units'       => [],
            ];
        }
        $byBatch[$key]['units'][] = $b;
    }
    return array_values($byBatch);
}

/** The student's final assessment, if one has been recorded — same lookup my_rotation.php does. */
function getStudentFinalAssessment(mysqli $conn, int $studentId): ?array
{
    $stmt = $conn->prepare("
        SELECT final_grade, final_verdict, average_percentage
        FROM clinical_final_assessments
        WHERE clinical_student_id = ? LIMIT 1
    ");
    $stmt->bind_param('i', $studentId);
    $stmt->execute();
    $row = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    return $row ?: null;
}
