<?php
if (!defined('ABSPATH'))
    exit;

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 as Order;
use AC_SYNC\Includes\Classes\Order\Action_Wear_Order_Sync as OrderSync;
use AC_SYNC\Includes\Classes\Api\Action_Wear_Api as Api;

$route = new Action_Wear_Api_Route("/preview_order_payload");
$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;

    $order = wc_get_order($order_id);
    if (!$order) {
        $response->fail("Order not found");
        return $response->getResponse();
    }

    $items = Order::getActionWearItems($order);
    if (empty($items)) {
        $response->fail("No ActionWear products found in order");
        return $response->getResponse();
    }

    $payload = OrderSync::buildPayload($order, $items, $destination_address_id);

    $apikey = get_option("_ACTIONWEAR_APIKEY");
    $url = Api::getBaseUrl() . '/customer_order';

    $response->success([
        'payload' => $payload,
        'url' => $url,
        'api_key' => $apikey ? substr($apikey, 0, 8) . '...' : '',
        'test_mode' => (bool) get_option('_ACTIONWEAR_ORDER_TEST_MODE', 0),
    ]);

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