<?php
/**
 * ZERTI REST API (zerti/v1) — grids and shop order mutations.
 */

if (!defined('ABSPATH')) {
    exit;
}

/**
 * @return void
 */
function zerti_register_rest_routes(): void
{
    register_rest_route(
        'zerti/v1',
        '/shop-orders',
        [
            'methods' => WP_REST_Server::READABLE,
            'callback' => 'zerti_rest_shop_orders_grid',
            'permission_callback' => 'zerti_rest_permission_shop_orders_grid',
            'args' => zerti_rest_shop_orders_grid_args(),
        ]
    );

    register_rest_route(
        'zerti/v1',
        '/customers',
        [
            'methods' => WP_REST_Server::READABLE,
            'callback' => 'zerti_rest_customers_grid',
            'permission_callback' => 'zerti_rest_permission_customers_grid',
            'args' => zerti_rest_customers_grid_args(),
        ]
    );

    register_rest_route(
        'zerti/v1',
        '/payments',
        [
            'methods' => WP_REST_Server::READABLE,
            'callback' => 'zerti_rest_payments_grid',
            'permission_callback' => 'zerti_rest_permission_payments_grid',
            'args' => zerti_rest_payments_grid_args(),
        ]
    );

    register_rest_route(
        'zerti/v1',
        '/products',
        [
            'methods' => WP_REST_Server::READABLE,
            'callback' => 'zerti_rest_products_grid',
            'permission_callback' => 'zerti_rest_permission_products_grid',
            'args' => zerti_rest_products_grid_args(),
        ]
    );

    register_rest_route(
        'zerti/v1',
        '/shop-orders/(?P<id>[\d]+)/status',
        [
            'methods' => 'PATCH',
            'callback' => 'zerti_rest_shop_order_update_status',
            'permission_callback' => 'zerti_rest_permission_shop_order_status',
            'args' => [
                'id' => [
                    'required' => true,
                    'type' => 'integer',
                    'minimum' => 1,
                ],
                'status' => [
                    'required' => true,
                    'type' => 'string',
                ],
            ],
        ]
    );

    register_rest_route(
        'zerti/v1',
        '/home-stats',
        [
            'methods' => WP_REST_Server::READABLE,
            'callback' => 'zerti_rest_home_stats',
            'permission_callback' => 'zerti_rest_permission_home_stats',
            'args' => [
                'days' => [
                    'type' => 'integer',
                    'default' => 30,
                    'minimum' => 7,
                    'maximum' => 90,
                ],
            ],
        ]
    );
}

add_action('rest_api_init', 'zerti_register_rest_routes');

/**
 * @return array<string, array<string, mixed>>
 */
function zerti_rest_shop_orders_grid_args(): array
{
    return [
        'start' => ['type' => 'integer', 'default' => 0, 'minimum' => 0],
        'limit' => ['type' => 'integer', 'default' => 50, 'minimum' => 1, 'maximum' => 100],
        'search' => ['type' => 'string', 'default' => ''],
        'sort_model' => ['type' => 'string', 'default' => ''],
        'filter_model' => ['type' => 'string', 'default' => ''],
    ];
}

/**
 * @return array<string, array<string, mixed>>
 */
function zerti_rest_customers_grid_args(): array
{
    return [
        'start' => ['type' => 'integer', 'default' => 0, 'minimum' => 0],
        'limit' => ['type' => 'integer', 'default' => 50, 'minimum' => 1, 'maximum' => 100],
        'search' => ['type' => 'string', 'default' => ''],
        'sort_model' => ['type' => 'string', 'default' => ''],
    ];
}

/**
 * @return array<string, array<string, mixed>>
 */
function zerti_rest_payments_grid_args(): array
{
    return [
        'start' => ['type' => 'integer', 'default' => 0, 'minimum' => 0],
        'limit' => ['type' => 'integer', 'default' => 50, 'minimum' => 1, 'maximum' => 100],
        'search' => ['type' => 'string', 'default' => ''],
        'sort_model' => ['type' => 'string', 'default' => ''],
        'filter_model' => ['type' => 'string', 'default' => ''],
        'payments_scope' => ['type' => 'string', 'default' => ''],
    ];
}

/**
 * @return array<string, array<string, mixed>>
 */
function zerti_rest_products_grid_args(): array
{
    return [
        'start' => ['type' => 'integer', 'default' => 0, 'minimum' => 0],
        'limit' => ['type' => 'integer', 'default' => 50, 'minimum' => 1, 'maximum' => 100],
        'search' => ['type' => 'string', 'default' => ''],
        'sort_model' => ['type' => 'string', 'default' => ''],
        'stock_filter' => ['type' => 'string', 'default' => ''],
    ];
}

