<?php

namespace BexioConnectorByHelvy;

/**
 * Admin API Synchronization
 *
 * @since 0.1.0
 */

defined('ABSPATH') || exit;

class AdminAPISynchronization
{

    public function __construct()
    {
        add_action('rest_api_init', function () {
            // Usage quota
            register_rest_route(BEXIO_CONNECTOR_BY_HELVY_REST_API_ROUTE, '/sync/usage-quota', array(
                'methods' => 'GET',
                'callback' => array($this, 'get_usage_quota'),
                'permission_callback' => array($this, 'get_permission')
            ));
            // Orders sync state
            register_rest_route(BEXIO_CONNECTOR_BY_HELVY_REST_API_ROUTE, '/orders/(?P<page>\d+)', array(
                'methods' => 'GET',
                'callback' => array($this, 'get_orders'),
                'args' => array(
                    'page' => array(
                        'validate_callback' => function ($param, $request, $key) {
                            return is_numeric($param);
                        }
                    ),
                ),
                'permission_callback' => array($this, 'get_permission')
            ));
            // Products sync state
            register_rest_route(BEXIO_CONNECTOR_BY_HELVY_REST_API_ROUTE, '/products/(?P<page>\d+)', array(
                'methods' => 'GET',
                'callback' => array($this, 'get_products'),
                'args' => array(
                    'page' => array(
                        'validate_callback' => function ($param, $request, $key) {
                            return is_numeric($param);
                        }
                    ),
                ),
                'permission_callback' => array($this, 'get_permission')
            ));
            // Sync product
            register_rest_route(BEXIO_CONNECTOR_BY_HELVY_REST_API_ROUTE, '/sync/product/(?P<product_id>\d+)', array(
                'methods' => 'POST',
                'callback' => array($this, 'sync_product'),
                'args' => array(
                    'product_id' => array(
                        'validate_callback' => function ($param, $request, $key) {
                            return is_numeric($param);
                        }
                    ),
                ),
                'permission_callback' => array($this, 'get_permission')
            ));
            // Sync order
            register_rest_route(BEXIO_CONNECTOR_BY_HELVY_REST_API_ROUTE, '/sync/order/(?P<order_id>\d+)', array(
                'methods' => 'POST',
                'callback' => array($this, 'sync_order'),
                'args' => array(
                    'order_id' => array(
                        'validate_callback' => function ($param, $request, $key) {
                            return is_numeric($param);
                        }
                    ),
                ),
                'permission_callback' => array($this, 'get_permission')
            ));
            register_rest_route(BEXIO_CONNECTOR_BY_HELVY_REST_API_ROUTE, '/sync/order/(?P<order_id>\d+)/payment', array(
                'methods' => 'POST',
                'callback' => array($this, 'sync_order_payment'),
                'args' => array(
                    'order_id' => array(
                        'validate_callback' => function ($param, $request, $key) {
                            return is_numeric($param);
                        }
                    ),
                ),
                'permission_callback' => array($this, 'get_permission')
            ));
            register_rest_route(BEXIO_CONNECTOR_BY_HELVY_REST_API_ROUTE, '/sync/order/(?P<order_id>\d+)/fulfillment', array(
                'methods' => 'POST',
                'callback' => array($this, 'sync_order_fulfillment'),
                'args' => array(
                    'order_id' => array(
                        'validate_callback' => function ($param, $request, $key) {
                            return is_numeric($param);
                        }
                    ),
                ),
                'permission_callback' => array($this, 'get_permission')
            ));
            // Delete metadata
            register_rest_route(BEXIO_CONNECTOR_BY_HELVY_REST_API_ROUTE, '/sync/order/(?P<order_id>\d+)/metadata', array(
                'methods' => 'DELETE',
                'callback' => array($this, 'delete_order_metadata'),
                'args' => array(
                    'order_id' => array(
                        'validate_callback' => function ($param, $request, $key) {
                            return is_numeric($param);
                        }
                    ),
                ),
                'permission_callback' => array($this, 'get_permission')
            ));
            // Get sync status
            register_rest_route(BEXIO_CONNECTOR_BY_HELVY_REST_API_ROUTE, '/sync/order/(?P<order_id>\d+)/status', array(
                'methods' => 'GET',
                'callback' => array($this, 'get_sync_status'),
                'args' => array(
                    'order_id' => array(
                        'validate_callback' => function ($param, $request, $key) {
                            return is_numeric($param);
                        }
                    ),
                ),
                'permission_callback' => array($this, 'get_permission')
            ));
            // Reset sync status
            register_rest_route(BEXIO_CONNECTOR_BY_HELVY_REST_API_ROUTE, '/sync/order/(?P<order_id>\d+)/reset', array(
                'methods' => 'POST',
                'callback' => array($this, 'reset_sync_status'),
                'args' => array(
                    'order_id' => array(
                        'validate_callback' => function ($param, $request, $key) {
                            return is_numeric($param);
                        }
                    ),
                ),
                'permission_callback' => array($this, 'get_permission')
            ));
            // Force unlock order
            register_rest_route(BEXIO_CONNECTOR_BY_HELVY_REST_API_ROUTE, '/sync/order/(?P<order_id>\d+)/unlock', array(
                'methods' => 'POST',
                'callback' => array($this, 'force_unlock_order'),
                'args' => array(
                    'order_id' => array(
                        'validate_callback' => function ($param, $request, $key) {
                            return is_numeric($param);
                        }
                    ),
                ),
                'permission_callback' => array($this, 'get_permission')
            ));
            // Fetch PDFs
            register_rest_route(BEXIO_CONNECTOR_BY_HELVY_REST_API_ROUTE, '/orders/(?P<order_id>\d+)/pdf', array(
                'methods' => 'GET',
                'callback' => array($this, 'get_order_pdf'),
                'args' => array(
                    'order_id' => array(
                        'validate_callback' => function ($param, $request, $key) {
                            return is_numeric($param);
                        }
                    ),
                ),
                'permission_callback' => array($this, 'get_permission')
            ));
            register_rest_route(BEXIO_CONNECTOR_BY_HELVY_REST_API_ROUTE, '/invoices/(?P<invoice_id>\d+)/pdf', array(
                'methods' => 'GET',
                'callback' => array($this, 'get_invoice_pdf'),
                'args' => array(
                    'invoice_id' => array(
                        'validate_callback' => function ($param, $request, $key) {
                            return is_numeric($param);
                        }
                    ),
                ),
                'permission_callback' => array($this, 'get_permission')
            ));
        });

        // Add custom meta fields to WooCommerce order admin (for debugging purposes only)
        // add_action('woocommerce_admin_order_data_after_order_details', array($this, 'display_bexio_meta_fields'));
        // add_action('woocommerce_process_shop_order_meta', array($this, 'save_bexio_meta_fields'));
    }

