<?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_orders_bulk");
$route->setMethods("POST");
$route->setCallback(function () {
    $response = new ApiResponse();

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

    // Support both legacy format { order_ids: [1,2,3] } and new format { orders: [{ order_id, destination_address_id }] }
    if (isset($data->orders) && is_array($data->orders) && !empty($data->orders)) {
        $orders = $data->orders;
        $results = OrderSync::syncOrdersBulk($orders);
    } elseif (isset($data->order_ids) && is_array($data->order_ids) && !empty($data->order_ids)) {
        $order_ids = array_map('intval', $data->order_ids);
        $results = OrderSync::syncOrdersBulk($order_ids);
    } else {
        $response->fail("Orders data is required");
        return $response->getResponse();
    }

    // Count successes and failures
    $success_count = 0;
    $failure_count = 0;
    foreach ($results as $result) {
        if ($result['success']) {
            $success_count++;
        } else {
            $failure_count++;
        }
    }

    $response->success([
        'results' => $results,
        'summary' => [
            'total' => count($order_ids),
            'success' => $success_count,
            'failed' => $failure_count
        ]
    ], "$success_count orders synced successfully, $failure_count failed");

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