<?php

namespace Soft_Tehnica\Freya_Sync_Service\Services;

use WP_REST_Request;
use WP_REST_Response;

class RestService
{

    public function __construct()
    {
        $this->init();
    }

    public function registerRoutes(): void
    {
        register_rest_route( 'fss/v1', '/orders', [
            [
                'methods'             => 'GET',
                'callback'            => [$this, 'fsRestGetOrders'],
                'permission_callback' => fn () => true,
            ],
        ] );

        register_rest_route( 'fss/v1', '/version', [
            [
                'methods'             => 'GET',
                'callback'            => fn () => fsPluginVersion(),
                'permission_callback' => fn () => true,
            ],
        ] );

        register_rest_route( 'wc/v3/fss/v1', '/product-images', [
            [
                'methods'             => 'DELETE',
                'callback'            => [$this, 'deleteProductImage'],
                'permission_callback' => fn () => current_user_can( 'read_private_shop_orders' ),
            ],
        ] );
    }

    public function fsRestGetOrders(): void
    {
        $redirect_url = get_rest_url( null, 'wc/v3/orders' );

        if ( defined( 'FSS_DOCKER' ) ) {
            $redirect_url = str_replace( '://localhost', '://fss-wordpress', $redirect_url );
        }
        $redirect_url = add_query_arg( $_GET, $redirect_url );
        wp_redirect( $redirect_url );
    }

    public function deleteProductImage( WP_REST_Request $request ): WP_REST_Response
    {
        $params = $request->get_query_params();
        $id     = $params['id'] ?? null;

        if ( is_null( $id ) ) {
            return new WP_REST_Response( [
                'message' => 'No image id provided',
                'code'    => 'fss_bad_params',
                'data'    => null,
            ], 404 );
        }
        $id = intval( $id );

        wp_delete_attachment( $id, true );

        return new WP_REST_Response( [
            'message' => 'Image successfully deleted',
            'code'    => 'success',
            'data'    => null,
        ], 200, ['Content-Type' => 'application/json'] );
    }

    public function filterOrdersByMeta( array $args, $request ): array
    {
        if ( !isset( $request['freya-sync-processed'] ) ) {
            return $args;
        }

        $source_meta_query = [
            'key'   => 'freya-sync-processed',
            'value' => '',
        ];

        if ( isset( $args['meta_query'] ) ) {
            $args['meta_query']['relation'] = 'AND';
        } else {
            $args['meta_query'] = [];
        }
        $args['meta_query'][] = $source_meta_query;

        return $args;
    }

    /**
     * @hook http_request_args
     *
     * Dezactivează securitatea de URL-uri dacă URL-ul este de la FSS
     */
    public function product_image_fix( array $args, string $url ): array
    {
        $startWith = fsServiceUrl();

        if ( strlen( $startWith ) === 0 ) {
            return $args;
        }

        if ( str_starts_with( $url, $startWith ) ) {
            $args['reject_unsafe_urls'] = false;
        }

        return $args;
    }

    public function init(): void
    {
        add_filter( 'woocommerce_rest_shop_order_object_query', [$this, 'filterOrdersByMeta'], 0, 2 );
        add_action( 'rest_api_init', [$this, 'registerRoutes'] );
        add_action( 'http_request_args', [$this, 'product_image_fix'], 10, 2 );
    }
}