    /**
     * Display Bexio meta fields in the WooCommerce order admin interface.
     */
    public function display_bexio_meta_fields($order)
    {
        $meta_fields = [
            'bexio_order_id' => 'Bexio Order ID',
            'bexio_order_number' => 'Bexio Order Number',
            'bexio_invoice_id' => 'Bexio Invoice ID',
            'bexio_invoice_number' => 'Bexio Invoice Number',
            'bexio_delivery_id' => 'Bexio Delivery ID',
            'bexio_delivery_number' => 'Bexio Delivery Number',
            'bexio_payment_id' => 'Bexio Payment ID',
            'bexio_fulfillment_id' => 'Bexio Fulfillment ID',
        ];

        echo '<div class="bexio-meta-fields">';
        echo '<h4>' . __('Bexio Meta Fields', 'woocommerce') . '</h4>';
        foreach ($meta_fields as $meta_key => $label) {
            $value = get_post_meta($order->get_id(), AdminAPISettings::$prefix . $meta_key, true);
            echo '<p><strong>' . esc_html($label) . ':</strong> ';
            echo '<input type="text" name="' . esc_attr(AdminAPISettings::$prefix . $meta_key) . '" value="' . esc_attr($value) . '" style="width: 100%;">';
            echo '</p>';
        }
        echo '</div>';
    }

