<?php

namespace WeDevs\Wpuf\Pro;

use WeDevs\Wpuf\Admin\Subscription;
use WeDevs\Wpuf\Data\Country_State;
use WeDevs\Wpuf\Pro\Traits\TaxableTrait;

/**
 * Tax Class
 *
 * @since 2.8.1
 *
 */
class Tax {

    use TaxableTrait;

    public function __construct() {
        add_action( 'init', [ $this, 'wpuf_save_tax_options' ] );

        if ( ! class_exists( 'WeDevs\Wpuf\Data\Country_State' ) ) {
            return;
        }
        add_filter( 'wpuf_settings_sections', [ $this, 'wpuf_tax_settings_tab' ] );
        add_filter( 'wpuf_settings_fields', [ $this, 'wpuf_tax_settings_content' ] );
        add_action( 'admin_enqueue_scripts', [ $this, 'enqueue_scripts' ] );
        add_action( 'wpuf_calculate_tax', [ $this, 'wpuf_calculate_taxes' ] );
        add_action( 'wpuf_before_pack_payment_total', [ $this, 'wpuf_render_tax_field' ] );

        // Add tax to payment data before sending to gateway
        add_filter( 'wpuf_payment_data_before_gateway', [ $this, 'add_tax_to_payment_data' ], 10, 2 );

        // Recalculate tax from pack when PayPal webhook data is missing
        add_filter( 'wpuf_recalculate_tax_from_pack', [ $this, 'recalculate_tax_from_pack' ], 10, 4 );

        $price_with_tax = $this->wpuf_prices_include_tax();

        if ( isset( $price_with_tax ) && $price_with_tax ) {
            add_filter( 'wpuf_payment_amount', [ $this, 'wpuf_amount_with_tax' ] );
        }
    }

    /**
     *
     * Adds tax settings tab
     *
     */
    public function wpuf_tax_settings_tab( $settings ) {
        $tax_settings = [
            [
                'id'    => 'wpuf_payment_tax',
                'title' => __( 'Tax', 'wpuf-pro' ),
                'icon'  => 'dashicons-media-text',
            ],
        ];

        return array_merge( $settings, $tax_settings );
    }

    /**
     *
     * Adds tax settings tab contents
     *
     */
    public function wpuf_tax_settings_content( $settings_fields ) {
        $cs = new Country_State();
        $countries = $cs->countries();
        $tax_settings_fields = [
            'wpuf_payment_tax' => [
                [
                    'name'     => 'tax_help',
                    'label'    => __( 'Need help?', 'wpuf-pro' ),
                    'desc'    => sprintf(
                    // translators: %1$s: opening anchor tag, %2$s: closing anchor tag
                        __( 'Visit the %1$sTax setup documentation%2$s for guidance on how to setup tax.', 'wpuf-pro' ), '<a href="https://wedevs.com/docs/wp-user-frontend-pro/settings/tax/" target="_blank">',
                        '</a>'
                    ),
                    'callback' => 'wpuf_descriptive_text',
                ],
                [
                    'name'    => 'enable_tax',
                    'label'   => __( 'Enable Tax', 'wpuf-pro' ),
                    'desc'    => __( 'Enable tax on payments', 'wpuf-pro' ),
                    'type'    => 'checkbox',
                    'default' => 'on',
                ],
                [
                    'name'     => 'wpuf_base_country_state',
                    'label'    => '<strong>' . __( 'Base Country and State', 'wpuf-pro' ) . '</strong>',
                    'desc'     => __( 'The Base Country is where your business or company is located', 'wpuf-pro' ),
                    'callback' => [ $this, 'wpuf_base_country_state' ],
                ],
                [
                    'name'     => 'wpuf_tax_rates',
                    'label'    => '<strong>' . __( 'Tax Rates', 'wpuf-pro' ) . '</strong>',
                    'desc'     => __(
                        'Add tax rates for specific regions. Enter a percentage, such as 5 for 5%', 'wpuf-pro'
                    ),
                    'callback' => [ $this, 'wpuf_tax_rates' ],
                ],
                [
                    'name'    => 'fallback_tax_rate',
                    'label'   => '<strong>' . __( 'Fallback Tax Rate', 'wpuf-pro' ) . '</strong>',
                    'desc'    => __(
                        'Customers not in a specific rate will be charged this tax rate. Enter a percentage, such as 5 for 5%',
                        'wpuf-pro'
                    ),
                    'type'    => 'number',
                    'default' => 0,
                ],
                [
                    'name'    => 'prices_include_tax',
                    'label'   => __( 'Show prices with tax', 'wpuf-pro' ),
                    'desc'    => __( 'If frontend prices will include tax or not', 'wpuf-pro' ),
                    'type'    => 'radio',
                    'default' => 'yes',
                    'options' => [
                        'yes' => __( 'Show prices with tax', 'wpuf-pro' ),
                        'no'  => __( 'Show prices without tax', 'wpuf-pro' ),
                    ],
                ],
            ],
        ];

        return array_merge( $settings_fields, $tax_settings_fields );
    }

