<?php
/**
 * AEAT UI Helpers
 *
 * Helper functions for rendering AEAT status and actions in the WordPress admin UI.
 *
 * @package Freefactu
 * @since 1.1.0
 */

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

/**
 * Class Freefactu_Aeat_UI_Helpers
 *
 * Provides static helper methods for rendering AEAT-related UI elements
 * in the WordPress admin area.
 */
class Freefactu_Aeat_UI_Helpers {

	/**
	 * Render a status badge for an invoice.
	 *
	 * @param object $invoice Invoice object from database.
	 * @return string HTML for status badge.
	 */
	public static function render_status_badge( $invoice ) {
		$status = isset( $invoice->aeat_final_status ) ? $invoice->aeat_final_status : 'pending';
		
		// Fallback to old status field if new one not set
		if ( $status === 'pending' && ! empty( $invoice->status ) ) {
			$status = self::map_legacy_status( $invoice->status );
		}

		$badge_class = '';
		$label = '';
		$icon = '';

		switch ( $status ) {
			case 'accepted':
				$badge_class = 'aeat-status-accepted';
				$label = __( 'Aceptada', 'freefactu' );
				$icon = 'dashicons-yes-alt';
				break;
				
			case 'subsanated':
				$badge_class = 'aeat-status-subsanated';
				$label = __( 'Subsanada', 'freefactu' );
				$icon = 'dashicons-saved';
				break;
				
			case 'accepted_with_errors':
				$badge_class = 'aeat-status-warnings';
				$label = __( 'Aceptada con errores', 'freefactu' );
				$icon = 'dashicons-warning';
				break;
				
			case 'rejected':
				$badge_class = 'aeat-status-rejected';
				$label = __( 'Rechazada', 'freefactu' );
				$icon = 'dashicons-dismiss';
				break;
				
			case 'pending':
			default:
				$badge_class = 'aeat-status-pending';
				$label = __( 'Pendiente', 'freefactu' );
				$icon = 'dashicons-clock';
				break;
		}

		return sprintf(
			'<span class="aeat-status-badge %s"><span class="dashicons %s"></span> %s</span>',
			esc_attr( $badge_class ),
			esc_attr( $icon ),
			esc_html( $label )
		);
	}

	/**
	 * Render action buttons based on invoice state.
	 *
	 * @param object $invoice Invoice object from database.
	 * @return string HTML for action buttons.
	 */
	public static function render_action_buttons( $invoice ) {
		$status = isset( $invoice->aeat_final_status ) ? $invoice->aeat_final_status : 'pending';
		$error_category = isset( $invoice->error_category ) ? $invoice->error_category : '';
		$tipo_factura = isset( $invoice->tipo_factura ) ? $invoice->tipo_factura : 'F1';

		$buttons = array();

		// Only show action buttons for rejected/error states
		if ( ! in_array( $status, array( 'rejected', 'accepted_with_errors' ), true ) ) {
			return '';
		}

		// Check if subsanation is possible
		$can_subsanar = Freefactu_Aeat_Next_Action_Decider::can_subsanar(
			$tipo_factura,
			$status,
			$error_category
		);

		if ( $can_subsanar ) {
			// Show subsanation button
			$subsanation_count = isset( $invoice->subsanation_count ) ? (int) $invoice->subsanation_count : 0;
			$max_attempts = apply_filters( 'freefactu_max_subsanation_attempts', 3, array( 'invoice_id' => $invoice->id ) );
			$attempts_left = max( 0, $max_attempts - $subsanation_count );

			$buttons[] = sprintf(
				'<button type="button" class="button button-primary aeat-action-subsanar" data-invoice-id="%d" data-order-id="%d">
					<span class="dashicons dashicons-update-alt"></span> %s
					<span class="attempts-count">(%d/%d)</span>
				</button>',
				esc_attr( $invoice->id ),
				esc_attr( $invoice->order_id ),
				esc_html__( 'Subsanar', 'freefactu' ),
				$max_attempts - $attempts_left,
				$max_attempts
			);
		} else {
			// Show explanation for why subsanation is not available
			$reason = Freefactu_Aeat_Next_Action_Decider::explain_no_subsanation( $tipo_factura, $status, $error_category );
			
			// Show rectificativa button if applicable
			if ( $error_category === Freefactu_Aeat_Error_Categories::BUSINESS || $status === 'accepted' ) {
				$buttons[] = sprintf(
					'<button type="button" class="button button-secondary aeat-action-rectificativa" data-invoice-id="%d" data-order-id="%d">
						<span class="dashicons dashicons-edit"></span> %s
					</button>',
					esc_attr( $invoice->id ),
					esc_attr( $invoice->order_id ),
					esc_html__( 'Crear rectificativa', 'freefactu' )
				);
			}

			// Show new F2 button for failed cancellations
			if ( $tipo_factura === 'F2' ) {
				$buttons[] = sprintf(
					'<button type="button" class="button button-secondary aeat-action-retry-f2" data-invoice-id="%d" data-order-id="%d">
						<span class="dashicons dashicons-update"></span> %s
					</button>',
					esc_attr( $invoice->id ),
					esc_attr( $invoice->order_id ),
					esc_html__( 'Reintentar anulación', 'freefactu' )
				);
			}
		}

		if ( empty( $buttons ) ) {
			return '';
		}

		return '<div class="aeat-action-buttons">' . implode( ' ', $buttons ) . '</div>';
	}