    /**
     * Save Bexio meta fields from the WooCommerce order admin interface.
     */
    public function save_bexio_meta_fields($post_id)
    {
        $meta_fields = [
            'bexio_order_id',
            'bexio_order_number',
            'bexio_invoice_id',
            'bexio_invoice_number',
            'bexio_delivery_id',
            'bexio_delivery_number',
            'bexio_payment_id',
            'bexio_fulfillment_id',
        ];

        foreach ($meta_fields as $meta_key) {
            if (isset($_POST[AdminAPISettings::$prefix . $meta_key])) {
                update_post_meta($post_id, AdminAPISettings::$prefix . $meta_key, sanitize_text_field($_POST[AdminAPISettings::$prefix . $meta_key]));
            }
        }
    }

    /*
    * Fetching orders.
    */
    public function get_orders($request)
    {
        $params = $request->get_params();

        if (isset($params['page']) && is_numeric($params['page'])) {
            $page = intval($params['page']);
            $per_page = 10;

            $args = array(
                'limit'        => $per_page,
                'page'         => $page,
                'orderby'      => 'date',
                'order'        => 'DESC',
                'paginate'     => true,
            );

            // Fetch orders
            $orders = [];
            $total_orders = 0;
            if (!empty($params['search'])) {
                $search = ltrim($params['search'], '#');
                $search = intval($search);
                $order = wc_get_order($search);
                if ($order) {
                    $orders = [$order];
                    $total_orders = 1;
                } else {
                    $orders = [];
                }
            } else {
                $results = wc_get_orders($args);
                $orders = $results->orders;
                $total_orders = $results->total;
            }

            $order_data = array();

            foreach ($orders as $order) {
                if ($order && $order instanceof \WC_Order) {
                    $formatted_date = gmdate('M d, Y', strtotime($order->get_date_created()));
                    $customer_name = $order->get_billing_first_name() . ' ' . $order->get_billing_last_name();

                    $order_data[] = array(
                        'id'       => $order->get_id(),
                        'date'     => $formatted_date,
                        'customer' => $customer_name,
                        'total'    => $order->get_total(),
                        'currency'    => $order->get_currency(),
                        'metaBexioInvoiceID'    => $order->get_meta(AdminAPISettings::$prefix . 'bexio_invoice_id') ?: get_post_meta($order->get_id(), AdminAPISettings::$prefix . 'bexio_invoice_id', true),
                        'metaBexioInvoiceNumber'    => $order->get_meta(AdminAPISettings::$prefix . 'bexio_invoice_number') ?: get_post_meta($order->get_id(), AdminAPISettings::$prefix . 'bexio_invoice_number', true),
                        'metaBexioOrderID'    => $order->get_meta(AdminAPISettings::$prefix . 'bexio_order_id') ?: get_post_meta($order->get_id(), AdminAPISettings::$prefix . 'bexio_order_id', true),
                        'metaBexioOrderNumber'    => $order->get_meta(AdminAPISettings::$prefix . 'bexio_order_number') ?: get_post_meta($order->get_id(), AdminAPISettings::$prefix . 'bexio_order_number', true),
                        'metaBexioPaymentID'    => $order->get_meta(AdminAPISettings::$prefix . 'bexio_payment_id') ?: get_post_meta($order->get_id(), AdminAPISettings::$prefix . 'bexio_payment_id', true),
                        'metaBexioFulfillmentID'    => $order->get_meta(AdminAPISettings::$prefix . 'bexio_fulfillment_id') ?: get_post_meta($order->get_id(), AdminAPISettings::$prefix . 'bexio_fulfillment_id', true),
                        // 'orderStatus'   => $order->get_status(),
                    );
                }
            }

            $response = array(
                'total' => $total_orders,
                'data'  => $order_data,
            );

            return new \WP_REST_Response($response, 200);
        }

        return new \WP_REST_Response(array('message' => 'Something went wrong!'), 403);
    }

