<?php
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

/**
 * Handles frontend and admin assets.
 */
class NNAXFUF_Assets {

    /**
     * Version / asset version string.
     * @var string
     */
    private $version;

    public function __construct( $version ) {
        $this->version = $version;
        add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_frontend_assets' ) );
    }

    /**
     * Assets constructor.
     *
     * @param string $version Asset version string (plugin version or filemtime).
     */

    public function enqueue_frontend_assets() {
        $settings = NNAXFUF_Helpers::get_settings();
        $share_options = isset( $settings['share_options'] ) && is_array( $settings['share_options'] )
            ? $settings['share_options']
            : array();

        if ( is_admin() || wp_doing_ajax() || wp_doing_cron() ) {
                return;
        }
        if ( defined( 'REST_REQUEST' ) && REST_REQUEST ) {
                return;
        }
        if ( defined( 'WP_CLI' ) && WP_CLI ) {
                return;
        }

        $load_plugin_uikit = ! empty( $settings['load_plugin_uikit'] ) && ! NNAXFUF_Helpers::is_yootheme_active();

        if ( $load_plugin_uikit ) {
            wp_register_style(
                'nnax-fm-uikit-css',
                NNAXFUF_PLUGIN_URL . 'assets/css/uikit.min.css',
                array(),
                $this->version
            );

            wp_register_script(
                'nnax-fm-uikit-js',
                NNAXFUF_PLUGIN_URL . 'assets/js/uikit.min.js',
                array(),
                $this->version,
                true
            );

            wp_register_script(
                'nnax-fm-uikit-icons',
                NNAXFUF_PLUGIN_URL . 'assets/js/uikit-icons.min.js',
                array( 'nnax-fm-uikit-js' ),
                $this->version,
                true
            );
        }

        wp_register_style(
            'nnax-fm-style',
            NNAXFUF_PLUGIN_URL . 'assets/css/style.css',
            array(),
            $this->version
        );

        $css_vars = $this->build_frontend_css_vars( $settings );
        if ( $css_vars !== '' ) {
            wp_add_inline_style( 'nnax-fm-style', $css_vars );
        }

        // Scripts registrieren (aufgeteilt in mehrere Dateien, ohne Build-Step)
        $core_deps = array( 'jquery' );
        if ( $load_plugin_uikit ) {
            $core_deps[] = 'nnax-fm-uikit-js';
        }
        wp_register_script(
            'nnax-fm-core',
            NNAXFUF_PLUGIN_URL . 'assets/js/modules/core.js',
            $core_deps,
            $this->version,
            true
        );
        // Allow the Sharing Addon to provide its own share.js. When present
        // register the handle pointing to the addon file so the addon can
        // override the frontend behavior.
        $share_script_src = NNAXFUF_PLUGIN_URL . 'assets/js/modules/share.js';
        if ( defined( 'NNAXFUF_SHARE_ADDON_PATH' ) && defined( 'NNAXFUF_SHARE_ADDON_URL' ) ) {
            $addon_path = rtrim( NNAXFUF_SHARE_ADDON_PATH, '/' ) . '/assets/js/modules/share.js';
            if ( file_exists( $addon_path ) ) {
                $share_script_src = rtrim( NNAXFUF_SHARE_ADDON_URL, '/' ) . '/assets/js/modules/share.js';
            }
        }

        wp_register_script(
            'nnax-fm-share',
            $share_script_src,
            array( 'nnax-fm-core' ),
            $this->version,
            true
        );
        wp_register_script(
            'nnax-fm-detail',
            NNAXFUF_PLUGIN_URL . 'assets/js/modules/detail.js',
            array( 'nnax-fm-core' ),
            $this->version,
            true
        );
        wp_register_script(
            'nnax-fm-upload',
            NNAXFUF_PLUGIN_URL . 'assets/js/modules/upload.js',
            array( 'nnax-fm-core' ),
            $this->version,
            true
        );
        wp_register_script(
            'nnax-fm-folder',
            NNAXFUF_PLUGIN_URL . 'assets/js/modules/folder.js',
            array( 'nnax-fm-core' ),
            $this->version,
            true
        );
        wp_register_script(
            'nnax-fm-preview',
            NNAXFUF_PLUGIN_URL . 'assets/js/modules/preview.js',
            array( 'nnax-fm-core' ),
            $this->version,
            true
        );
        wp_register_script(
            'nnax-fm-bulk',
            NNAXFUF_PLUGIN_URL . 'assets/js/modules/bulk.js',
            array( 'nnax-fm-core' ),
            $this->version,
            true
        );
        wp_register_script(
            'nnax-fm-settings',
            NNAXFUF_PLUGIN_URL . 'assets/js/modules/settings.js',
            array( 'nnax-fm-core' ),
            $this->version,
            true
        );
        wp_register_script(
            'nnax-fm-rows',
            NNAXFUF_PLUGIN_URL . 'assets/js/modules/rows.js',
            array(),
            $this->version,
            true
        );

        // Backward-compatible main handle. Enqueuing this loads all split files.
        $sharing_active = defined( 'NNAXFUF_SHARE_ADDON_PATH' ) && file_exists( rtrim( NNAXFUF_SHARE_ADDON_PATH, '/' ) . '/assets/js/modules/share.js' );

        $main_deps = array(
            'nnax-fm-core',
            'nnax-fm-detail',
            'nnax-fm-upload',
            'nnax-fm-folder',
            'nnax-fm-preview',
            'nnax-fm-bulk',
            'nnax-fm-settings',
            'nnax-fm-rows',
        );

        if ( $load_plugin_uikit ) {
            $main_deps[] = 'nnax-fm-uikit-icons';
        }

        if ( $sharing_active ) {
            // Only include share module when the Sharing Addon provides it.
            $main_deps[] = 'nnax-fm-share';
        }

        wp_register_script(
            'nnax-fm-script',
            NNAXFUF_PLUGIN_URL . 'assets/js/nnax-fm.js',
            $main_deps,
            $this->version,
            true
        );

        $current_user = wp_get_current_user();
        $default_msg = __( "Hello,\n\nI have shared \"{item_title}\" with you.\n\nYou can now find it in the file manager on the website: {site_url}\n\n{owner_name}", 'nnax-frontend-user-files' );
        $notif_msg_template = isset( $share_options['default_notification_msg'] ) ? $share_options['default_notification_msg'] : $default_msg;

        wp_localize_script(
            'nnax-fm-core',
            'nnaxFmAjax',
            array(
                'ajax_url'           => admin_url( 'admin-ajax.php' ),
                'nonce'              => wp_create_nonce( 'nnaxfuf_search_users' ),
                'item_details_nonce' => wp_create_nonce( 'nnaxfuf_item_details' ),
                'rename_nonce'       => wp_create_nonce( 'nnaxfuf_rename_item' ),
                'share_state_nonce'  => wp_create_nonce( 'nnaxfuf_get_item_share_state' ),
                'download_nonce'     => wp_create_nonce( 'nnaxfuf_download' ),
                'zip_download_nonce' => wp_create_nonce( 'nnaxfuf_zip_download' ),
                'current_user_id'    => (int) get_current_user_id(),
                'current_user_name'  => $current_user->display_name,
                'site_url'           => site_url(),
                'default_notification_msg' => $notif_msg_template,
                'share_options'      => array(
                    'allow_time_limit'   => ! empty( $share_options['allow_time_limit'] ),
                    'allow_owner_rights' => ! empty( $share_options['allow_owner_rights'] ),
                    'allow_shared_folder_file_delete' => ! empty( $share_options['allow_shared_folder_file_delete'] ),
                ),
                'i18n' => array(
                    'share_empty'                       => __( 'Currently shared with nobody.', 'nnax-frontend-user-files' ),
                    'search_placeholder_default'        => __( 'Enter name, username or email', 'nnax-frontend-user-files' ),
                    'share_title_item'                  => __( 'Share Item', 'nnax-frontend-user-files' ),
                    'share_title_folder'                => __( 'Share Folder', 'nnax-frontend-user-files' ),
                    'share_title_file'                  => __( 'Share', 'nnax-frontend-user-files' ),
                    'search_placeholder_folder'         => __( 'Search person', 'nnax-frontend-user-files' ),
                    'search_placeholder_file'           => __( 'Search person', 'nnax-frontend-user-files' ),
                    'role_normal'                       => __( 'Normal', 'nnax-frontend-user-files' ),
                    'role_manager'                      => __( 'Manager', 'nnax-frontend-user-files' ),
                    'role_admin'                        => __( 'Admin', 'nnax-frontend-user-files' ),
                    'label_role'                        => __( 'Role', 'nnax-frontend-user-files' ),
                    'label_from'                        => __( 'From', 'nnax-frontend-user-files' ),
                    'label_until'                       => __( 'Until', 'nnax-frontend-user-files' ),
                    'remove'                            => __( 'Remove', 'nnax-frontend-user-files' ),
                    'loading_existing_shares'           => __( 'Loading existing shares...', 'nnax-frontend-user-files' ),
                    'shares_load_failed'                => __( 'Could not load existing shares.', 'nnax-frontend-user-files' ),
                    'network_error_existing_shares'     => __( 'Network error while loading existing shares.', 'nnax-frontend-user-files' ),
                    'search_loading'                    => __( 'Searching for matching users...', 'nnax-frontend-user-files' ),
                    'search_no_results'                 => __( 'No matching users found.', 'nnax-frontend-user-files' ),
                    'search_failed'                     => __( 'Search failed. Please try again.', 'nnax-frontend-user-files' ),
                    'owner_suffix'                      => __( '(Owner)', 'nnax-frontend-user-files' ),
                    'roles_loading'                     => __( 'Loading shared roles...', 'nnax-frontend-user-files' ),
                    'roles_load_failed'                 => __( 'Error while loading roles.', 'nnax-frontend-user-files' ),
                    'network_error_roles'               => __( 'Network error while loading roles.', 'nnax-frontend-user-files' ),
                    'upload_list_empty'                 => __( 'No files selected yet.', 'nnax-frontend-user-files' ),
                    'bulk_actions'                      => __( 'Bulk actions', 'nnax-frontend-user-files' ),
                    'bulk_delete_confirm'               => __( 'Delete selected items?', 'nnax-frontend-user-files' ),
                    'bulk_delete_recursive_confirm'     => __( 'Delete selected items recursively (including subfolders)?', 'nnax-frontend-user-files' ),
                    'bulk_move_select_items'            => __( 'Select at least one item.', 'nnax-frontend-user-files' ),
                    'bulk_move_requires_permission'     => __( 'Selection contains items you cannot move.', 'nnax-frontend-user-files' ),
                    'confirm_cancel'                    => __( 'Cancel', 'nnax-frontend-user-files' ),
                    'confirm_ok'                        => __( 'Confirm', 'nnax-frontend-user-files' ),
                    'confirm_delete'                    => __( 'Delete', 'nnax-frontend-user-files' ),
                    'preview_hide'                      => __( 'Hide image preview', 'nnax-frontend-user-files' ),
                    'preview_show'                      => __( 'Show image preview', 'nnax-frontend-user-files' ),
                    'back_one_level'                    => __( 'Back', 'nnax-frontend-user-files' ),
                    'folder_label'                      => __( 'Folder', 'nnax-frontend-user-files' ),
                    'fixed_extension'                   => __( 'File extension is fixed:', 'nnax-frontend-user-files' ),
                    'no_meta_fields_configured'         => __( 'No meta fields configured.', 'nnax-frontend-user-files' ),
                    'image_preview_alt'                 => __( 'File preview', 'nnax-frontend-user-files' ),
                    'pdf_preview_title'                 => __( 'PDF preview', 'nnax-frontend-user-files' ),
                    'no_preview_for_type'               => __( 'No preview available for this file type.', 'nnax-frontend-user-files' ),
                    'download'                          => __( 'Download', 'nnax-frontend-user-files' ),
                    'details_load_failed'               => __( 'Details could not be loaded.', 'nnax-frontend-user-files' ),
                    'network_error_details'             => __( 'Network error while loading details.', 'nnax-frontend-user-files' ),
                    'loading'                           => __( 'Loading...', 'nnax-frontend-user-files' ),
                    'loading_history'                   => __( 'Loading history...', 'nnax-frontend-user-files' ),
                    'no_history'                        => __( 'No activity recorded.', 'nnax-frontend-user-files' ),
                    'error_missing_item_id'             => __( 'Error: No item ID found.', 'nnax-frontend-user-files' ),
                    'please_enter_name'                 => __( 'Please enter a name.', 'nnax-frontend-user-files' ),
                    'saving'                            => __( 'Saving...', 'nnax-frontend-user-files' ),
                    'save_changes'                      => __( 'Save changes', 'nnax-frontend-user-files' ),
                    'network_error_save'                => __( 'Network error while saving.', 'nnax-frontend-user-files' ),
                    'link_copied'                       => __( 'Link copied to clipboard.', 'nnax-frontend-user-files' ),
                    'move_file_foreign_owner_confirm'   => __( 'If you move this file into a folder owned by someone else, you may lose ownership rights if you later lose access to that folder. Continue?', 'nnax-frontend-user-files' ),
                    'move_file_foreign_owner_confirm_ok' => __( 'Yes, move file', 'nnax-frontend-user-files' ),
                    'move_file_foreign_owner_confirm_cancel' => __( 'Cancel', 'nnax-frontend-user-files' ),
                ),
                // Supported values: table, card, compact.
                'share_layout'       => 'compact',
            )
        );
    }

