<?php
// =============================================================
//  include/CheckinHelpers.php
//
//  The eligibility-check / duplicate-check / insert logic behind QR
//  self-check-in — extracted from checkin.php so it has exactly one
//  implementation whether it's reached by scanning the unit-display QR
//  code in a mobile browser (checkin.php) or by the Flutter app's camera
//  hitting api/v1/attendance/checkin_scan.php directly. Both callers are
//  still responsible for verifying the CheckinToken themselves first (see
//  include/CheckinToken.php) — these functions assume that's already done,
//  same as checkin.php's own flow order.
//
//  Split into a read-only eligibility check and a separate write, on
//  purpose: checkin.php's own header comment is explicit that a GET
//  request (a prefetching browser, a link preview) must never silently
//  mark someone present — only checkSelfCheckinEligibility() may run
//  before an explicit, confirmed action; recordSelfCheckin() is the only
//  function here that writes.
// =============================================================

/**
 * Read-only: is this (unit, user) pair eligible to check in right now, and
 * have they already done so today? Safe to call on a GET request.
 *
 * @param string $userTable 'rotation_nurses' | 'clinical_students'
 * @return array{eligible: bool, message: ?string, unit_name: ?string, already: bool, context: ?array}
 *   'context' carries whatever recordSelfCheckin() needs (rotation/schedule
 *   IDs, department) so it doesn't have to re-run the eligibility query.
 */
function checkSelfCheckinEligibility(mysqli $conn, string $userTable, int $userId, int $unitId): array
{
    if (!in_array($userTable, ['rotation_nurses', 'clinical_students'], true)) {
        return ['eligible' => false, 'message' => 'Self check-in is for rotation nurses and clinical students only.', 'unit_name' => null, 'already' => false, 'context' => null];
    }

    if ($userTable === 'clinical_students') {
        $elig = $conn->prepare("
            SELECT srd.clinical_rotation_id, u.unit_name
            FROM student_rotation_details srd
            JOIN units u ON srd.unit_id = u.id
            WHERE srd.clinical_student_id = ? AND srd.unit_id = ? AND srd.status = 'Ongoing'
            LIMIT 1
        ");
    } else {
        $elig = $conn->prepare("
            SELECT nrs.id AS schedule_id, nrs.nurse_rotation_id, nrs.unit_name, nrs.department_id, nrs.department_name
            FROM nurse_rotation_schedules nrs
            WHERE nrs.rotation_nurse_id = ? AND nrs.unit_id = ? AND nrs.status = 'In_Progress'
            LIMIT 1
        ");
    }
    $elig->bind_param('ii', $userId, $unitId);
    $elig->execute();
    $eligibility = $elig->get_result()->fetch_assoc();
    $elig->close();

    if (!$eligibility) {
        return ['eligible' => false, 'message' => "You're not currently scheduled at this unit. If this seems wrong, contact your supervisor.", 'unit_name' => null, 'already' => false, 'context' => null];
    }

    $unitName = $eligibility['unit_name'];
    $today    = date('Y-m-d');

    $dupCheck = $userTable === 'clinical_students'
        ? $conn->prepare('SELECT id FROM clinical_attendance WHERE clinical_student_id = ? AND unit_id = ? AND attendance_date = ?')
        : $conn->prepare('SELECT id FROM nurse_attendance WHERE rotation_nurse_id = ? AND unit_id = ? AND attendance_date = ?');
    $dupCheck->bind_param('iis', $userId, $unitId, $today);
    $dupCheck->execute();
    $already = (bool)$dupCheck->get_result()->fetch_assoc();
    $dupCheck->close();

    return [
        'eligible'  => true,
        'message'   => $already ? "You're already checked in at {$unitName} today." : null,
        'unit_name' => $unitName,
        'already'   => $already,
        'context'   => $eligibility,
    ];
}

/**
 * Writes the check-in row. Callers MUST have just confirmed
 * checkSelfCheckinEligibility() returned eligible=true, already=false, on
 * this same request (an explicit user action, not a bare page load).
 *
 * @param string $userTable 'rotation_nurses' | 'clinical_students'
 * @param array  $context   The 'context' array checkSelfCheckinEligibility() returned.
 */
function recordSelfCheckin(mysqli $conn, string $userTable, int $userId, int $unitId, string $unitName, array $context): array
{
    $today = date('Y-m-d');

    if ($userTable === 'clinical_students') {
        $ins = $conn->prepare("
            INSERT INTO clinical_attendance
                (clinical_student_id, clinical_rotation_id, unit_id, unit_name, attendance_date, status, marked_by, is_self_checkin)
            VALUES (?,?,?,?,?,'Present',NULL,1)
        ");
        $ins->bind_param('iiiss', $userId, $context['clinical_rotation_id'], $unitId, $unitName, $today);
    } else {
        $ins = $conn->prepare("
            INSERT INTO nurse_attendance
                (rotation_nurse_id, nurse_rotation_id, nurse_rotation_schedule_id, unit_id, unit_name, department_id, department_name, attendance_date, status, marked_by, is_self_checkin)
            VALUES (?,?,?,?,?,?,?,?,'Present',NULL,1)
        ");
        $ins->bind_param('iiiisiss',
            $userId, $context['nurse_rotation_id'], $context['schedule_id'], $unitId,
            $unitName, $context['department_id'], $context['department_name'], $today
        );
    }

    if ($ins->execute()) {
        $ins->close();
        return ['ok' => true, 'message' => "Checked in at {$unitName}. Have a great day!"];
    }

    error_log('Self check-in insert failed: ' . $ins->error);
    $ins->close();
    return ['ok' => false, 'message' => 'Could not record your check-in. Please tell your supervisor.'];
}