    /*
    * Fetching products.
    */
    public function get_products($request)
    {
        $params = $request->get_params();

        if (isset($params['page']) && is_numeric($params['page'])) {
            $page = intval($params['page']);
            $per_page = 10;

            $args = array(
                'limit'        => $per_page,
                'page'         => $page,
                'orderby'      => 'name',
                'order'        => 'ASC',
                'paginate'     => true,
            );

            if (!empty($params['search'])) {
                $args['sku'] = esc_attr($params['search']);
            }

            // Fetch products
            $results = wc_get_products(array_merge($args, array('status' => 'publish')));
            $products = $results->products;
            $total_products = $results->total;

            $product_data = array();

            foreach ($products as $product) {
                if ($product && $product instanceof \WC_Product) {
                    $formatted_date = gmdate('M d, Y', strtotime($product->get_date_created()));

                    $product_info = array(
                        'id'        => $product->get_id(),
                        'parent_id' => $product->get_id(),
                        'date'      => $formatted_date,
                        'name'      => $product->get_name(),
                        'sku'       => $product->get_sku(),
                        'price'     => $product->get_price(),
                        'currency'  => get_woocommerce_currency(),
                        'metaBexioProductID' => $product->get_meta(AdminAPISettings::$prefix . 'bexio_product_id') ?: get_post_meta($product->get_id(), AdminAPISettings::$prefix . 'bexio_product_id', true),
                        'variants' => []
                    );

                    // If variable product, list variables within the product info
                    if ($product->is_type('variable')) {
                        $variations = $product->get_children();
                        foreach ($variations as $variation_id) {
                            $variation = wc_get_product($variation_id);
                            if ($variation && $variation instanceof \WC_Product_Variation) {
                                $product_info['variants'][] = array(
                                    'id'        => $variation->get_id(),
                                    'parent_id' => $product->get_id(),
                                    'date'      => $formatted_date,
                                    'name'      => $variation->get_title() . ' - ' . wc_get_formatted_variation($variation, true, false),
                                    'sku'       => $variation->get_sku(),
                                    'price'     => $variation->get_price(),
                                    'currency'  => get_woocommerce_currency(),
                                    'metaBexioProductID' => $variation->get_meta(AdminAPISettings::$prefix . 'bexio_product_id') ?: get_post_meta($variation->get_id(), AdminAPISettings::$prefix . 'bexio_product_id', true),
                                );
                            }
                        }
                    }

                    $product_data[] = $product_info;
                }
            }

            $response = array(
                'total' => $total_products,
                'data'  => $product_data,
            );

            return new \WP_REST_Response($response, 200);
        }

        return new \WP_REST_Response(array('message' => 'Something went wrong!'), 403);
    }

    /*
    * Retrieve the current usage quota
    */
    public function get_usage_quota($request)
    {
        $res = API::instance()->get_usage_quota();
        return new \WP_REST_Response($res);
    }

    /*
    * Sync the given product (either simple product or variation) to bexio.
    */
    public function sync_product($request)
    {
        // Manual UI trigger: an admin is waiting on this AJAX call, so allow one retry on
        // broker timeouts (the inline order-lifecycle path keeps retries off).
        API::instance()->set_allow_retry(true);
        $params = $request->get_params();
        if (!isset($params['product_id']) && !is_numeric($params['product_id'])) {
            new \WP_REST_Response(array('message' => 'Missing order ID'), 403);
        }
        
        $product_id = intval($params['product_id']);

        $product = wc_get_product($product_id);
        if (!$product) {
            return new \WP_REST_Response(array('message' => 'Product not found'), 404);
        }

        $res = WCToBexio::instance()->sync_product($product, true);
        return new \WP_REST_Response($res);
    }

