<?php
// update_banner_sort.php
session_start();
if (!isset($_SESSION['admin'])) {
    echo json_encode(['status' => 'error', 'message' => 'Unauthorized']);
    exit;
}

require __DIR__ . '/../components/db_connect.php'; 

$data = json_decode(file_get_contents('php://input'), true);

if (isset($data['order']) && is_array($data['order'])) {
    try {
        $stmt = $conn->prepare("UPDATE banners SET sort_order = :sort_order WHERE id = :id");
        
        foreach ($data['order'] as $index => $id) {
            $stmt->execute([
                ':sort_order' => $index, 
                ':id' => (int)$id
            ]);
        }
        echo json_encode(['status' => 'success']);
    } catch (PDOException $e) {
        echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
    }
} else {
    echo json_encode(['status' => 'error', 'message' => 'Invalid data provided']);
}
?>