<?php
/**
 * Error Fix Helper for determining fix dialog requirements.
 *
 * @package Freefactu
 */

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

/**
 * Class Freefactu_Error_Fix_Helper
 *
 * Provides utility methods to determine if an error requires a fix dialog
 * and what fields should be shown in that dialog.
 */
class Freefactu_Error_Fix_Helper {

    /**
     * Fix field configurations for each error type that requires a dialog.
     *
     * @var array
     */
    private static $fix_fields = array(
        'hash_chain' => array(
            array(
                'name'        => 'id_anterior',
                'label'       => 'Número de factura anterior',
                'placeholder' => 'Ej: F2024-001',
                'type'        => 'text',
                'help'        => 'Introduce el número de la última factura enviada a Verifactu.',
                'required'    => false,
            ),
            array(
                'name'        => 'fecha_anterior',
                'label'       => 'Fecha de factura anterior',
                'placeholder' => 'DD-MM-YYYY',
                'type'        => 'text',
                'help'        => 'Fecha de expedición de la factura anterior en formato DD-MM-AAAA.',
                'required'    => false,
            ),
            array(
                'name'        => 'huella_anterior',
                'label'       => 'Huella factura anterior',
                'placeholder' => 'Hash SHA-256 (64 caracteres)',
                'type'        => 'text',
                'maxlength'   => 64,
                'pattern'     => '[a-fA-F0-9]{64}',
                'help'        => 'Introduce la huella (hash) de la última factura registrada en Verifactu.',
                'required'    => false,
            ),
        ),
    );

    /**
     * Check if an error category requires a fix dialog.
     *
     * @param string $error_category The error category constant.
     * @param string $error_message  Optional error message for CLIENT errors.
     * @return bool True if a fix dialog is required.
     */
    public static function requires_fix_dialog( $error_category, $error_message = '' ) {
        // HASH_CHAIN errors from AEAT always need the dialog
        if ( $error_category === 'hash_chain' ) {
            return true;
        }

        // CLIENT errors need dialog if they're about chaining
        if ( $error_category === 'client' && self::is_chaining_error( $error_message ) ) {
            return true;
        }

        return false;
    }

    /**
     * Get the fix fields configuration for a given error category.
     *
     * @param string $error_category The error category constant.
     * @param string $error_message  Optional error message for CLIENT errors.
     * @return array Array of fix field configurations, or empty array if no dialog needed.
     */
    public static function get_fix_fields( $error_category, $error_message = '' ) {
        if ( ! self::requires_fix_dialog( $error_category, $error_message ) ) {
            return array();
        }

        // Both hash_chain and client chaining errors use the same fields
        return self::$fix_fields['hash_chain'];
    }

    /**
     * Get dialog title for the error category.
     *
     * @param string $error_category The error category constant.
     * @return string Dialog title in Spanish.
     */
    public static function get_dialog_title( $error_category ) {
        $titles = array(
            'hash_chain' => __( 'Subsanar error de encadenamiento', 'freefactu' ),
            'client'     => __( 'Corregir error de validación', 'freefactu' ),
        );

        return isset( $titles[ $error_category ] ) ? $titles[ $error_category ] : __( 'Corregir error', 'freefactu' );
    }

    /**
     * Get dialog description for the error category.
     *
     * @param string $error_category The error category constant.
     * @return string Dialog description in Spanish.
     */
    public static function get_dialog_description( $error_category ) {
        $descriptions = array(
            'hash_chain' => __( 'Para corregir el encadenamiento de facturas, introduce los datos de la última factura registrada en Verifactu. Estos campos son opcionales si el sistema puede recuperar los datos automáticamente.', 'freefactu' ),
            'client'     => __( 'Para corregir el error de encadenamiento, introduce los datos de la última factura registrada en Verifactu.', 'freefactu' ),
        );

        return isset( $descriptions[ $error_category ] ) ? $descriptions[ $error_category ] : '';
    }

    /**
     * Check if an error message indicates a chaining error.
     *
     * @param string $error_message The error message to check.
     * @return bool True if the error is about chaining.
     */
    public static function is_chaining_error( $error_message ) {
        if ( empty( $error_message ) ) {
            return false;
        }

        $chaining_patterns = array(
            'previousHash',
            'previousInvoiceId',
            'Previous hash',
            'Previous invoice ID',
            'huella anterior',
            'factura anterior',
            'hash is required',
            'invoice ID is required',
            'encadenamiento',
        );

        $message_lower = strtolower( $error_message );
        foreach ( $chaining_patterns as $pattern ) {
            if ( stripos( $message_lower, strtolower( $pattern ) ) !== false ) {
                return true;
            }
        }

        return false;
    }

    /**
     * Get all fix fields configurations for JavaScript localization.
     *
     * @return array Array of fix field configurations keyed by error category.
     */
    public static function get_all_fix_fields() {
        return self::$fix_fields;
    }

    /**
     * Get error categories that require fix dialogs.
     *
     * @return array Array of error category strings.
     */
    public static function get_dialog_required_categories() {
        return array( 'hash_chain' );
    }
}
