<?php
declare(strict_types=1);

require_once dirname(__DIR__) . '/lib/tenant.php';

if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}
if (empty($_SESSION['admin_logged_in'])) {
    json_response(['ok' => false, 'error' => 'Unauthorized'], 401);
}

$tenantId = current_tenant_id();

try {
    $order = json_decode((string) ($_POST['order'] ?? '[]'), true);
    if (!is_array($order)) {
        json_response(['ok' => false, 'error' => 'Invalid order'], 400);
    }
    $stmt = db()->prepare('UPDATE services SET display_order = ? WHERE id = ? AND tenant_id = ?');
    foreach (array_values($order) as $i => $id) {
        $stmt->execute([$i + 1, (int) $id, $tenantId]);
    }
    json_response(['ok' => true]);
} catch (Throwable $e) {
    json_response(['ok' => false, 'error' => $e->getMessage()], 400);
}
