<?php
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

// Cargar utilidades si no se usa autoload PSR-4
require_once __DIR__ . '/class-pftf-utils.php';

use PFTF\Utils;

class PFTF_WC_Transfer_Pagos_Fiable extends WC_Payment_Gateway {

    protected $images_dir;

    public function __construct() {
        $this->id                 = 'pagos_fiable_tf';
        $this->method_title       = __( 'Pagos Fiable Transferencia Bancaria', 'pagosfiable-transfer' );
        $this->method_description = __( 'Permite pagar mediante transferencia bancaria a través de Pagos Fiable.', 'pagosfiable-transfer' );
        $this->title              = __( 'Pago por transferencia bancaria', 'pagosfiable-transfer' );
        $this->has_fields         = true;
        $this->api_key     = $this->get_option('api_key');

 $this->id_payment  = $this->get_option('id_payment');
        $this->api_url     = $this->get_option('api_url');

        $this->supports = [
            'products',
            'high-performance-order-storage',
            'payment-blocks',
        ];

        // Logo de la pasarela (opcional)
//$this->icon = plugins_url( 'assets/images/logo_pf.jpg', dirname(__DIR__) );
        $this->icon = plugins_url( '../src/img/logo_pf_bn.png', __FILE__ );

//$this->icon = plugins_url( 'assets/images/logo_pf.jpg', dirname(__DIR__) ); 
// Inicializar ajustes
        $this->init_form_fields();
        $this->init_settings();

        $this->description  = $this->get_option( 'description' );
        $this->instructions = $this->get_option( 'instructions' );

        // Hooks
        add_action( 'wp_enqueue_scripts', [ $this, 'enqueue_checkout_assets' ] );
        add_action( 'woocommerce_update_options_payment_gateways_' . $this->id, [ $this, 'process_admin_options' ] );
        add_action( 'woocommerce_thankyou_' . $this->id, [ $this, 'thankyou_page' ] );
       // add_action( 'woocommerce_email_before_order_table', [ $this, 'email_instructions' ], 10, 3 );
    }

    // ────────────────────────────────
    // Ajustes del administrador
    // ────────────────────────────────
    public function init_form_fields() {
        $this->form_fields = [
            'enabled' => [
                'title'   => __( 'Activar/Desactivar', 'pagosfiable-transfer' ),
                'type'    => 'checkbox',
                'label'   => __( 'Habilitar pagos por transferencia bancaria con Pagos Fiable', 'pagosfiable-transfer' ),
                'default' => 'no',
            ],
                        'api_key' => array(
                'title'       => __('API Key', 'pagosfiable-transfer'),
                'type'        => 'text',
                'description' => __('Clave de API para conectar con la pasarela de pagos.', 'pagosfiable-transfer'),
                'default'     => '',
                'desc_tip'    => true,
            ),
            'api_url' => array(
                'title'       => __('URL de la API', 'pagosfiable-transfer'),
                'type'        => 'text',
                'description' => __('(Requerido)', 'pagosfiable-transfer'),
                'default'     => '',
                'desc_tip'    => true,
            ),
            'id_payment' => array(
                'title'       => __('ID de pago', 'pagosfiable-transfer'),
                'type'        => 'text',
                'description' => __('ID único de pago.', 'pagosfiable-transfer'),
                'default'     => '',
                'desc_tip'    => true,
            ),
            // 'description' => [
            //     'title'       => __( 'Descripción', 'pagosfiable-transfer' ),
            //     'type'        => 'textarea',
            //     'default'     => __( '', 'pagosfiable-transfer' ),
            //     'desc_tip'    => true,
            // ],
            // 'instructions' => [
            //     'title'       => __( 'Instrucciones', 'pagosfiable-transfer' ),
            //     'type'        => 'textarea',
            //     'default'     => __( '', 'pagosfiable-transfer' ),
            //     'desc_tip'    => true,
            // ],
        ];
    }

    // ────────────────────────────────
    // Campos visibles en checkout
    // ────────────────────────────────
    public function payment_fields() {
        $this->images_dir = plugin_dir_url( __DIR__ ) . 'assets/images/';
        $template_path    = plugin_dir_path( __DIR__ ) . 'templates/transferpayment-pagosfiable.php';

        if ( file_exists( $template_path ) ) {
            include $template_path;
        } else {
            echo '<p>' . esc_html__( 'Completa tu pedido y recibirás las instrucciones para realizar tu transferencia bancaria.', 'pagosfiable-transfer' ) . '</p>';
        }
    }

