<?php
/**
 * Stablezact Blocks support
 */

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

use Automattic\WooCommerce\Blocks\Payments\Integrations\AbstractPaymentMethodType;

/**
 * Stablezact payment method integration
 *
 * @since 1.0.0
 */
final class Stablezact_Blocks_Support extends AbstractPaymentMethodType {

    /**
     * The gateway instance.
     *
     * @var Stablezact_Gateway
     */
    private $gateway;

    /**
     * Payment method name/id/slug.
     *
     * @var string
     */
    protected $name = 'stablezact';

    /**
     * Initializes the payment method type.
     */
    public function initialize() {
        $this->settings = get_option('woocommerce_stablezact_settings', []);
        $gateways       = WC()->payment_gateways->payment_gateways();
        $this->gateway  = $gateways['stablezact'];

        // Add payment processing hook for blocks
        add_action('woocommerce_rest_checkout_process_payment_with_context', array($this, 'process_payment_with_context'), 10, 2);
    }

    /**
     * Returns if this payment method should be active. If false, the scripts will not be enqueued.
     *
     * @return boolean
     */
    public function is_active() {
        return $this->gateway->is_available();
    }

    /**
     * Returns an array of scripts/handles to be registered for this payment method.
     *
     * @return array
     */
    public function get_payment_method_script_handles() {
        $script_path       = '/assets/js/stablezact-blocks.js';
        $script_asset_path = STABLEZACT_PLUGIN_DIR . 'assets/js/stablezact-blocks.asset.php';
        $script_asset      = file_exists($script_asset_path)
            ? require($script_asset_path)
            : array('dependencies' => array(), 'version' => '1.0.0');

        $script_url = STABLEZACT_PLUGIN_URL . $script_path;

        wp_register_script(
            'stablezact-blocks',
            $script_url,
            $script_asset['dependencies'],
            $script_asset['version'],
            true
        );

        if (function_exists('wp_set_script_translations')) {
            wp_set_script_translations('stablezact-blocks', 'stablezact-crypto-payments', STABLEZACT_PLUGIN_DIR . 'languages');
        }

        return array('stablezact-blocks');
    }

    /**
     * Returns an array of key=>value pairs of data made available to the payment methods script.
     *
     * @return array
     */
    public function get_payment_method_data() {
        $payment_timeout = $this->get_setting('payment_timeout', '300');
        $data = array(
            'title'       => $this->get_setting('title'),
            'description' => $this->get_setting('description'),
            'supports'    => array_filter($this->gateway->supports, array($this->gateway, 'supports')),
            'testmode'    => $this->get_setting('testmode'),
            'payment_timeout' => intval($payment_timeout) * 1000, // Convert to milliseconds for JavaScript
        );
        return $data;
    }

    /**
     * Process payment with context for blocks checkout
     */
    public function process_payment_with_context($context, &$result) {
        if ('stablezact' !== $context->payment_method) {
            return;
        }

        try {
            // Get the order from context
            $order = $context->order;

            // Extract payment data - WooCommerce Blocks stores it in PaymentContext
            $payment_data = array();

            // Method 1: Try direct access
            if (isset($context->payment_data) && is_array($context->payment_data)) {
                $payment_data = $context->payment_data;
            }

            // Method 2: Try accessing as property
            if (empty($payment_data) && property_exists($context, 'payment_data')) {
                $payment_data = $context->payment_data;
            }

            // Method 3: Check the raw POST data. The decoded values are not trusted here;
            // every field read from $payment_data below is sanitized on use (sanitize_text_field).
            if (empty($payment_data)) {
                $request_body = file_get_contents('php://input');
                // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- decoded values sanitized field-by-field on use below.
                $request_data = json_decode($request_body, true);
                if (isset($request_data['payment_data'])) {
                    $payment_data = $request_data['payment_data'];
                }
            }

            // Check if we have payment completion data
            $transaction_hash = isset($payment_data['stablezact_transaction_hash']) ? sanitize_text_field($payment_data['stablezact_transaction_hash']) : '';
            $payment_id = isset($payment_data['stablezact_payment_id']) ? sanitize_text_field($payment_data['stablezact_payment_id']) : '';
            $completed = isset($payment_data['stablezact_completed']) ? $payment_data['stablezact_completed'] : false;

            // Convert completed to boolean (handles both string 'true' and boolean true)
            $is_completed = ($completed === 'true' || $completed === true);

            if ($is_completed && !empty($transaction_hash) && !empty($payment_id)) {
                // ✅ PERFORMANCE FIX: Process payment completion quickly
                // Update order meta with payment information
                $order->update_meta_data('_stablezact_transaction_hash', $transaction_hash);
                $order->update_meta_data('_stablezact_payment_id', $payment_id);
                $order->update_meta_data('_stablezact_payment_completed', true);

                // Add order note (lightweight)
                $order->add_order_note(
                    sprintf(
                        /* translators: %s: transaction hash (first 10 characters) */
                        __('Stablezact payment completed. TX: %s', 'stablezact-crypto-payments'),
                        substr($transaction_hash, 0, 10) . '...'
                    )
                );

                // ✅ FIX: Use payment_complete() which handles emails properly
                // This is faster and more reliable than manual status changes
                $order->payment_complete($transaction_hash);

                // payment_complete() already:
                // - Sets order status to 'processing' or 'completed'
                // - Reduces stock levels
                // - Sends emails asynchronously (WooCommerce default behavior)
                // - Sets transaction ID

                // Set result status to success
                $result->set_status('success');
                $result->set_redirect_url($this->gateway->get_return_url($order));
            } else {
                // Set order status to pending
                $order->update_status('pending', __('Awaiting Stablezact payment', 'stablezact-crypto-payments'));
                $order->save();

                // Still redirect to thank you page
                $result->set_status('success');
                $result->set_redirect_url($this->gateway->get_return_url($order));
            }
        } catch (Exception $e) {
            // Set error status
            $result->set_status('failure');
            $result->set_message(__('Payment processing error. Please contact support.', 'stablezact-crypto-payments'));
        }
    }
} 