    /**
     * Add tax to payment data before sending to gateway
     *
     * @since 4.2.9
     *
     * @param array $payment_data Payment data structure
     * @param array $original_data Original form submission data
     *
     * @return array Modified payment data with tax
     */
    public function add_tax_to_payment_data( $payment_data, $original_data ) {
        if ( ! $this->wpuf_tax_enabled() ) {
            return $payment_data;
        }

        // Get tax rate
        $tax_rate = $this->wpuf_current_tax_rate(); // Returns percentage (e.g., 10 for 10%)

        if ( empty( $tax_rate ) || $tax_rate <= 0 ) {
            return $payment_data;
        }

        // Calculate tax amount
        $subtotal = $payment_data['amount'];
        $tax_amount = ( $subtotal * $tax_rate ) / 100;

        // Initialize breakdown if not exists
        if ( ! isset( $payment_data['breakdown'] ) ) {
            $payment_data['breakdown'] = [];
        }

        // Add breakdown items
        $payment_data['breakdown']['item_total'] = $subtotal;
        $payment_data['breakdown']['tax_total'] = $tax_amount;

        // Calculate and set total
        $payment_data['total'] = $subtotal + $tax_amount;

        // Add metadata for reference
        if ( ! isset( $payment_data['metadata'] ) ) {
            $payment_data['metadata'] = [];
        }
        $payment_data['metadata']['tax_rate'] = $tax_rate;

        return $payment_data;
    }

    /**
     * Recalculate tax from subscription pack
     *
     * This method is hooked into wpuf_recalculate_tax_from_pack filter to calculate tax
     * when PayPal webhook data is missing or incorrect.
     *
     * @since 4.2.9
     *
     * @param false|array $tax_data   Existing tax data (false by default)
     * @param int         $pack_id    Subscription pack ID
     * @param int         $user_id    User ID
     * @param float       $total_amount Total amount from PayPal (for validation)
     * @param string      $payment_type Payment type ('pack' or 'post')
     *
     * @return array|false Array with 'subtotal', 'tax', and 'cost' keys, or false on failure
     */
    public function recalculate_tax_from_pack( $tax_data, $pack_id, $user_id, $total_amount = 0, $payment_type = 'pack' ) {
        // Only process for pack payments
        if ( 'pack' !== $payment_type ) {
            return $tax_data;
        }

        // If tax is not enabled, return false to allow other fallbacks
        if ( ! $this->wpuf_tax_enabled() ) {
            return false;
        }

        try {
            // Get subscription pack
            $subscription = new Subscription();
            $pack = $subscription->get_subscription( $pack_id );

            if ( ! $pack || ! isset( $pack->meta_value['billing_amount'] ) ) {
                return false;
            }

            // Get billing amount from pack
            $billing_amount = floatval( $pack->meta_value['billing_amount'] );

            if ( $billing_amount <= 0 ) {
                return false;
            }

            // Get user billing address
            $address_fields = wpuf_get_user_address( $user_id );
            $billing_country = '';
            $billing_state = '';

            if ( ! empty( $address_fields ) ) {
                // Handle both 'billing_country' and 'country' keys
                if ( isset( $address_fields['billing_country'] ) ) {
                    $billing_country = $address_fields['billing_country'];
                } elseif ( isset( $address_fields['country'] ) ) {
                    $billing_country = $address_fields['country'];
                }

                // Handle both 'billing_state' and 'state' keys
                if ( isset( $address_fields['billing_state'] ) ) {
                    $billing_state = $address_fields['billing_state'];
                } elseif ( isset( $address_fields['state'] ) ) {
                    $billing_state = $address_fields['state'];
                }
            }

            // Get tax rate based on country and state
            $tax_rate = $this->wpuf_tax_rate_country_state( $billing_country, $billing_state );

            if ( empty( $tax_rate ) || $tax_rate <= 0 ) {
                // No tax rate found, return false to allow other fallbacks
                return false;
            }

            // Calculate tax amount
            $tax_amount = ( $billing_amount * $tax_rate ) / 100;
            $cost = $billing_amount + $tax_amount;

            // Validate against total_amount if provided (within 0.01 tolerance for rounding)
            if ( $total_amount > 0 ) {
                $difference = abs( $cost - $total_amount );
                if ( $difference > 0.01 ) {
                    // If calculated cost doesn't match PayPal total significantly,
                    // trust our calculation based on pack (we're fixing PayPal's incorrect data)
                    $subtotal = $billing_amount;
                } else {
                    // Values match within tolerance, use calculated values
                    $subtotal = $billing_amount;
                }
            } else {
                $subtotal = $billing_amount;
            }

            return [
                'subtotal' => $subtotal,
                'tax'      => $tax_amount,
                'cost'     => $cost,
            ];
        } catch ( \Exception $e ) {
            return false;
        }
    }

    /**
     *
     * Enqueue scripts
     *
     */
    public function enqueue_scripts() {
        wp_enqueue_script( 'wpuf-tax' );
        wp_enqueue_style( 'wpuf-tax' );
    }
}