	/**
	 * Get error explanation HTML for an invoice.
	 *
	 * @param object $invoice Invoice object from database.
	 * @return string HTML for error explanation.
	 */
	public static function get_error_explanation( $invoice ) {
		$error_category = isset( $invoice->error_category ) ? $invoice->error_category : '';
		$error_message = isset( $invoice->error_message ) ? $invoice->error_message : '';

		if ( empty( $error_category ) && empty( $error_message ) ) {
			return '';
		}

		$category_label = Freefactu_Aeat_Error_Categories::get_label( $error_category );
		$is_subsanable = Freefactu_Aeat_Error_Categories::is_subsanable_category( $error_category );

		$html = '<div class="aeat-error-explanation">';
		
		// Category badge
		$html .= sprintf(
			'<div class="error-category"><strong>%s:</strong> %s</div>',
			esc_html__( 'Tipo de error', 'freefactu' ),
			esc_html( $category_label )
		);

		// Error message
		if ( ! empty( $error_message ) ) {
			$html .= sprintf(
				'<div class="error-message"><strong>%s:</strong> %s</div>',
				esc_html__( 'Mensaje de AEAT', 'freefactu' ),
				esc_html( $error_message )
			);
		}

		// Subsanation indicator
		if ( $is_subsanable ) {
			$html .= sprintf(
				'<div class="subsanable-indicator subsanable-yes">
					<span class="dashicons dashicons-yes"></span> %s
				</div>',
				esc_html__( 'Este error puede subsanarse corrigiendo los datos y reenviando.', 'freefactu' )
			);
		} else {
			$html .= sprintf(
				'<div class="subsanable-indicator subsanable-no">
					<span class="dashicons dashicons-no"></span> %s
				</div>',
				esc_html__( 'Este error no puede subsanarse. Puede requerir una factura rectificativa.', 'freefactu' )
			);
		}

		$html .= '</div>';

		return $html;
	}

	/**
	 * Get CSS styles for AEAT status badges and UI.
	 *
	 * @deprecated 1.2.0 Styles have been moved to assets/css/freefactu-admin.css.
	 *                   This method now returns an empty string for backward compatibility.
	 *
	 * @return string Empty string (styles are now in external CSS file).
	 */
	public static function get_styles() {
		// Styles have been moved to assets/css/freefactu-admin.css
		// This method is kept for backward compatibility but returns empty string.
		return '';
	}

	/**
	 * Map legacy status to new aeat_final_status.
	 *
	 * @param string $legacy_status Old status value.
	 * @return string New status value.
	 */
	private static function map_legacy_status( $legacy_status ) {
		$map = array(
			'success'    => 'accepted',
			'alert_aeat' => 'rejected',
			'alert_qr'   => 'accepted', // QR issue but AEAT accepted
			'alert_pdf'  => 'accepted', // PDF issue but AEAT accepted
		);

		return isset( $map[ $legacy_status ] ) ? $map[ $legacy_status ] : 'pending';
	}
}