    /**
     * Enqueue styles used on the plugin settings pages.
     *
     * @param string $hook Current admin page hook.
     * @param array $settings_hooks Array of plugin settings hooks where assets should be enqueued.
     */
    public function enqueue_settings_assets( $hook, array $settings_hooks ) {
        if ( empty( $settings_hooks ) || ! in_array( $hook, $settings_hooks, true ) ) {
            return;
        }

        wp_enqueue_style(
            'nnax-fm-admin-ui',
            NNAXFUF_PLUGIN_URL . 'assets/css/nnax-admin-ui.css',
            array(),
            $this->asset_version( 'assets/css/nnax-admin-ui.css' )
        );

        wp_enqueue_style(
            'nnax-fm-admin-settings',
            NNAXFUF_PLUGIN_URL . 'assets/css/admin-settings.css',
            array( 'nnax-fm-admin-ui' ),
            $this->asset_version( 'assets/css/admin-settings.css' )
        );
    }

    /**
     * Resolve an asset version string based on file modification time when available.
     *
     * @param string $relative_path Relative path under plugin root to the asset file.
     * @return string
     */
    private function asset_version( $relative_path ) {
        $path = NNAXFUF_PLUGIN_PATH . ltrim( $relative_path, '/' );
        if ( file_exists( $path ) ) {
            return (string) ( filemtime( $path ) ?: $this->version );
        }

        return $this->version;
    }

