<?php
// candidate/api/update_priority.php — Xắp xếp lại thứ tự nguyện vọng (insert-and-shift)
require_once __DIR__ . '/_guard.php';

$user_id = $_SESSION['user_id'];
$input = json_decode(file_get_contents('php://input'), true);
$app_id = $input['app_id'] ?? '';
$newPriority = intval($input['priority'] ?? 0);

if (!$app_id || $newPriority < 1) {
    echo json_encode(['success' => false, 'message' => 'Dữ liệu không hợp lệ']);
    exit;
}

$supabase = new DatabaseClient('service');

// 1. Lấy thông tin đợt tuyển sinh (đảm bảo hồ sơ thuộc user này)
$targetRes = $supabase->select('applications', "id=eq.{$app_id}&user_id=eq.{$user_id}&select=id,admission_period_id,priority");
if (empty($targetRes['data'])) {
    echo json_encode(['success' => false, 'message' => 'Không tìm thấy hồ sơ']);
    exit;
}
$targetApp = $targetRes['data'][0];
$period_id = $targetApp['admission_period_id'];

// 2. Lấy tất cả hồ sơ trong cùng đợt
$allRes = $supabase->select('applications', "user_id=eq.{$user_id}&admission_period_id=eq.{$period_id}&select=id,priority&order=priority.asc");
$allApps = ($allRes['code'] === 200) ? $allRes['data'] : [];

if (empty($allApps)) {
    echo json_encode(['success' => false, 'message' => 'Không tìm thấy hồ sơ trong đợt']);
    exit;
}

// 3. Insert-and-Shift
$others = array_values(array_filter($allApps, fn($a) => (string)$a['id'] !== (string)$app_id));
$maxPriority = count($allApps);
$newPriority = max(1, min($newPriority, $maxPriority));
array_splice($others, $newPriority - 1, 0, [['id' => $app_id, 'priority' => (int)($targetApp['priority'])]]);

// 4. Bulk update (Zero-Latency Pattern via RPC)
$priorityMap = [];
$updatesList = [];

foreach ($others as $idx => $app) {
    $assignedPriority = $idx + 1;
    $priorityMap[(string)$app['id']] = $assignedPriority;

    if ((int)($app['priority'] ?? 0) !== $assignedPriority) {
        $updatesList[] = [
            'id' => $app['id'],
            'priority' => $assignedPriority
        ];
    }
}

if (!empty($updatesList)) {
    // Thay thế RPC bulk_update bằng Transaction
    $supabase->beginTransaction();
    $rpcResCode = 200;
    $errDetail = '';

    foreach ($updatesList as $upd) {
        $res = $supabase->update('applications', 'id', $upd['id'], ['priority' => $upd['priority']]);
        if ($res['code'] !== 200) {
            $rpcResCode = $res['code'];
            $errDetail = isset($res['error']) ? $res['error'] : 'Unknown';
            break;
        }
    }

    if ($rpcResCode === 200) {
        $supabase->commit();
    } else {
        $supabase->rollBack();
        echo json_encode(['success' => false, 'message' => 'Lỗi cập nhật CSDL (' . $rpcResCode . ') Chi tiết: ' . $errDetail]);
        exit;
    }
}

echo json_encode(['success' => true, 'priority_map' => $priorityMap]);
