<?php
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/functions.php';
if ($_SERVER['REQUEST_METHOD'] !== 'POST') { http_response_code(405); echo json_encode(['success'=>false,'msg'=>'Method not allowed']); exit; }
if (!is_logged_in()) { http_response_code(403); echo json_encode(['success'=>false,'msg'=>'Unauthorized']); exit; }
$input = json_decode(file_get_contents('php://input'), true);
$order = $input['order'] ?? null;
if (!is_array($order)) { echo json_encode(['success'=>false,'msg'=>'Invalid payload']); exit; }
$db = get_db();
try {
    $db->beginTransaction();
    foreach ($order as $i => $id) {
        $stmt = $db->prepare('UPDATE slides SET display_order = :o WHERE id = :id');
        $stmt->execute([':o' => $i, ':id' => (int)$id]);
    }
    $db->commit();
    echo json_encode(['success'=>true]);
} catch (Exception $e) {
    if ($db->inTransaction()) $db->rollBack();
    echo json_encode(['success'=>false,'msg'=>$e->getMessage()]);
}