    /**
     * Build inline CSS variables for the frontend wrapper.
     *
     * @param array $settings Plugin settings.
     * @return string
     */
    private function build_frontend_css_vars( array $settings ) {
        $ui_colors = isset( $settings['ui_colors'] ) && is_array( $settings['ui_colors'] ) ? $settings['ui_colors'] : array();
        $badge_colors = isset( $settings['badge_colors'] ) && is_array( $settings['badge_colors'] ) ? $settings['badge_colors'] : array();

        $ui_defs = NNAXFUF_Helpers::get_ui_color_definitions();
        $badge_defs = NNAXFUF_Helpers::get_badge_color_definitions();

        $css_vars = array();

        foreach ( $ui_defs as $key => $def ) {
            if ( empty( $def['css_var'] ) || empty( $ui_colors[ $key ] ) ) {
                continue;
            }

            $hex = sanitize_hex_color( (string) $ui_colors[ $key ] );
            if ( $hex ) {
                $css_vars[] = $def['css_var'] . ':' . $hex;
            }
        }

        foreach ( $badge_defs as $key => $def ) {
            if ( empty( $def['css_var'] ) || empty( $badge_colors[ $key ] ) ) {
                continue;
            }

            $hex = sanitize_hex_color( (string) $badge_colors[ $key ] );
            if ( $hex ) {
                $css_vars[] = $def['css_var'] . ':' . $hex;
            }
        }

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

        return '.nnaxfuf-file-manager,.nnaxfuf-modal,.nnaxfuf-actions-dropdown{' . implode( ';', $css_vars ) . ';}';
    }

}