function zerti_rest_permission_shop_orders_grid(): bool
{
    return zerti_user_can_access_tab('shop') && zerti_user_can_view_shop_orders_grid();
}

function zerti_rest_permission_customers_grid(): bool
{
    return zerti_user_can_access_tab('customers') && zerti_user_can_view_customers_grid();
}

function zerti_rest_permission_payments_grid(): bool
{
    return zerti_user_can_access_tab('financial') && zerti_user_can_view_payments_grid();
}

function zerti_rest_permission_products_grid(): bool
{
    return zerti_user_can_access_tab('inventory') && zerti_user_can_view_products_grid();
}

/**
 * @param WP_REST_Request $request
 */
function zerti_rest_permission_shop_order_status(WP_REST_Request $request): bool
{
    $order_id = (int) $request['id'];

    return $order_id > 0
        && zerti_user_can_access_tab('shop')
        && zerti_user_can_view_shop_order($order_id)
        && current_user_can('edit_shop_order', $order_id);
}

function zerti_rest_permission_home_stats(): bool
{
    return zerti_user_can_access_tab('home');
}

/**
 * @param WP_REST_Request $request
 * @return WP_REST_Response|WP_Error
 */
function zerti_rest_shop_orders_grid(WP_REST_Request $request)
{
    $result = zerti_fetch_shop_orders_grid($request->get_params());
    if (is_wp_error($result)) {
        return $result;
    }

    return new WP_REST_Response($result, 200);
}

/**
 * @param WP_REST_Request $request
 * @return WP_REST_Response|WP_Error
 */
function zerti_rest_customers_grid(WP_REST_Request $request)
{
    $result = zerti_fetch_customers_grid($request->get_params());
    if (is_wp_error($result)) {
        return $result;
    }

    return new WP_REST_Response($result, 200);
}

/**
 * @param WP_REST_Request $request
 * @return WP_REST_Response|WP_Error
 */
function zerti_rest_payments_grid(WP_REST_Request $request)
{
    $result = zerti_fetch_payments_grid($request->get_params());
    if (is_wp_error($result)) {
        return $result;
    }

    return new WP_REST_Response($result, 200);
}

/**
 * @param WP_REST_Request $request
 * @return WP_REST_Response|WP_Error
 */
function zerti_rest_products_grid(WP_REST_Request $request)
{
    $result = zerti_fetch_products_grid($request->get_params());
    if (is_wp_error($result)) {
        return $result;
    }

    return new WP_REST_Response($result, 200);
}

/**
 * @param WP_REST_Request $request
 * @return WP_REST_Response|WP_Error
 */
function zerti_rest_shop_order_update_status(WP_REST_Request $request)
{
    $order_id = (int) $request['id'];
    $status = sanitize_key((string) $request->get_param('status'));
    if ($status === '') {
        return new WP_Error('zerti_invalid_status', __('No status selected.', 'zerti'), ['status' => 400]);
    }

    $allowed = zerti_wc_order_status_choices();
    if (!isset($allowed[$status])) {
        return new WP_Error('zerti_invalid_status', __('Selected status is not allowed.', 'zerti'), ['status' => 400]);
    }

    if (!function_exists('wc_get_order')) {
        return new WP_Error('zerti_wc_missing', 'woocommerce_missing', ['status' => 400]);
    }

    $order = wc_get_order($order_id);
    if (!is_a($order, 'WC_Order')) {
        return new WP_Error('zerti_not_found', __('Order not found.', 'zerti'), ['status' => 404]);
    }

    if ($order->get_status() === $status) {
        return new WP_REST_Response([
            'message' => __('Order status unchanged.', 'zerti'),
            'status' => $status,
            'statusLabel' => zerti_wc_order_status_label_fa($status),
        ], 200);
    }

    $order->update_status($status, __('Status changed from ZERTI panel', 'zerti'), true);

    return new WP_REST_Response([
        'message' => __('Order status updated.', 'zerti'),
        'status' => $status,
        'statusLabel' => zerti_wc_order_status_label_fa($status),
    ], 200);
}

/**
 * @param WP_REST_Request $request
 * @return WP_REST_Response|WP_Error
 */
function zerti_rest_home_stats(WP_REST_Request $request)
{
    if (!class_exists('WooCommerce') || !function_exists('wc_get_orders')) {
        return new WP_Error('zerti_wc_missing', 'woocommerce_missing', ['status' => 400]);
    }

    require_once dirname(__DIR__) . '/zerti-wc-home-stats.php';
    $days = (int) $request->get_param('days');
    $bundle = zerti_wc_home_get_dashboard_bundle($days);

    return new WP_REST_Response($bundle, 200);
}
