<?php
// =============================================================
//  POST /api/v1/rotations/student_generate
//
//  Clinical/student rotation-generation write path, extracted into
//  app/clinical_rotation_generation_service.php (see that file's header
//  for the full extraction and correctness notes — in particular, this
//  endpoint enforces hard AI conflict blocking correctly, unlike the
//  desktop page, which has no such gate at all today, unless the caller
//  explicitly passes force_assign: true after reviewing the conflicts).
//
//  Request body:
//    {
//      "student_ids": [1,2,3],
//      "batch_name": "Sept 2026 Cohort A",
//      "start_date": "2026-09-01",
//      "preceptor_id": 12,                // optional
//      "rotation_notes": "",              // optional
//      "stagger_distribution": true,      // optional, default true
//      "unit_ids": [4,5,6],               // optional — default: every unit
//                                          //   assigned to the students' school(s)
//      "force_assign": false
//    }
//
//  Responses:
//    200 — assigned. data: { success_count, rotation_end_date,
//          ai_score_result, ai_conflicts, ai_sequence_warnings,
//          ai_anomalies, ai_cohort_warnings, sms_sent_count, sms_total_count }
//    409 — blocked by hard AI conflicts (force_assign not set).
//    422 — validation failure (no valid students, no assigned units, etc.)
// =============================================================

require_once __DIR__ . '/../_bootstrap.php';
require_once __DIR__ . '/../../../app/ai_clinical_rotation_engine.php';
require_once __DIR__ . '/../../../app/clinical_rotation_generation_service.php';
require_once __DIR__ . '/../../../include/account_helpers.php';
require_once __DIR__ . '/../../../services/VelstackServiceProvider.php';
require_once __DIR__ . '/../../../include/notification_queue.php';

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

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

$body = Api::body();

$studentIds = array_values(array_unique(array_map('intval', (array)($body['student_ids'] ?? []))));
$batchName  = trim((string)($body['batch_name'] ?? ''));
$startDate  = (string)($body['start_date'] ?? '');
$preceptorId = isset($body['preceptor_id']) && $body['preceptor_id'] !== null && $body['preceptor_id'] !== ''
    ? (int)$body['preceptor_id'] : null;
$rotationNotes = trim((string)($body['rotation_notes'] ?? ''));
$stagger = array_key_exists('stagger_distribution', $body) ? (bool)$body['stagger_distribution'] : true;
$unitIds = isset($body['unit_ids']) && is_array($body['unit_ids'])
    ? array_values(array_unique(array_map('intval', $body['unit_ids'])))
    : null;
$forceAssign = (bool)($body['force_assign'] ?? false);

if (empty($studentIds)) {
    Api::error(422, 'ValidationError', 'student_ids must be a non-empty array');
}
if ($batchName === '') {
    Api::error(422, 'ValidationError', 'batch_name is required');
}

$result = generateStudentRotationBatch(
    $conn,
    $account->getId(),
    $studentIds,
    $batchName,
    $startDate,
    $preceptorId,
    $rotationNotes,
    $stagger,
    $unitIds,
    $forceAssign
);

if ($result['blocked_by_ai']) {
    Api::error(409, 'BlockedByAiConflicts', $result['message'], [
        'ai_conflicts'         => $result['ai_conflicts'],
        'ai_score_result'      => $result['ai_score_result'],
        'ai_sequence_warnings' => $result['ai_sequence_warnings'],
        'ai_assigned_ids'      => $result['ai_assigned_ids'],
    ]);
}

if (!$result['ok']) {
    Api::error(422, 'AssignmentFailed', $result['message'] ?? 'Assignment failed.');
}

$permManager = new PermissionManager($conn);
$permManager->logAudit($account->getId(), 'assign_rotations', 'clinical_rotation', null, null, json_encode([
    'student_count' => $result['success_count'],
    'batch_name'    => $batchName,
]));

Api::success([
    'success_count'        => $result['success_count'],
    'rotation_end_date'    => $result['rotation_end_date'],
    'ai_score_result'      => $result['ai_score_result'],
    'ai_conflicts'         => $result['ai_conflicts'],
    'ai_sequence_warnings' => $result['ai_sequence_warnings'],
    'ai_anomalies'         => $result['ai_anomalies'],
    'ai_cohort_warnings'   => $result['ai_cohort_warnings'],
    'sms_sent_count'       => $result['sms_sent_count'],
    'sms_total_count'      => $result['sms_total_count'],
]);
