<?php

namespace BWDK\Integrations\Digify;

use BWDK\Support\Constant;
use BWDK\Support\WooCompatibility;
use WC_Order;
use WC_Order_Item_Product;

class Client
{

    protected $base_url;
    protected $apiKey;
    protected $timeout;

    public function __construct(
         $endpoint = null,
         $apiKey = null,
         $timeout = 10
    ) {

        $this->base_url = $endpoint ?: (get_option(Constant::BWDK_OPTION_NAME)["api"]["endpoint"]);
        $this->apiKey   = $apiKey   ?: (get_option(Constant::BWDK_OPTION_NAME)["api"]["api-key"]);

    }
    public function verifyOrder($order,$order_uuid)
    {
        $merchant_unique_id=$order->get_meta(Constant::META_BWDK_WOO_ORDER_UUID);
        $response = wp_remote_post($this->base_url . 'orders/api/v1/manager/'.$order_uuid.'/verify/', [
            'method'      => 'POST',
            'headers'     => [
                'Authorization' =>  $this->apiKey,
                'Content-Type'  => 'application/json',
            ],
            'body'        => wp_json_encode(["merchant_unique_id"=>$merchant_unique_id], JSON_UNESCAPED_UNICODE),
            'timeout'     => $this->timeout,
            'data_format' => 'body',
        ]);


        if (is_wp_error($response)) {
            return false;
        }

        $code = (int) wp_remote_retrieve_response_code($response);
        $body_raw = wp_remote_retrieve_body($response);
        $body = json_decode($body_raw, true);


        if ($code==200){
            return $body;
        }

        return false;


    }
    public function refundOrder($order_uuid)
    {
        $response = wp_remote_post($this->base_url . 'orders/api/v1/manager/'.$order_uuid.'/refund/', [
            'method'      => 'POST',
            'headers'     => [
                'Authorization' =>  $this->apiKey,
                'Content-Type'  => 'application/json',
            ],
            'timeout'     => $this->timeout,
            'data_format' => 'body',
        ]);


        if (is_wp_error($response)) {
            return false;
        }

        $code = (int) wp_remote_retrieve_response_code($response);
        $body_raw = wp_remote_retrieve_body($response);
        $body = json_decode($body_raw, true);

        if ($code==200 || $code==400){
            return $body;
        }


        return false;


    }
    public function createRemoteOrder($order): array
    {

        $payload = $this->buildPayload($order);


        $response = wp_remote_post($this->base_url . 'orders/api/v1/create-order/', [
            'method'      => 'POST',
            'headers'     => [
                'Authorization' =>  $this->apiKey,
                'Content-Type'  => 'application/json',
            ],
            'body'        => wp_json_encode($payload, JSON_UNESCAPED_UNICODE),
            'timeout'     => $this->timeout,
            'data_format' => 'body',
        ]);


        if (is_wp_error($response)) {
            $order->delete();
            return ['ok' => false, 'code' => 0, 'error' => $response->get_error_message()];
        }

        $code = (int) wp_remote_retrieve_response_code($response);
        $body_raw = wp_remote_retrieve_body($response);
        $body = json_decode($body_raw, true);



        if ($code >= 200 && $code < 300 && is_array($body)) {


            return [
                'ok'              => true,
                'code'            => $code,
                'order_start_url'=> $body['order_start_url'] ?? null,
                'order_uuid'      => $body['order_uuid'] ?? null,
                'raw'             => $body,
            ];
        }


        $order->delete();
        return ['ok' => false, 'code' => $code, 'error' => $body_raw ?: ('HTTP '.$code)];
    }
    public function merchantsAuthStatus($apiKey)
    {
        $response = wp_remote_get($this->base_url . 'merchants/api/v1/auth/status', [
            'headers'     => [
                'Authorization' =>  $apiKey,
                'Content-Type'  => 'application/json',
            ],
            'timeout'     => $this->timeout,
            'data_format' => 'body',
        ]);


        if (is_wp_error($response)) {
            return false;
        }

        $code = (int) wp_remote_retrieve_response_code($response);
        $body_raw = wp_remote_retrieve_body($response);
        $body = json_decode($body_raw, true);
        $is_authenticated=$body["is_authenticated"]??false;

        return $is_authenticated;
    }
    public function orderGetStatus($order_uuid): array
    {



        $response = wp_remote_get($this->base_url.'orders/api/v1/manager/'.$order_uuid.'/', [
            'headers'     => [
                'Authorization' => $this->apiKey,
                'Content-Type'  => 'application/json',
            ],
            'timeout'     => $this->timeout,
        ]);

        if (is_wp_error($response)) {
            return ['ok' => false, 'code' => 0, 'error' => $response->get_error_message()];
        }

        $code = (int) wp_remote_retrieve_response_code($response);
        $body_raw = wp_remote_retrieve_body($response);
        $body = json_decode($body_raw, true);

        if ($code >= 200 && $code < 300 && is_array($body)) {

            return [
                'ok'              => true,
                'code'            => $code,
                'raw'             => $body,
            ];
        }

        return [
            'ok'              => false,
            'code'            => $code,
            'raw'             => $body,
        ];
    }



