<?php

namespace WeDevs\DokanPro\Modules\RMA\Traits;

use WP_Error;

/**
* Trail Class for RMA
*/
trait RMACommon {

    /**
     * Transform conversation response
     *
     * @since 1.0.0
     *
     * @param array $request
     *
     * @return array
     */
    public function transform_request_conversation( array $request ): array {
        return apply_filters(
            'dokan_get_request_conversation_data',
            [
                'id'         => $request['id'],
                'from'       => $request['from'],
                'to'         => $request['to'],
                'message'    => $request['message'],
                'created_at' => $request['created_at'],
            ]
        );
    }

    /**
     * Transform warranty request items
     *
     * @since 1.0.0
     *
     * @param array $request
     *
     * @return array|WP_Error
     */
    public function transform_warranty_requests( array $request ) {
        $product_ids = explode( ',', $request['products'] );
        $quantities = explode( ',', $request['quantity'] );
        $item_ids = explode( ',', $request['item_id'] );
        $items = [];
        $order = wc_get_order( absint( $request['order_id'] ) );

        // Check if order exists
        if ( ! $order ) {
            return $this->transform_deleted_order_warranty_request( $request );
        }

        // Original logic for existing orders
        foreach ( $product_ids as $key => $product_id ) {
            $product   = wc_get_product( $product_id );
            $line_item = $order->get_item( absint( $item_ids[ $key ] ) );

            if ( $product ) {
                $items[] = [
                    'id'        => $line_item->get_variation_id() ? $line_item->get_variation_id() : $line_item->get_product_id(),
                    'title'     => $line_item->get_name(),
                    'thumbnail' => wp_get_attachment_url( $product->get_image_id() ),
                    'quantity'  => $quantities[ $key ],
                    'url'       => $product->get_permalink(),
                    'price'     => wc_format_decimal( $line_item->get_total() ) / $line_item->get_quantity(),
                    'item_id'   => $item_ids[ $key ],
                    'tax'       => wc_format_decimal( $line_item->get_total_tax() ) / $line_item->get_quantity(),
                ];
            }
        }

        $vendor = dokan()->vendor->get( $request['vendor_id'] );
        $customer = get_user_by( 'id', $request['customer_id'] );

        $reason_label = dokan_rma_refund_reasons( $request['reasons'] );
        if ( is_array( $reason_label ) || '' === $reason_label ) {
            $reason_label = esc_html__( 'No reason provided', 'dokan' );
        }

        $has_already_refund_request = false;
        if ( 'refund' === $request['type'] && dokan_pro()->refund->has_pending_request( $order->get_id() ) ) {
            $has_already_refund_request = true;
        }

        return apply_filters(
            'dokan_get_warranty_single_request_data',
            [
                'id'          => $request['id'],
                'order_id'    => $request['order_id'],
                'vendor'   => [
                    'store_id'   => $vendor->get_id(),
                    'store_name' => $vendor->get_shop_name(),
                    'store_url'  => $vendor->get_shop_url(),
                    'store_avatar' => $vendor->get_avatar(),
                    'store_banner' => $vendor->get_banner(),
                ],
                'customer' => [
                    'id'   => $customer->ID,
                    'name' => sprintf( '%s %s', $customer->first_name, $customer->last_name ),
                ],
                'type'             => $request['type'],
                'type_label'       => dokan_warranty_request_type( $request['type'] ),
                'status'           => $request['status'],
                'reasons'          => $request['reasons'],
                'reasons_label'    => $reason_label,
                'details'          => $request['details'],
                'note'             => $request['note'],
                'created_at'       => $request['created_at'],
                'items'            => $items,
                'is_order_deleted' => false,
                'is_refund_pending' => $has_already_refund_request,

            ]
        );
    }

    /**
     * Transform post request for rma settings
     *
     * @since 1.0.0
     *
     * @param array $request
     *
     * @return array
     */
    public function transform_rma_settings( array $request = [] ): array {
        $data = [];

        if ( ! empty( $request ) ) {
            $data = [
                'label'           => ! empty( $request['warranty_label'] ) ? $request['warranty_label'] : __( 'Warranty', 'dokan' ),
                'type'            => ! empty( $request['warranty_type'] ) ? $request['warranty_type'] : 'no_warranty',
                'policy'          => ! empty( $request['warranty_policy'] ) ? $request['warranty_policy'] : '',
                'reasons'         => ! empty( $request['warranty_reason'] ) ? $request['warranty_reason'] : [],
                'length'          => '',
                'length_value'    => '',
                'length_duration' => '',
                'addon_settings'  => [],
            ];

            if ( 'included_warranty' === $data['type'] ) {
                $data['length']          = $request['warranty_length'];
                $data['length_value']    = $request['warranty_length_value'];
                $data['length_duration'] = $request['warranty_length_duration'];
                $data['addon_settings']  = [];

                if ( 'lifetime' === $data['length'] ) {
                    $data['length_value']    = '';
                    $data['length_duration'] = '';
                }
            }

            if ( 'addon_warranty' === $data['type'] ) {
                $addon_settings = [];

                if ( ! empty( $request['warranty_addon_price'] ) ) {
                    foreach ( $request['warranty_addon_price'] as $key => $price ) {
                        $addon_settings[] = [
                            'price'    => wc_format_decimal( $price ),
                            'length'   => ! empty( $request['warranty_addon_length'][ $key ] ) ? $request['warranty_addon_length'][ $key ] : '',
                            'duration' => ! empty( $request['warranty_addon_duration'][ $key ] ) ? $request['warranty_addon_duration'][ $key ] : '',
                        ];
                    }
                }

                $data['addon_settings'] = $addon_settings;
            }
        }

        return $data;
    }