    /*
    * Sync the given order to bexio.
    */
    public function sync_order($request)
    {
        // Manual UI trigger: an admin is waiting on this AJAX call, so allow one retry on
        // broker timeouts (the inline order-lifecycle path keeps retries off).
        API::instance()->set_allow_retry(true);
        $params = $request->get_params();
        if (!isset($params['order_id']) && !is_numeric($params['order_id'])) {
            return new \WP_REST_Response(array('message' => 'Missing order ID'), 403);
        }

        $order_id = intval($params['order_id']);
        $order = wc_get_order($order_id);
        if (!$order) {
            return new \WP_REST_Response(array('message' => 'Order not found'), 404);
        }

        // Run the comprehensive sync workflow synchronously for manual trigger
        $results = [];
        
        // 1. Sync order to Bexio
        $result = WCToBexio::instance()->sync_order($order, true);
        if ($result instanceof \WP_Error) {
            $status = 400;
            $data = $result->get_error_data();
            if (is_array($data) && isset($data['status_code'])) {
                $status = $data['status_code'];
            }
            return new \WP_REST_Response([
                'error' => true,
                'code' => $result->get_error_code(),
                'message' => $result->get_error_message(),
                'data' => $data,
            ], $status);
        }
        $results['order'] = $result;

        // Re-fetch order to get updated meta
        $order = wc_get_order($order_id);

        // 2. Create delivery note
        $result = WCToBexio::instance()->sync_order_create_delivery($order_id);
        if ($result instanceof \WP_Error) {
            $results['delivery_error'] = $result->get_error_message();
        } else {
            $results['delivery'] = $result;
        }

        // Re-fetch order
        $order = wc_get_order($order_id);

        // 3. Create invoice
        $result = WCToBexio::instance()->sync_order_create_invoice($order_id);
        if ($result instanceof \WP_Error) {
            $results['invoice_create_error'] = $result->get_error_message();
        } else {
            $results['invoice'] = $result;
        }

        // Re-fetch order
        $order = wc_get_order($order_id);

        // 4. Issue invoice if order status allows
        $bexio_invoice_id = get_post_meta($order->get_id(), AdminAPISettings::$prefix . 'bexio_invoice_id', true);
        if ($bexio_invoice_id) {
            $result = WCToBexio::instance()->sync_order_issue_invoice($order_id);
            if ($result instanceof \WP_Error) {
                $results['invoice_issue_error'] = $result->get_error_message();
            } else {
                $results['invoice_issued'] = $result;
            }
        }

        // Re-fetch order
        $order = wc_get_order($order_id);

        // 5. Sync payment if order is paid
        if ($order->is_paid()) {
            $result = WCToBexio::instance()->sync_order_payment($order, true);
            if ($result instanceof \WP_Error) {
                $results['payment_error'] = $result->get_error_message();
            } else {
                $results['payment'] = $result;
            }
        }

        // Re-fetch order
        $order = wc_get_order($order_id);

        // 6. Sync fulfillment if order status allows
        $result = WCToBexio::instance()->sync_order_fulfillment($order, true);
        if ($result instanceof \WP_Error) {
            $results['fulfillment_error'] = $result->get_error_message();
        } else {
            $results['fulfillment'] = $result;
        }

        return new \WP_REST_Response($results);
    }

    /*
    * Sync the payment of the given order to bexio.
    */
    public function sync_order_payment($request)
    {
        // Manual UI trigger: an admin is waiting on this AJAX call, so allow one retry on
        // broker timeouts (the inline order-lifecycle path keeps retries off).
        API::instance()->set_allow_retry(true);
        $params = $request->get_params();
        if (!isset($params['order_id']) && !is_numeric($params['order_id'])) {
            return new \WP_REST_Response(array('message' => 'Missing order ID'), 403);
        }
        
        $order_id = intval($params['order_id']);
        $order = wc_get_order($order_id);
        if (!$order) {
            return new \WP_REST_Response(array('message' => 'Order not found'), 404);
        }

        $res = SyncManager::instance()->execute_sync_operation(
            'payment',
            $order_id,
            array(WCToBexio::instance(), 'sync_order_payment'),
            array($order, true) // Force sync
        );

        if ($res instanceof \WP_Error) {
            $status = 400;
            $data = $res->get_error_data();
            if (is_array($data) && isset($data['status_code'])) {
                $status = $data['status_code'];
            }
            return new \WP_REST_Response([
                'error' => true,
                'code' => $res->get_error_code(),
                'message' => $res->get_error_message(),
                'data' => $data,
            ], $status);
        }
        
        return new \WP_REST_Response($res);
    }