    protected function buildPayload($order): array
    {
        $items = [];

        foreach ($order->get_items('line_item') as $item) {

            if (!$item instanceof WC_Order_Item_Product) continue;


            $product = $item->get_product();
            $qty           = max(1, (int) $item->get_quantity());
            $line_subtotal = WooCompatibility::convert_to_BWDK_currency((float) $item->get_subtotal());
            $line_total    = WooCompatibility::convert_to_BWDK_currency((float) $item->get_total());

            $options = [];
            if ( $product ) {
                foreach ( $item->get_meta_data() as $meta ) {
                    $raw_key   = $meta->key;
                    $raw_value=$meta->value;

                    if (
                        strpos($raw_key, 'pa_') === 0 ||
                        strpos($raw_key, 'attribute_pa_') === 0 ||
                        strpos($raw_key, 'attribute_') === 0
                    ) {
                        $tax = str_replace('attribute_', '', $raw_key);

                        $label = wc_attribute_label($tax, $product);


                        if ( taxonomy_exists($tax) ) {
                            $term = get_term_by('slug', (string) $raw_value, $tax);
                            $value_readable = $term ? $term->name : (string) $raw_value;
                        } else {
                            $value_readable = (string) $raw_value;
                        }





                        $options[] = [
                            "type_name"=>"other",
                            "name"=>$label." : ".$value_readable ?: $raw_key ." ".$value_readable,
                            "value"=>$label." : ".$value_readable ?: $raw_key ." ".$value_readable,
                            "is_color"=>false,

                        ];
                    }
                }
            }

            $items[] = [
                'name'            => $item->get_name(),
                'image_link'      =>$product->get_image_id()? wp_get_attachment_image_url($product->get_image_id()):"",
                'primary_amount'  => WooCompatibility::convert_to_BWDK_currency(round($qty ? $line_subtotal / $qty : $line_subtotal, 2)),
                'amount'          => WooCompatibility::convert_to_BWDK_currency(round($qty ? $line_total / $qty   : $line_total, 2)),
                'count'           => $qty,
                'discount_amount' => WooCompatibility::convert_to_BWDK_currency(round(max(0, $line_subtotal - $line_total), 2)),
                'tax_amount'      => WooCompatibility::convert_to_BWDK_currency(round((float) $item->get_total_tax(), 2)),
                'pure_data'       => new \stdClass(),
                'options'         => $options,
            ];








        }

        $callbackUrl = home_url( Constant::BWDK_CB_URL );
        $hold_minutes = get_option( 'woocommerce_hold_stock_minutes' )*60;


        $order->save();



        $payload = [
            'merchant_order_id' => $order->get_id(),
            'merchant_unique_id' =>  $order->get_meta(Constant::META_BWDK_WOO_ORDER_UUID),
            'reservation_expired_at' => time()+$hold_minutes,
            'main_amount'       =>  WooCompatibility::convert_to_BWDK_currency(round((float) $order->get_subtotal(), 2)),
            'final_amount'      =>  WooCompatibility::convert_to_BWDK_currency(round((float) $order->get_total(), 2)),
            'discount_amount'   =>  WooCompatibility::convert_to_BWDK_currency(round((float) $order->get_discount_total(), 2)),
            'tax_amount'        =>  WooCompatibility::convert_to_BWDK_currency(round((float) $order->get_total_tax(), 2)),
            'shipping_amount'   =>  WooCompatibility::convert_to_BWDK_currency(round((float) $order->get_shipping_total(), 2)),
            'loyalty_amount'    => 0.0,
            'callback_url'      => $callbackUrl,
            'items'             => $items,
        ];

        return apply_filters('bwdk/digify/payload', $payload, $order);
    }

}
