<?php
// =============================================================
//  POST /api/v1/admin_allocations/school_unit_create
//
//  Wraps app/create_clinical_unit_assignment.php's own
//  'assign_school_unit' action — same duplicate-active-pair check, same
//  shift hardcoded to 'Full_Day' (the desktop form never collects a
//  shift for this feature despite the column supporting others).
//
//  school_unit_assignments carries a UNIQUE(school_name, unit_id) index
//  not scoped to is_active — the same gap found and fixed in
//  specialty_department_weeks (Section 5.2.2t / commit ff87da7). Fixed
//  here too, in both this endpoint and the desktop page it mirrors, by
//  reactivating a trashed row instead of inserting a duplicate.
//
//  Body: { "school_name": "UHAS", "unit_id": 5, "duration_value": 4, "duration_unit": "weeks" }
// =============================================================

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

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

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

$body = Api::body();
$schoolName = trim((string)($body['school_name'] ?? ''));
$unitId = (int)($body['unit_id'] ?? 0);
$durationValue = (int)($body['duration_value'] ?? 1);
$durationUnit = in_array($body['duration_unit'] ?? 'weeks', ['days', 'weeks', 'months'], true) ? $body['duration_unit'] : 'weeks';
const SHIFT = 'Full_Day';

if ($schoolName === '' || !$unitId || $durationValue < 1) {
    Api::error(422, 'ValidationError', 'School, Unit, and Duration are required');
}

$chk = $conn->prepare("SELECT id FROM school_unit_assignments WHERE LOWER(school_name) = LOWER(?) AND unit_id = ? AND is_active = 'Active'");
$chk->bind_param('si', $schoolName, $unitId);
$chk->execute();
$chk->store_result();
if ($chk->num_rows > 0) {
    $chk->close();
    Api::error(409, 'DuplicateAssignment', 'This unit is already assigned to this school');
}
$chk->close();

$userId = $account->getId();
$stmt = $conn->prepare("
    INSERT INTO school_unit_assignments
    (school_name, unit_id, duration_value, duration_unit, shift, created_by)
    VALUES (?, ?, ?, ?, ?, ?)
");
$shift = SHIFT;
$stmt->bind_param('siissi', $schoolName, $unitId, $durationValue, $durationUnit, $shift, $userId);

$newId = null;
try {
    $stmt->execute();
    $newId = $conn->insert_id;
    $stmt->close();
} catch (mysqli_sql_exception $e) {
    $stmt->close();
    if ($e->getCode() !== 1062) throw $e;

    $reactivate = $conn->prepare("
        UPDATE school_unit_assignments
        SET duration_value = ?, duration_unit = ?, shift = ?, is_active = 'Active',
            created_by = ?, updated_by = NULL, updated_at = NOW(),
            deleted_by = NULL, deleted_at = NULL
        WHERE LOWER(school_name) = LOWER(?) AND unit_id = ? AND is_active = 'Inactive'
    ");
    $reactivate->bind_param('issisi', $durationValue, $durationUnit, $shift, $userId, $schoolName, $unitId);
    if (!$reactivate->execute() || $reactivate->affected_rows === 0) {
        $reactivate->close();
        Api::error(409, 'DuplicateAssignment', 'This unit is already assigned to this school');
    }
    $reactivate->close();

    $idRow = $conn->prepare("SELECT id FROM school_unit_assignments WHERE LOWER(school_name) = LOWER(?) AND unit_id = ? AND is_active = 'Active'");
    $idRow->bind_param('si', $schoolName, $unitId);
    $idRow->execute();
    $newId = (int)($idRow->get_result()->fetch_assoc()['id'] ?? 0);
    $idRow->close();
}

$permManager = new PermissionManager($conn);
$permManager->logAudit($account->getId(), 'assign_school_unit', 'school_unit_assignments', $newId, null, json_encode(['school_name' => $schoolName, 'unit_id' => $unitId]));

Api::success(['id' => $newId], [], 201);
