<?php
/**
 * Freefactu Extensions Manager
 *
 * Manages the extensions/add-ons system for Freefactu plugin.
 *
 * @package Freefactu
 * @since 1.2.0
 */

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

/**
 * Class Freefactu_Extensions
 *
 * Handles the display and management of plugin extensions.
 */
class Freefactu_Extensions {

    /**
     * The single instance of this class.
     *
     * @var Freefactu_Extensions|null
     */
    private static $instance = null;

    /**
     * Get the singleton instance.
     *
     * @return Freefactu_Extensions
     */
    public static function instance() {
        if ( null === self::$instance ) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * Constructor.
     */
    private function __construct() {
        add_action( 'wp_ajax_freefactu_toggle_extension', array( $this, 'ajax_toggle_extension' ) );
    }

    /**
     * Get all available extensions.
     *
     * Returns both core (required) extensions and optional extensions.
     *
     * @return array Array of extension data.
     */
    public static function get_extensions() {
        $extensions = array(
            // Core/Required extensions (already integrated, cannot be disabled)
            array(
                'id'          => 'invoice-generation',
                'name'        => __( 'Generación de facturas', 'freefactu' ),
                'description' => __( 'Genera facturas PDF profesionales con todos los datos fiscales requeridos, incluyendo códigos QR y firma digital.', 'freefactu' ),
                'icon'        => 'dashicons-media-document',
                'required'    => true,
                'active'      => true,
                'version'     => FREEFACTU_VERSION,
                'author'      => 'Freefactu',
            ),
            array(
                'id'          => 'verifactu',
                'name'        => __( 'Veri*factu', 'freefactu' ),
                'description' => __( 'Comunicación con la AEAT para el cumplimiento del sistema Veri*factu, incluyendo firma electrónica y envío de registros.', 'freefactu' ),
                'icon'        => 'dashicons-shield-alt',
                'required'    => true,
                'active'      => true,
                'version'     => FREEFACTU_VERSION,
                'author'      => 'Freefactu',
            ),
            array(
                'id'          => 'invoice-export',
                'name'        => __( 'Exportación de facturas', 'freefactu' ),
                'description' => __( 'Exporta facturas en formatos CSV y ZIP para contabilidad, backup y análisis de datos.', 'freefactu' ),
                'icon'        => 'dashicons-download',
                'required'    => true,
                'active'      => true,
                'version'     => FREEFACTU_VERSION,
                'author'      => 'Freefactu',
            ),
            // Optional extensions
            array(
                'id'          => 'presupuestos',
                'name'        => __( 'Generación de presupuestos', 'freefactu' ),
                'description' => __( 'Crea y gestiona presupuestos profesionales que pueden convertirse fácilmente en facturas cuando se aceptan.', 'freefactu' ),
                'icon'        => 'dashicons-clipboard',
                'required'    => false,
                'active'      => self::is_extension_active( 'presupuestos' ),
                'version'     => '1.0.0',
                'author'      => 'Freefactu',
                'folder'      => 'presupuestos',
            ),
            array(
                'id'          => 'adjuntar-factura-correo',
                'name'        => __( 'Adjuntar factura en correos', 'freefactu' ),
                'description' => __( 'Adjunta automáticamente el PDF de la factura a los correos electrónicos de pedido completado de WooCommerce.', 'freefactu' ),
                'icon'        => 'dashicons-email-alt',
                'required'    => false,
                'active'      => self::is_extension_active( 'adjuntar-factura-correo' ),
                'version'     => '1.0.0',
                'author'      => 'Freefactu',
                'folder'      => 'adjuntar-factura-correo',
            ),
            // Coming soon extensions
            array(
                'id'          => 'personalizar-diseno-factura',
                'name'        => __( 'Personalizar diseño factura', 'freefactu' ),
                'description' => __( 'Personaliza el diseño de tus facturas: logotipo, colores, tipografía y distribución de los elementos para reflejar la identidad de tu marca.', 'freefactu' ),
                'icon'        => 'dashicons-art',
                'required'    => false,
                'active'      => false,
                'version'     => '-',
                'author'      => 'Freefactu',
                'coming_soon' => true,
            ),
        );

        /**
         * Filter the list of available extensions.
         *
         * @param array $extensions Array of extension data.
         */
        return apply_filters( 'freefactu_extensions', $extensions );
    }

    /**
     * Check if an extension is active.
     *
     * @param string $extension_id The extension ID.
     * @return bool Whether the extension is active.
     */
    public static function is_extension_active( $extension_id ) {
        $active_extensions = get_option( 'freefactu_active_extensions', array() );
        return in_array( $extension_id, $active_extensions, true );
    }

    /**
     * Activate an extension.
     *
     * @param string $extension_id The extension ID.
     * @return bool Whether the activation was successful.
     */
    public static function activate_extension( $extension_id ) {
        $extensions = self::get_extensions();
        $extension  = null;

        foreach ( $extensions as $ext ) {
            if ( $ext['id'] === $extension_id ) {
                $extension = $ext;
                break;
            }
        }

        if ( ! $extension || $extension['required'] ) {
            return false;
        }

        $active_extensions = get_option( 'freefactu_active_extensions', array() );

        if ( ! in_array( $extension_id, $active_extensions, true ) ) {
            $active_extensions[] = $extension_id;
            update_option( 'freefactu_active_extensions', $active_extensions );
        }

        /**
         * Fires after an extension is activated.
         *
         * @param string $extension_id The extension ID.
         * @param array  $extension    The extension data.
         */
        do_action( 'freefactu_extension_activated', $extension_id, $extension );

        return true;
    }

    /**
     * Deactivate an extension.
     *
     * @param string $extension_id The extension ID.
     * @return bool Whether the deactivation was successful.
     */
    public static function deactivate_extension( $extension_id ) {
        $extensions = self::get_extensions();
        $extension  = null;

        foreach ( $extensions as $ext ) {
            if ( $ext['id'] === $extension_id ) {
                $extension = $ext;
                break;
            }
        }

        if ( ! $extension || $extension['required'] ) {
            return false;
        }

        $active_extensions = get_option( 'freefactu_active_extensions', array() );
        $key               = array_search( $extension_id, $active_extensions, true );

        if ( false !== $key ) {
            unset( $active_extensions[ $key ] );
            update_option( 'freefactu_active_extensions', array_values( $active_extensions ) );
        }

        /**
         * Fires after an extension is deactivated.
         *
         * @param string $extension_id The extension ID.
         * @param array  $extension    The extension data.
         */
        do_action( 'freefactu_extension_deactivated', $extension_id, $extension );

        return true;
    }

    /**
     * AJAX handler for toggling extension state.
     *
     * @return void
     */
    public function ajax_toggle_extension() {
        check_ajax_referer( 'freefactu_toggle_extension', 'nonce' );

        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( array( 'message' => __( 'Permiso denegado.', 'freefactu' ) ) );
        }

        $extension_id = isset( $_POST['extension_id'] ) ? sanitize_text_field( wp_unslash( $_POST['extension_id'] ) ) : '';
        $action       = isset( $_POST['toggle_action'] ) ? sanitize_text_field( wp_unslash( $_POST['toggle_action'] ) ) : '';

        if ( empty( $extension_id ) || empty( $action ) ) {
            wp_send_json_error( array( 'message' => __( 'Datos inválidos.', 'freefactu' ) ) );
        }

        if ( 'activate' === $action ) {
            $result = self::activate_extension( $extension_id );
            if ( $result ) {
                wp_send_json_success( array(
                    'message' => __( 'Extensión activada correctamente.', 'freefactu' ),
                    'active'  => true,
                ) );
            }
        } elseif ( 'deactivate' === $action ) {
            $result = self::deactivate_extension( $extension_id );
            if ( $result ) {
                wp_send_json_success( array(
                    'message' => __( 'Extensión desactivada correctamente.', 'freefactu' ),
                    'active'  => false,
                ) );
            }
        }

        wp_send_json_error( array( 'message' => __( 'No se pudo realizar la acción.', 'freefactu' ) ) );
    }

    /**
     * Render the extensions page.
     *
     * @return void
     */
    public static function render_extensions_page() {
        $extensions = self::get_extensions();
        include FREEFACTU_PLUGIN_DIR . 'includes/admin/views/extensions-page.php';
    }
}

// Initialize the extensions manager
Freefactu_Extensions::instance();
