<?php
// =============================================================
//  POST /api/v1/attendance/nurse_mark
//
//  Staff-facing roll-call submission — the mobile equivalent of
//  app/nurse_attendance.php's POST handler. Requires 'mark_attendance'.
//
//  Body: {
//    "attendance_date": "2026-08-16",
//    "unit_id": 19, "unit_name": "...", "department_id": 3, "department_name": "...",
//    "rotation_id": 101, "schedule_id": 55,
//    "records": [ { "nurse_id": 7, "status": "Present", "remarks": null }, ... ]
//  }
//
//  Only INSERTs — every record here is expected to come from GET
//  nurse_pending's list, which already excludes nurses with an existing
//  attendance row for the date/unit (see that endpoint's NOT EXISTS
//  clause), so there is no "already marked" case to update here. Editing
//  an already-marked record is app/nurse_attendance_history.php's job on
//  the web side and hasn't been ported to this API yet.
// =============================================================

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

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

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

$body = json_decode(file_get_contents('php://input'), true) ?? [];

$att_date        = trim((string)($body['attendance_date'] ?? ''));
$unit_id         = (int)($body['unit_id'] ?? 0);
$unit_name       = trim((string)($body['unit_name'] ?? ''));
$department_id   = isset($body['department_id']) ? (int)$body['department_id'] : null;
$department_name = isset($body['department_name']) ? trim((string)$body['department_name']) : null;
$rotation_id     = (int)($body['rotation_id'] ?? 0);
$schedule_id     = (int)($body['schedule_id'] ?? 0);
$records         = is_array($body['records'] ?? null) ? $body['records'] : [];

if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $att_date) || !$unit_id || !$unit_name || empty($records)) {
    Api::error(422, 'ValidationError', 'attendance_date, unit_id, unit_name, and at least one record are required');
}

const STATUSES = ['Present', 'Absent', 'Late', 'Excused'];

$saved     = 0;
$skipped   = [];
$accountId = $account->getId();

foreach ($records as $r) {
    $nurse_id = (int)($r['nurse_id'] ?? 0);
    $status   = (string)($r['status'] ?? '');
    $remark   = isset($r['remarks']) && trim((string)$r['remarks']) !== '' ? trim((string)$r['remarks']) : null;

    if (!$nurse_id || !in_array($status, STATUSES, true)) {
        $skipped[] = $r;
        continue;
    }

    // Belt-and-braces re-check (nurse_pending's NOT EXISTS already filters
    // this at read time, but the client's list could be stale by the time
    // this POST lands — e.g. two staff members marking the same unit).
    $check = $conn->prepare(
        'SELECT id FROM nurse_attendance WHERE rotation_nurse_id = ? AND unit_id = ? AND attendance_date = ?'
    );
    $check->bind_param('iis', $nurse_id, $unit_id, $att_date);
    $check->execute();
    $exists = $check->get_result()->fetch_assoc();
    $check->close();
    if ($exists) {
        $skipped[] = $r + ['reason' => 'already_marked'];
        continue;
    }

    $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, remarks, marked_by)
        VALUES (?,?,?,?,?,?,?,?,?,?,?)
    ');
    $ins->bind_param(
        'iiiisissssi',
        $nurse_id, $rotation_id, $schedule_id, $unit_id, $unit_name,
        $department_id, $department_name, $att_date, $status, $remark, $accountId
    );
    if ($ins->execute()) {
        $saved++;
    } else {
        $skipped[] = $r + ['reason' => 'db_error'];
    }
    $ins->close();
}

Api::success([
    'saved'   => $saved,
    'skipped' => $skipped,
]);