    /*
    * Sync the fulfillment of the given order to bexio.
    */
    public function sync_order_fulfillment($request)
    {
        // Manual UI trigger: an admin is waiting on this AJAX call, so allow one retry on
        // broker timeouts (the inline order-lifecycle path keeps retries off).
        API::instance()->set_allow_retry(true);
        $params = $request->get_params();
        if (!isset($params['order_id']) && !is_numeric($params['order_id'])) {
            return new \WP_REST_Response(array('message' => 'Missing order ID'), 403);
        }
        
        $order_id = intval($params['order_id']);
        $order = wc_get_order($order_id);
        if (!$order) {
            return new \WP_REST_Response(array('message' => 'Order not found'), 404);
        }

        $res = SyncManager::instance()->execute_sync_operation(
            'fulfillment',
            $order_id,
            array(WCToBexio::instance(), 'sync_order_fulfillment'),
            array($order, true) // Force sync
        );

        if ($res instanceof \WP_Error) {
            $status = 400;
            $data = $res->get_error_data();
            if (is_array($data) && isset($data['status_code'])) {
                $status = $data['status_code'];
            }
            return new \WP_REST_Response([
                'error' => true,
                'code' => $res->get_error_code(),
                'message' => $res->get_error_message(),
                'data' => $data,
            ], $status);
        }
        
        return new \WP_REST_Response($res);
    }

    /*
    * Delete metadata of the given order.
    */
    public function delete_order_metadata($request)
    {
        $params = $request->get_params();
        if (!isset($params['order_id']) && !is_numeric($params['order_id'])) {
            new \WP_REST_Response(array('message' => 'Missing order ID'), 403);
        }
        
        $order_id = intval($params['order_id']);
        $order = wc_get_order($order_id);

        // Delete Bexio-related meta data
        $order->delete_meta_data(AdminAPISettings::$prefix . 'bexio_order_id');
        $order->delete_meta_data(AdminAPISettings::$prefix . 'bexio_order_number');
        $order->delete_meta_data(AdminAPISettings::$prefix . 'bexio_invoice_id');
        $order->delete_meta_data(AdminAPISettings::$prefix . 'bexio_invoice_number');
        $order->delete_meta_data(AdminAPISettings::$prefix . 'bexio_delivery_id');
        $order->delete_meta_data(AdminAPISettings::$prefix . 'bexio_delivery_number');
        $order->delete_meta_data(AdminAPISettings::$prefix . 'bexio_payment_id');
        $order->delete_meta_data(AdminAPISettings::$prefix . 'bexio_payment_number');
        $order->delete_meta_data(AdminAPISettings::$prefix . 'bexio_fulfillment_id');
        $order->delete_meta_data(AdminAPISettings::$prefix . 'bexio_fulfillment_number');
        $order->save_meta_data();

        delete_post_meta($order_id, AdminAPISettings::$prefix . 'bexio_order_id');
        delete_post_meta($order_id, AdminAPISettings::$prefix . 'bexio_order_number');
        delete_post_meta($order_id, AdminAPISettings::$prefix . 'bexio_invoice_id');
        delete_post_meta($order_id, AdminAPISettings::$prefix . 'bexio_invoice_number');
        delete_post_meta($order_id, AdminAPISettings::$prefix . 'bexio_delivery_id');
        delete_post_meta($order_id, AdminAPISettings::$prefix . 'bexio_delivery_number');
        delete_post_meta($order_id, AdminAPISettings::$prefix . 'bexio_payment_id');
        delete_post_meta($order_id, AdminAPISettings::$prefix . 'bexio_payment_number');
        delete_post_meta($order_id, AdminAPISettings::$prefix . 'bexio_fulfillment_id');
        delete_post_meta($order_id, AdminAPISettings::$prefix . 'bexio_fulfillment_number');

        // Also delete mapping from local bexio_invoice_mappings table
        global $wpdb;
        $table_name = $wpdb->prefix . 'bexio_invoice_mappings';
        $wpdb->delete($table_name, array('order_id' => $order_id));

        // Also reset sync tracking metadata
        SyncManager::instance()->reset_sync_status($order_id);
        
        // Force release any locks for this order
        SyncManager::instance()->force_release_order_locks($order_id);

        return new \WP_REST_Response(["success" => true]);
    }

