<?php

namespace HugeAddons\Classes;

class ExtensionManager {
    private $extensions = [];
    private $extensions_flat = [];
    private $enabled = [];

    public function __construct() {
        $this->load_extensions(); 
        $this->load_enabled_extensions(); 
        $this->init_hooks();
    }

    private function load_extensions() { 

        if ( ! defined( 'THHA_EXTENSIONS_JSON' ) || ! file_exists( THHA_EXTENSIONS_JSON ) ) {
            error_log( 'Huge Addons: Extensions JSON file not found at ' . THHA_EXTENSIONS_JSON );
            return;  // Missing: Graceful fail
        }

        $json = file_get_contents( THHA_EXTENSIONS_JSON );
        $all_extensions = json_decode( $json, true );

        if ( json_last_error() !== JSON_ERROR_NONE ) {  // Missing: JSON validation
            error_log( 'Huge Addons: Invalid JSON in extensions file: ' . json_last_error_msg() );
            return;
        }

        if ( ! is_array( $all_extensions ) ) {
            error_log( 'Huge Addons: Extensions JSON is not an array.' );
            return;
        }

        foreach ( $all_extensions as $extension_category => $extensions_list ) {  // Fixed: Naming
            if ( ! is_array( $extensions_list ) ) continue;

            foreach ( $extensions_list as $extension ) {
                if ( ! isset( $extension['class'] ) || ! isset( $extension['mainClass'] ) ) continue;  // Missing: Basic validation

                $this->extensions[ $extension_category ][ $extension['class'] ] = $extension;
                $this->extensions_flat[ $extension['class'] ] = $extension;
            }
        }

        // pretty_log( '$this->extensions', $this->extensions );  // Uncomment for debug
        // pretty_log( '$this->extensions_flat', $this->extensions_flat );
    }

    private function load_enabled_extensions() { 
        $enabled = get_option( 'thha_enabled_extensions', null );  // Fixed: Option name consistency

        if ( is_null( $enabled ) ) {
            $enabled = [ 'THHA_Custom_CSS' ];  // Fixed: Simple array, no numeric key
            update_option( 'thha_enabled_extensions', $enabled );
        }

        // Missing: Filter to valid extensions only (defensive)
        $this->enabled = array_filter( $enabled, function( $key ) {
            return isset( $this->extensions_flat[ $key ] );
        } );
    }

    public function get_all_extensions() { 
        return $this->extensions;
    }

    public function get_enabled_extensions() { 
        return $this->enabled;
    }

    public function save_enabled_extensions( $enabled ) { 
        // Missing: Validate against known extensions
        $valid_enabled = array_filter( $enabled, function( $key ) {
            return isset( $this->extensions_flat[ $key ] ) && $this->extensions_flat[ $key ]['status'] === 'available';
        } );

        $this->enabled = array_values( $valid_enabled );  // Re-index as simple array
        update_option( 'thha_enabled_extensions', $this->enabled );
    }

    private function init_hooks() {
        add_action( 'wp_ajax_thha_get_extensions', [ $this, 'ajax_get_extensions' ], 10, 0 );  // Fixed: Action name; explicit priority
        add_action( 'wp_ajax_thha_save_extensions', [ $this, 'ajax_save_extensions' ], 10, 0 );  // Fixed: Action name (was addons)
    }

    public function register_extensions( $extensions_manager ) {  // Fixed: Method name; param is Elementor\Extensions_Manager
        if ( ! $extensions_manager instanceof \Elementor\Core\Base\Document ) {  // Missing: Type check (adjust if wrong)
            error_log( 'Huge Addons: Invalid extensions manager passed to register_extensions.' );
            return;
        }

        foreach ( $this->enabled as $extension_key ) {
            if ( ! isset( $this->extensions_flat[ $extension_key ] ) ) continue;

            $extension = $this->extensions_flat[ $extension_key ];
            if ( $extension['status'] !== 'available' ) continue;

            if ( class_exists( $extension['mainClass'] ) ) {  // Missing: Class exists check
                try {
                    $extensions_manager->register( new $extension['mainClass']() );
                } catch ( Exception $e ) {
                    error_log( 'Huge Addons: Failed to register extension ' . $extension_key . ': ' . $e->getMessage() );
                }
            } else {
                error_log( 'Huge Addons: Class not found for extension: ' . $extension['mainClass'] );
            }
        }
    }

    public function ajax_get_extensions() {  // Fixed: Method name
        // Fixed: Standardize nonce to 'thha_extensions_nonce' (update frontend)
        $nonce_valid = check_ajax_referer( 'thha_extensions_nonce', 'nonce', false );
        if ( ! $nonce_valid ) {
            wp_send_json_error( 'Invalid Nonce', 403 );
        }

        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( 'Insufficient Permission', 403 );
        }

        $all_extensions = $this->get_all_extensions();
        $enabled = $this->get_enabled_extensions();

        // Missing: Include status/pro for UI (e.g., disable unavailable in JS)
        $response = [
            'all' => $all_extensions,
            'enabled' => $enabled
        ];

        wp_send_json_success( $response );
    }

    public function ajax_save_extensions() {  // Fixed: Method name
        // Fixed: Standardize nonce
        check_ajax_referer( 'thha_extensions_nonce', '_wpnonce' );

        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( 'Insufficient Permission', 403 );
        }

        // Fixed: POST key typo; sanitize array properly
        $enabled = isset( $_POST['enabled_extensions'] ) ? array_map( 'sanitize_text_field', wp_unslash( $_POST['enabled_extensions'] ) ) : [];
        $this->save_enabled_extensions( $enabled );

        wp_send_json_success( [ 'message' => 'Settings saved successfully.' ] );
    }
}