    /**
     * Get setting value
     *
     * @since 1.0.0
     *
     * @param int $product_id
     *
     * @return array
     */
    public function get_settings( int $product_id = 0 ): array {
        $rma_settings   = [];
        $admin_settings = dokan_get_option( 'rma_policy', 'dokan_rma', '' );
        $default        = [
            'from'            => 'store',
            'label'           => __( 'Warranty', 'dokan' ),
            'type'            => 'no_warranty',
            'policy'          => $admin_settings,
            'reasons'         => [],
            'length'          => '',
            'length_value'    => '',
            'length_duration' => '',
            'addon_settings'  => [],
        ];

        if ( $product_id ) {

            /**
             * Has product ID and get product rma settings if have. If not set in product then
             * return those product store owner default settings
             */
            $override_default = get_post_meta( $product_id, '_dokan_rma_override_product', true );

            if ( 'yes' === $override_default ) {
                $rma_settings         = get_post_meta( $product_id, '_dokan_rma_settings', true );
                $rma_settings['from'] = 'product';
            } else {
                $seller_id    = get_post_field( 'post_author', $product_id );
                $rma_settings = get_user_meta( $seller_id, '_dokan_rma_settings', true );
                $rma_settings = dokan_parse_args( $rma_settings, $default );
            }
        } else {
            // return default store settings if user logged id as a seller
            $user_id = dokan_get_current_user_id();

            // Not found any user so return $default settings
            if ( ! $user_id ) {
                return $default;
            }

            $rma_settings         = get_user_meta( $user_id, '_dokan_rma_settings', true );
            $rma_settings         = dokan_parse_args( $rma_settings, $default );
            $rma_settings['from'] = 'store';
        }

        return $rma_settings;
    }

    /**
     * Check required add-ons.
     *
     * @param int $product_id Product ID.
     *
     * @return bool
     */
    public function check_required_warranty( int $product_id ): bool {
        $warranty = $this->get_settings( $product_id );

        return $warranty['type'] === 'addon_warranty' && ! isset( $_REQUEST['dokan_warranty'] ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended
    }

    /**
     * Transform warranty request for deleted orders
     *
     * @since 3.7.0
     *
     * @param array $request
     *
     * @return array
     */
    private function transform_deleted_order_warranty_request( $request ) {
        $product_ids = explode( ',', $request['products'] );
        $quantities = explode( ',', $request['quantity'] );
        $item_ids = explode( ',', $request['item_id'] );
        // Return basic information for deleted orders
        $vendor = dokan()->vendor->get( $request['vendor_id'] );
        $customer = get_user_by( 'id', $request['customer_id'] );
        $items = [];

        foreach ( $product_ids as $key => $product_id ) {
            $product = wc_get_product( $product_id );

            if ( $product ) {
                $items[] = [
                    'id'        => $product->get_id(),
                    'title'     => $product->get_name(),
                    'thumbnail' => wp_get_attachment_url( $product->get_image_id() ),
                    'quantity'  => $quantities[ $key ],
                    'url'       => $product->get_permalink(),
                    'price'     => wc_format_decimal( $product->get_price() ),
                    'item_id'   => $item_ids[ $key ],
                    'tax'       => 'unknown',
                ];
            }
        }

        $reason_label = dokan_rma_refund_reasons( $request['reasons'] );
        if ( is_array( $reason_label ) || '' === $reason_label ) {
            $reason_label = esc_html__( 'No reason provided', 'dokan' );
        }

        return apply_filters(
            'dokan_get_warranty_single_request_data',
            [
                'id'          => $request['id'],
                'order_id'    => $request['order_id'],
                'vendor'   => [
                    'store_id'   => $vendor ? $vendor->get_id() : 0,
                    'store_name' => $vendor ? $vendor->get_shop_name() : __( 'Unknown Store', 'dokan' ),
                    'store_url'  => $vendor ? $vendor->get_shop_url() : '#',
                ],
                'customer' => [
                    'id'   => $customer ? $customer->ID : 0,
                    'name' => $customer ? $customer->display_name : __( 'Unknown Customer', 'dokan' ),
                ],
                'type'             => $request['type'],
                'type_label'       => dokan_warranty_request_type( $request['type'] ),
                'status'           => 'info_removed', // New status for deleted orders
                'reasons'          => $request['reasons'],
                'reasons_label'    => $reason_label,
                'details'          => $request['details'],
                'note'             => $request['note'],
                'created_at'       => $request['created_at'],
                'items'            => $items,
                'is_order_deleted' => true,
            ]
        );
    }
}
