<?php
/**
 * Plugin Name: Verifika para WooCommerce
 * Plugin URI:  https://verifika.app/widget/
 * Description: Verificación de comprobantes bancarios con IA. El cliente adjunta su comprobante en el checkout; Verifika lo analiza en segundos y aprueba o retiene el pedido automáticamente.
 * Version:     1.0.0
 * Author:      Verifika / Kitifica
 * Author URI:  https://verifika.app
 * Requires at least: 5.8
 * Requires PHP: 7.4
 * WC requires at least: 6.0
 * WC tested up to: 9.0
 * Text Domain: verifika-wc
 */

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

// HPOS compatibility declaration
add_action( 'before_woocommerce_init', function () {
	if ( class_exists( '\Automattic\WooCommerce\Utilities\FeaturesUtil' ) ) {
		\Automattic\WooCommerce\Utilities\FeaturesUtil::declare_compatibility( 'custom_order_tables', __FILE__, true );
	}
} );

// Register gateway
add_filter( 'woocommerce_payment_gateways', function ( $gateways ) {
	$gateways[] = 'WC_Gateway_Verifika';
	return $gateways;
} );

add_action( 'plugins_loaded', function () {
	if ( ! class_exists( 'WC_Payment_Gateway' ) ) return;

	class WC_Gateway_Verifika extends WC_Payment_Gateway {

		const API_URL = 'https://qztcjvslcyzrgxrdrptx.supabase.co/functions/v1/analizar-comprobante';

		public function __construct() {
			$this->id                 = 'verifika';
			$this->has_fields         = true;
			$this->method_title       = 'Verifika — Transferencia bancaria';
			$this->method_description = 'El cliente adjunta su comprobante de pago; Verifika lo verifica con IA y actualiza el pedido automáticamente.';

			$this->init_form_fields();
			$this->init_settings();

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

			add_action( 'woocommerce_update_options_payment_gateways_' . $this->id, [ $this, 'process_admin_options' ] );
		}

		// ── Settings ──────────────────────────────────────────────────────────────

		public function init_form_fields() {
			$this->form_fields = [
				'enabled' => [
					'title'   => 'Activar',
					'type'    => 'checkbox',
					'label'   => 'Activar método de pago Verifika',
					'default' => 'yes',
				],
				'title' => [
					'title'    => 'Título en checkout',
					'type'     => 'text',
					'default'  => 'Transferencia bancaria',
					'desc_tip' => 'Nombre que ve el cliente al seleccionar el método de pago.',
				],
				'description' => [
					'title'   => 'Descripción en checkout',
					'type'    => 'textarea',
					'default' => 'Realiza una transferencia al número de cuenta indicado y sube tu comprobante. Lo verificamos en segundos.',
				],
				'api_key' => [
					'title'       => 'API Key de Verifika',
					'type'        => 'password',
					'description' => 'Tu clave <code>vfk_…</code>. Obtenerla en <a href="https://verifika.app/api/dashboard/" target="_blank">Panel API →</a>',
					'desc_tip'    => false,
				],
				'banco' => [
					'title'       => 'Banco receptor',
					'type'        => 'text',
					'placeholder' => 'Banco Agrícola',
				],
				'titular' => [
					'title'       => 'Titular de la cuenta',
					'type'        => 'text',
					'placeholder' => 'Juan Pérez',
				],
				'numero_cuenta' => [
					'title'       => 'Número de cuenta',
					'type'        => 'text',
					'placeholder' => '770000849870',
				],
				'tipo_cuenta' => [
					'title'   => 'Tipo de cuenta',
					'type'    => 'select',
					'options' => [
						'Ahorros'   => 'Ahorros',
						'Corriente' => 'Corriente',
					],
					'default' => 'Ahorros',
				],
				'monto_limite' => [
					'title'             => 'Monto límite para RETENER ($)',
					'type'              => 'number',
					'description'       => 'Pedidos con monto ≥ este valor quedan en "En espera" para revisión manual aunque el score sea alto. <code>0</code> = desactivado.',
					'desc_tip'          => false,
					'default'           => '0',
					'custom_attributes' => [ 'min' => '0', 'step' => '0.01' ],
				],
				'accion_rechazado' => [
					'title'   => 'Acción cuando se rechaza',
					'type'    => 'select',
					'options' => [
						'cancel'  => 'Cancelar pedido (recomendado)',
						'on-hold' => 'Poner en espera para revisión manual',
					],
					'default' => 'cancel',
				],
			];
		}

		// ── Checkout UI ───────────────────────────────────────────────────────────

		public function payment_fields() {
			$desc = $this->get_description();
			if ( $desc ) {
				echo '<p style="margin-bottom:12px;">' . esc_html( $desc ) . '</p>';
			}

			$banco  = $this->get_option( 'banco' );
			$titular = $this->get_option( 'titular' );
			$numero  = $this->get_option( 'numero_cuenta' );
			$tipo    = $this->get_option( 'tipo_cuenta' );

			if ( $banco ) {
				echo '<div style="background:#f8fafc;border:1px solid #e2e8f0;border-radius:8px;padding:12px 16px;margin-bottom:14px;font-size:13px;line-height:2;">';
				echo '<strong>' . esc_html( $banco ) . '</strong><br>';
				if ( $titular ) echo 'Titular: <strong>' . esc_html( $titular ) . '</strong><br>';
				if ( $numero  ) echo 'Cuenta: <strong>' . esc_html( $numero ) . '</strong>';
				if ( $tipo    ) echo ' <span style="color:#6b7280;">(' . esc_html( $tipo ) . ')</span>';
				echo '</div>';
			}

			echo '<div>';
			echo '<label for="verifika_comprobante" style="display:block;font-weight:600;font-size:13px;margin-bottom:6px;">';
			echo 'Comprobante de pago <span style="color:#e53e3e;">*</span>';
			echo '</label>';
			echo '<input type="file" id="verifika_comprobante" name="verifika_comprobante" required ';
			echo 'accept="image/png,image/jpeg,image/webp" ';
			echo 'style="display:block;width:100%;padding:8px;border:1px solid #d1d5db;border-radius:6px;font-size:13px;cursor:pointer;">';
			echo '<p style="font-size:11px;color:#9ca3af;margin:5px 0 0;">PNG · JPG · WEBP &mdash; máx 8 MB</p>';
			echo '</div>';
			echo '<script>(function(){';
			echo 'var sent=false;';
			echo 'jQuery(document.body).on("checkout_place_order_verifika",function(){';
			echo 'if(sent){return false;}sent=true;return true;';
			echo '});';
			echo 'jQuery(document.body).on("checkout_error",function(){sent=false;});';
			echo '})();</script>';
		}

		public function validate_fields() {
			if ( empty( $_FILES['verifika_comprobante']['tmp_name'] ) ) {
				wc_add_notice( 'Debes adjuntar tu comprobante de pago.', 'error' );
				return false;
			}

			$allowed = [ 'image/jpeg', 'image/jpg', 'image/png', 'image/webp' ];
			if ( ! in_array( $_FILES['verifika_comprobante']['type'], $allowed, true ) ) {
				wc_add_notice( 'El comprobante debe ser una imagen PNG, JPG o WEBP.', 'error' );
				return false;
			}

			if ( $_FILES['verifika_comprobante']['size'] > 8 * 1024 * 1024 ) {
				wc_add_notice( 'El comprobante no debe superar los 8 MB.', 'error' );
				return false;
			}

			return true;
		}

		// ── Payment processing ────────────────────────────────────────────────────

		public function process_payment( $order_id ) {
			$order = wc_get_order( $order_id );

			$file   = $_FILES['verifika_comprobante'];
			$base64 = base64_encode( file_get_contents( $file['tmp_name'] ) );
			$mime   = $file['type'];

			$payload = [
				'imageBase64'        => $base64,
				'mimeType'           => $mime,
				'banco_seleccionado' => $this->get_option( 'banco' ),
				'titular'            => $this->get_option( 'titular' ),
				'numero_cuenta'      => $this->get_option( 'numero_cuenta' ),
				'tipo_cuenta'        => $this->get_option( 'tipo_cuenta' ),
				'transfer_code'      => 'WC-' . $order_id,
				'monto_esperado'     => (float) $order->get_total(),
			];

			$monto_limite = (float) $this->get_option( 'monto_limite', 0 );
			if ( $monto_limite > 0 ) {
				$payload['monto_limite'] = $monto_limite;
			}

			$result = $this->call_api( $payload );

			// API unreachable — hold for manual review
			if ( is_wp_error( $result ) ) {
				$logger = wc_get_logger();
				$logger->error( sprintf( '[Pedido #%d] API error: %s', $order_id, $result->get_error_message() ), [ 'source' => 'verifika' ] );
				$order->update_status( 'on-hold', 'Verifika no disponible — revisión manual requerida.' );
				WC()->cart->empty_cart();
				return [ 'result' => 'success', 'redirect' => $this->get_return_url( $order ) ];
			}

			// Persist Verifika data on order
			$order->update_meta_data( '_verifika_score',  $result['puntaje_autenticidad'] ?? '' );
			$order->update_meta_data( '_verifika_accion', $result['accion_recomendada']   ?? '' );
			$order->update_meta_data( '_verifika_status', $result['status']               ?? '' );
			$order->update_meta_data( '_verifika_banco',  $result['banco']                ?? '' );
			$order->update_meta_data( '_verifika_monto',  $result['monto']                ?? '' );
			$order->save();

			$accion = $result['accion_recomendada'] ?? 'RECHAZADO';
			$score  = intval( $result['puntaje_autenticidad'] ?? 0 );

			if ( $accion === 'PRE_APROBADO' ) {
				$order->payment_complete();
				$order->add_order_note( sprintf( 'Verifika: comprobante pre-aprobado. Score %d/100.', $score ) );
				WC()->cart->empty_cart();
				return [ 'result' => 'success', 'redirect' => $this->get_return_url( $order ) ];
			}

			if ( $accion === 'RETENER' ) {
				$razon = $result['razon_rechazo'] ?? 'monto alto';
				$order->update_status( 'on-hold', sprintf( 'Verifika: RETENER — score %d/100. %s', $score, $razon ) );
				WC()->cart->empty_cart();
				return [ 'result' => 'success', 'redirect' => $this->get_return_url( $order ) ];
			}

			// RECHAZADO
			$instruccion = $result['instruccion_usuario'] ?? 'Tu comprobante no pudo verificarse. Por favor intenta de nuevo o contacta con nosotros.';

			if ( $this->get_option( 'accion_rechazado' ) === 'on-hold' ) {
				$order->update_status( 'on-hold', sprintf( 'Verifika: rechazado — score %d/100.', $score ) );
				WC()->cart->empty_cart();
				return [ 'result' => 'success', 'redirect' => $this->get_return_url( $order ) ];
			}

			$order->update_status( 'cancelled', sprintf( 'Verifika: comprobante rechazado — score %d/100.', $score ) );
			wc_add_notice( esc_html( $instruccion ), 'error' );
			return;
		}

		// ── API client ────────────────────────────────────────────────────────────

		private function call_api( array $payload ) {
			$response = wp_remote_post( self::API_URL, [
				'headers' => [
					'Content-Type' => 'application/json',
					'x-api-key'    => $this->get_option( 'api_key' ),
				],
				'body'    => wp_json_encode( $payload ),
				'timeout' => 30,
			] );

			if ( is_wp_error( $response ) ) return $response;

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

			if ( empty( $body['ok'] ) ) {
				return new WP_Error( 'verifika_api', $body['error'] ?? 'Respuesta inesperada de Verifika.' );
			}

			return $body;
		}
	}

	// ── Admin order panel ─────────────────────────────────────────────────────

	add_action( 'woocommerce_admin_order_data_after_billing_address', function ( $order ) {
		$score  = $order->get_meta( '_verifika_score' );
		$accion = $order->get_meta( '_verifika_accion' );
		$monto  = $order->get_meta( '_verifika_monto' );

		if ( $score === '' || $score === null || $score === false ) return;

		if ( $accion === 'PRE_APROBADO' ) {
			$color = '#16a34a';
		} elseif ( $accion === 'RETENER' ) {
			$color = '#d97706';
		} else {
			$color = '#dc2626';
		}

		echo '<div style="margin-top:14px;padding:10px 14px;background:#f9fafb;border:1px solid #e5e7eb;border-radius:6px;font-size:12px;">';
		echo '<span style="color:#9ca3af;text-transform:uppercase;letter-spacing:.05em;font-weight:700;">Verifika</span><br>';
		echo '<span style="color:' . esc_attr( $color ) . ';font-weight:700;">' . esc_html( $accion ) . '</span>';
		echo ' &mdash; Score <strong>' . intval( $score ) . '/100</strong>';
		if ( $monto ) echo ' &mdash; ' . esc_html( $monto );
		echo '</div>';
	} );
} );
