<?php
declare(strict_types=1);
session_start();
require_once '../../config.php';
if (!isset($_SESSION['user_id'])) { http_response_code(401); echo json_encode(['success'=>false]); exit; }
header('Content-Type: application/json');
$conn = getDBConnection();
$paperId = (int) ($_POST['paper_id'] ?? 0);
$order = json_decode((string) ($_POST['order'] ?? '[]'), true);
if (!$conn instanceof mysqli || $paperId <= 0 || !is_array($order)) { echo json_encode(['success'=>false]); exit; }
$stmt = $conn->prepare("UPDATE exam_paper_questions SET order_no = ? WHERE paper_id = ? AND question_id = ?");
$position = 1;
foreach ($order as $questionId) {
    $qid = (int) $questionId;
    $stmt->bind_param('iii', $position, $paperId, $qid);
    $stmt->execute();
    $position++;
}
$stmt->close();
echo json_encode(['success'=>true]);
