<?php
require_once 'db/config.php';

session_start();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['order']) && is_array($_POST['order'])) {
        $ordered_ids = $_POST['order'];

        $pdo = db();
        $pdo->beginTransaction();

        try {
            foreach ($ordered_ids as $index => $id) {
                $sql = "UPDATE functions SET display_order = ? WHERE id = ?";
                $stmt = $pdo->prepare($sql);
                $stmt->execute([$index + 1, $id]);
            }
            $pdo->commit();
            header('Content-Type: application/json');
            echo json_encode(['success' => true, 'message' => 'Order updated successfully.']);
            exit();

        } catch (PDOException $e) {
            $pdo->rollBack();
            header('Content-Type: application/json');
            http_response_code(500);
            echo json_encode(['success' => false, 'message' => 'Error updating display order: ' . $e->getMessage()]);
            exit();
        }
    }
}

// Fallback for old form submission, though it's being deprecated
if (isset($_POST['ids']) && isset($_POST['display_order'])) {
    $ids = $_POST['ids'];
    $display_orders = $_POST['display_order'];

    if (count($ids) !== count($display_orders)) {
        $_SESSION['error_message'] = "Something went wrong. Please try again.";
        header("Location: functions.php");
        exit();
    }

    $pdo = db();
    $pdo->beginTransaction();

    try {
        for ($i = 0; $i < count($ids); $i++) {
            $sql = "UPDATE functions SET display_order = ? WHERE id = ?";
            $stmt = $pdo->prepare($sql);
            $stmt->execute([$display_orders[$i], $ids[$i]]);
        }
        $pdo->commit();
        $_SESSION['success_message'] = "Display order updated successfully.";
    } catch (PDOException $e) {
        $pdo->rollBack();
        $_SESSION['error_message'] = "Error updating display order: " . $e->getMessage();
    }

    header("Location: functions.php");
    exit();
}

http_response_code(400);
header('Content-Type: application/json');
echo json_encode(['success' => false, 'message' => 'Invalid request.']);
