<?php

if (!defined('ABSPATH'))
    exit; // Exit if accessed directly

use AC_SYNC\Includes\Classes\Api\Action_Wear_Api_Route;
use AC_SYNC\Includes\Classes\Api\Action_Wear_API_Response as ApiResponse;
use AC_SYNC\Includes\Classes\Order\Action_Wear_Order_Sync as OrderSync;

$route = new Action_Wear_Api_Route("/sync_order");
$route->setMethods("POST");
$route->setCallback(function () {
    $response = new ApiResponse();

    $data = json_decode(file_get_contents("php://input"));

    if (!isset($data->order_id) || empty($data->order_id)) {
        $response->fail("Order ID is required");
        return $response->getResponse();
    }

    $order_id = intval($data->order_id);
    $destination_address_id = isset($data->destination_address_id) ? intval($data->destination_address_id) : null;
    if ($destination_address_id === 0) $destination_address_id = null;
    $result = OrderSync::syncOrder($order_id, $destination_address_id);

    if ($result['success']) {
        $response->success([
            'order_id' => $order_id,
            'result' => $result
        ], "Order synchronized successfully");
    } else {
        $response->fail($result['error'], [
            'order_id' => $order_id,
            'result' => $result
        ]);
    }

    return $response->getResponse();
});
$route->registerRoute();