    /*
    * Retrieve the PDF of the given order.
    */
    public function get_order_pdf($request)
    {
        $params = $request->get_params();
        if (!isset($params['order_id']) && !is_numeric($params['order_id'])) {
            return new \WP_REST_Response(array('message' => 'Missing order ID'), 403);
        }
        
        $order_id = intval($params['order_id']);
        $pdf = API::instance()->get_order_pdf($order_id);
        if ($pdf instanceof \WP_Error) {
            return $pdf;
        }

        return new \WP_REST_Response($pdf);
    }

    /**
     * Retrieve the PDF of the given invoice
     */
    public function get_invoice_pdf($request) {
        $params = $request->get_params();
        if (!isset($params['invoice_id']) && !is_numeric($params['invoice_id'])) {
            return new \WP_REST_Response(array('message' => 'Missing order ID'), 403);
        }
        
        $invoice_id = intval($params['invoice_id']);
        $pdf = API::instance()->get_invoice_pdf($invoice_id);
        if ($pdf instanceof \WP_Error) {
            return $pdf;
        }

        return new \WP_REST_Response($pdf);
    }

    /**
     * Get sync status for an order
     */
    public function get_sync_status($request) {
        $params = $request->get_params();
        if (!isset($params['order_id']) || !is_numeric($params['order_id'])) {
            return new \WP_REST_Response(array('message' => 'Missing or invalid order ID'), 400);
        }
        
        $order_id = intval($params['order_id']);
        $sync_status = SyncManager::instance()->get_sync_status($order_id);
        
        return new \WP_REST_Response([
            'order_id' => $order_id,
            'sync_status' => $sync_status
        ]);
    }

    /**
     * Reset sync status for an order
     */
    public function reset_sync_status($request) {
        $params = $request->get_params();
        if (!isset($params['order_id']) || !is_numeric($params['order_id'])) {
            return new \WP_REST_Response(array('message' => 'Missing or invalid order ID'), 400);
        }
        
        $order_id = intval($params['order_id']);
        
        // Get operation types from request body if specified
        $body = $request->get_json_params();
        $operation_types = isset($body['operation_types']) ? $body['operation_types'] : null;
        
        SyncManager::instance()->reset_sync_status($order_id, $operation_types);
        
        return new \WP_REST_Response([
            'message' => 'Sync status reset successfully',
            'order_id' => $order_id,
            'operations_reset' => $operation_types ?: ['all']
        ]);
    }

    /**
     * Force unlock all locks for an order
     */
    public function force_unlock_order($request) {
        $params = $request->get_params();
        if (!isset($params['order_id']) || !is_numeric($params['order_id'])) {
            return new \WP_REST_Response(array('message' => 'Missing or invalid order ID'), 400);
        }
        
        $order_id = intval($params['order_id']);
        SyncManager::instance()->force_release_order_locks($order_id);
        
        return new \WP_REST_Response([
            'message' => 'All locks force released for order',
            'order_id' => $order_id
        ]);
    }

    /**
     * Permission Callback
     **/
    public function get_permission()
    {
        if (current_user_can('administrator') || current_user_can('manage_woocommerce')) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * Cloning is forbidden.
     */
    public function __clone()
    {
        _doing_it_wrong(__FUNCTION__, __('Cheatin&#8217; huh?'), BEXIO_CONNECTOR_BY_HELVY_VERSION);
    }
}