    // ────────────────────────────────
    // Cargar CSS/JS solo en checkout
    // ────────────────────────────────
    public function enqueue_checkout_assets() {
        if ( is_checkout() ) {
            wp_enqueue_style(
                'pftf-bootstrap',
                  plugins_url('assets/css/bootstrap.min.css', __FILE__),
                [],
                '5.3.2'
            );

            wp_enqueue_script(
                'pftf-bootstrap',
                plugins_url('assets/js/bootstrap.bundle.min.js', __FILE__),
                [ 'jquery' ],
                '5.3.2',
                true
            );
        }
    }

    // ────────────────────────────────
    // Procesar el pago
    // ────────────────────────────────
public function process_payment( $order_id ) {
    $order = wc_get_order( $order_id );

    $items_data = [];
    foreach ( $order->get_items() as $item_id => $item ) {
        $product = $item->get_product();

        $items_data[] = array(
            'product_id'   => $product ? $product->get_id() : 0,
            'sku'          => $product ? $product->get_sku() : '',
            'name'         => $item->get_name(),
            'quantity'     => $item->get_quantity(),
            'subtotal'     => (float) $item->get_subtotal(),
            'total'        => (float) $item->get_total(),
            'price'        => (float) $order->get_item_subtotal( $item, false ),
        );
    }

    $payment_data = array(
        'value'            => (float) $order->get_total(),
        'request_currency' => $order->get_currency(),
        'id_payment'       => 'WC-' . $order_id,
        'customer' => array(
            'email'      => $order->get_billing_email(),
            'first_name' => $order->get_billing_first_name(),
            'last_name'  => $order->get_billing_last_name(),
            'commision'  => null,
            'phone'      => $order->get_billing_phone(),
        ),
        'order'             => array(
            'id'            => $order_id,
            'number'        => $order->get_order_number(),
            'created_at'    => $created_date,
            'updated_at'    => $modified_date,
            'discount_total'=> $total_discount,
            'tax_total'     => $total_tax,
            'shipping_total'=> $total_shipping,
            'items'         => $items_data,
        ),
    );

    $body = array(
    'payload' => $payment_data
);

    $response = wp_remote_post( 'https://api.pagosfiable.com/api/v1/transference/service', array(
        'method'  => 'POST',
        'timeout' => 500,
        'body'    => wp_json_encode(   $body ),
        'headers' => array(
            'Content-Type'  => 'application/json',
            'Authorization' => 'Bearer ' . sanitize_text_field( $this->api_key ),
        ),
    ));

    if ( is_wp_error( $response ) ) {
        wc_add_notice( __('Error procesando el pago.', 'pagosfiable-transfer'), 'error' );
        return ['result' => 'failure'];
    }

    $body = wp_remote_retrieve_body( $response );
    $data = json_decode( $body, true );

    if ( empty( $data ) || ( $data['response']['status'] ?? '' ) !== 'CHARGE_PENDING' ) {
        wc_add_notice( __('Error en la respuesta del servidor de pago.', 'pagosfiable-transfer'), 'error' );
        return ['result' => 'failure'];
    }

    // Registrar transacción
    $order->add_order_note( 'Pago enviado a Pagos Fiable. ID: ' . $payment_data['id_payment'] );
    update_post_meta( $order_id, '_pagos_fiable_response', $data );

    $order->update_status( 'on-hold', __( 'Esperando pago por transferencia.', 'pagosfiable-transfer' ) );
    WC()->cart->empty_cart();

    return [
        'result'   => 'success',
        'redirect' => $this->get_return_url( $order ),
    ];
}


    // ────────────────────────────────
    // Página de agradecimiento
    // ────────────────────────────────
    public function thankyou_page( $order_id ) {
        if ( class_exists( 'PFTF\Utils' ) ) {
            echo wp_kses_post(
    Utils::render_instructions_html( $order_id, $this->instructions, $data )
);
        }
    }
}
