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

require_once NNAXFUF_PLUGIN_PATH . 'includes/class-nnaxfuf-settings-admin-ui-trait.php';

/**
 * Handles admin settings pages.
 */
class NNAXFUF_Settings {
    use NNAXFUF_Settings_Admin_UI_Trait;

    /** @var string */
    private $menu_slug = 'nnax-user-files';

    /** @var array */
    private $settings_hooks = array();

    /** @var NNAXFUF_Assets|null */
    private $assets;

    public function __construct( $migration = null, $assets = null ) {
        $this->assets    = ( $assets instanceof NNAXFUF_Assets ) ? $assets : null;

        add_action( 'admin_menu', array( $this, 'add_admin_menu' ) );
        add_action( 'admin_init', array( $this, 'register_settings' ) );
        add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_admin_menu_icon_styles' ) );
        add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_admin_assets' ) );
    }

    public function enqueue_admin_menu_icon_styles() {
        wp_enqueue_style(
            'nnax-fm-admin-menu-icon',
            NNAXFUF_PLUGIN_URL . 'assets/css/admin-menu-icon.css',
            array(),
                file_exists( NNAXFUF_PLUGIN_PATH . 'assets/css/admin-menu-icon.css' ) ? (string) filemtime( NNAXFUF_PLUGIN_PATH . 'assets/css/admin-menu-icon.css' ) : '1.0.4'
        );
    }

    public function add_admin_menu() {
        $main_hook = add_menu_page(
            __( 'User Files', 'nnax-frontend-user-files' ),
            __( 'User Files', 'nnax-frontend-user-files' ),
            'manage_options',
            $this->menu_slug,
            array( $this, 'render_general_page' ),
            NNAXFUF_PLUGIN_URL . 'assets/images/nnaxfuf-icon.png',
            58
        );

        $settings_hook = add_submenu_page(
            $this->menu_slug,
            __( 'Settings', 'nnax-frontend-user-files' ),
            __( 'Settings', 'nnax-frontend-user-files' ),
            'manage_options',
            $this->menu_slug,
            array( $this, 'render_general_page' )
        );

        // Hidden settings subpages: reachable via header navigation, but not listed in WP admin menu.
        $general_hook = add_submenu_page(
            null,
            __( 'General', 'nnax-frontend-user-files' ),
            __( 'General', 'nnax-frontend-user-files' ),
            'manage_options',
            'nnax-user-files-general',
            array( $this, 'render_general_page' )
        );

        $design_hook = add_submenu_page(
            null,
            __( 'Design', 'nnax-frontend-user-files' ),
            __( 'Design', 'nnax-frontend-user-files' ),
            'manage_options',
            'nnax-user-files-design',
            array( $this, 'render_design_page' )
        );

        $upload_hook = add_submenu_page(
            null,
            __( 'Upload', 'nnax-frontend-user-files' ),
            __( 'Upload', 'nnax-frontend-user-files' ),
            'manage_options',
            'nnax-user-files-upload',
            array( $this, 'render_upload_page' )
        );

        // Register a placeholder sharing admin page only when the Sharing
        // Addon is NOT active. The real addon will register the page when
        // present (same behavior as Migration addon placeholder).
        $sharing_hook = null;
        if ( ! class_exists( 'NNAXFUF_Sharing_Addon_Admin' ) ) {
            $sharing_hook = add_submenu_page(
                null,
                __( 'Sharing', 'nnax-frontend-user-files' ),
                __( 'Sharing', 'nnax-frontend-user-files' ),
                'manage_options',
                'nnax-user-files-sharing',
                array( $this, 'render_sharing_page' )
            );
        }

        $licenses_hook = add_submenu_page(
            $this->menu_slug,
            __( 'Licenses', 'nnax-frontend-user-files' ),
            __( 'Licenses', 'nnax-frontend-user-files' ),
            'manage_options',
            'nnax-user-files-licenses',
            array( $this, 'render_licenses_page' )
        );

        $this->settings_hooks = array_filter(
            array(
                $main_hook,
                $settings_hook,
                $general_hook,
                $design_hook,
                $upload_hook,
                $sharing_hook,
                $licenses_hook,
            )
        );
    }

    public function enqueue_admin_assets( $hook ) {
        if ( empty( $this->settings_hooks ) || ! in_array( $hook, $this->settings_hooks, true ) ) {
            return;
        }

        if ( $this->assets instanceof NNAXFUF_Assets ) {
            $this->assets->enqueue_settings_assets( $hook, $this->settings_hooks );
        } else {
            wp_enqueue_style(
                'nnax-fm-admin-ui',
                NNAXFUF_PLUGIN_URL . 'assets/css/nnax-admin-ui.css',
                array(),
                file_exists( NNAXFUF_PLUGIN_PATH . 'assets/css/nnax-admin-ui.css' ) ? (string) filemtime( NNAXFUF_PLUGIN_PATH . 'assets/css/nnax-admin-ui.css' ) : '1.0.4'
            );
            wp_enqueue_style(
                'nnax-fm-admin-settings',
                NNAXFUF_PLUGIN_URL . 'assets/css/admin-settings.css',
                array( 'nnax-fm-admin-ui' ),
                file_exists( NNAXFUF_PLUGIN_PATH . 'assets/css/admin-settings.css' ) ? (string) filemtime( NNAXFUF_PLUGIN_PATH . 'assets/css/admin-settings.css' ) : '1.0.4'
            );
        }

        wp_enqueue_style( 'wp-color-picker' );
        wp_enqueue_script( 'wp-color-picker' );
        wp_enqueue_script(
            'nnax-fm-admin-settings',
            NNAXFUF_PLUGIN_URL . 'assets/js/admin-settings.js',
            array( 'jquery', 'wp-color-picker' ),
            file_exists( NNAXFUF_PLUGIN_PATH . 'assets/js/admin-settings.js' ) ? (string) filemtime( NNAXFUF_PLUGIN_PATH . 'assets/js/admin-settings.js' ) : '1.0.4',
            true
        );

        wp_localize_script(
            'nnax-fm-admin-settings',
            'nnaxAdminSettings',
            array(
                'optionName' => NNAXFUF_Plugin::OPTION_SETTINGS,
                'i18n'       => array(
                    'changeOrder'      => __( 'Change order', 'nnax-frontend-user-files' ),
                    'labelPlaceholder' => __( 'e.g. Description', 'nnax-frontend-user-files' ),
                    'text'             => __( 'Text', 'nnax-frontend-user-files' ),
                    'textarea'         => __( 'Textarea', 'nnax-frontend-user-files' ),
                    'date'             => __( 'Date', 'nnax-frontend-user-files' ),
                    'number'           => __( 'Number', 'nnax-frontend-user-files' ),
                    'email'            => __( 'Email', 'nnax-frontend-user-files' ),
                    'url'              => __( 'URL', 'nnax-frontend-user-files' ),
                    'remove'           => __( 'Remove', 'nnax-frontend-user-files' ),
                ),
            )
        );
    }

    public function register_settings() {
        register_setting(
            'nnaxfuf_settings_group',
            NNAXFUF_Plugin::OPTION_SETTINGS,
            array( $this, 'sanitize_settings' )
        );
    }

    public function sanitize_settings( $input ) {
        $input = is_array( $input ) ? $input : array();


        $defaults = NNAXFUF_Helpers::get_default_settings();
        $current  = get_option( NNAXFUF_Plugin::OPTION_SETTINGS, array() );
        $default_main_headline = isset( $defaults['main_headline'] ) ? (string) $defaults['main_headline'] : __( 'My Files', 'nnax-frontend-user-files' );

        $output = is_array( $current ) ? $current : array();

        if ( ! isset( $output['custom_meta_fields'] ) || ! is_array( $output['custom_meta_fields'] ) ) {
            $output['custom_meta_fields'] = array();
        }

        if ( ! isset( $output['quota'] ) || ! is_array( $output['quota'] ) ) {
            $output['quota'] = array();
        }

        if ( ! isset( $output['main_headline'] ) ) {
            $output['main_headline'] = $default_main_headline;
        }

        if ( ! isset( $output['allowed_types'] ) ) {
            $output['allowed_types'] = '';
        }
        if ( ! isset( $output['load_plugin_uikit'] ) ) {
            $output['load_plugin_uikit'] = isset( $defaults['load_plugin_uikit'] ) ? (int) $defaults['load_plugin_uikit'] : 1;
        }
        if ( ! isset( $output['enforce_mime_check'] ) ) {
            $output['enforce_mime_check'] = isset( $defaults['enforce_mime_check'] ) ? (int) $defaults['enforce_mime_check'] : 1;
        }
        if ( ! isset( $output['delete_all_on_uninstall'] ) ) {
            $output['delete_all_on_uninstall'] = isset( $defaults['delete_all_on_uninstall'] ) ? (int) $defaults['delete_all_on_uninstall'] : 0;
        }
        if ( ! isset( $output['max_file_size_mb'] ) ) {
            $output['max_file_size_mb'] = isset( $defaults['max_file_size_mb'] ) ? max( 0, (float) $defaults['max_file_size_mb'] ) : 0;
        }
        if ( ! isset( $output['blocked_types'] ) ) {
            $output['blocked_types'] = isset( $defaults['blocked_types'] ) ? (string) $defaults['blocked_types'] : '';
        }
        if ( ! isset( $output['items_per_page'] ) ) {
            $output['items_per_page'] = isset( $defaults['items_per_page'] ) ? (int) $defaults['items_per_page'] : 20;
        }

        if ( isset( $input['items_per_page'] ) ) {
            $output['items_per_page'] = max( 1, absint( $input['items_per_page'] ) );
        }

        if ( array_key_exists( 'main_headline', $input ) ) {
            $headline = sanitize_text_field( (string) $input['main_headline'] );
            $headline = trim( $headline );
            if ( '' === $headline ) {
                $headline = $default_main_headline;
            }
            $output['main_headline'] = $headline;
        }

        if ( ! isset( $output['share_options'] ) || ! is_array( $output['share_options'] ) ) {
            $output['share_options'] = array();
        }

        if ( array_key_exists( 'custom_meta_fields', $input ) ) {
            $output['custom_meta_fields'] = array();
            if ( ! empty( $input['custom_meta_fields'] ) && is_array( $input['custom_meta_fields'] ) ) {
                $fields = array();
                foreach ( $input['custom_meta_fields'] as $row ) {
                    if ( ! is_array( $row ) ) {
                        continue;
                    }

                    $fields[] = array(
                        'key'   => isset( $row['key'] ) ? (string) $row['key'] : '',
                        'label' => isset( $row['label'] ) ? (string) $row['label'] : '',
                        'type'  => isset( $row['type'] ) ? (string) $row['type'] : 'text',
                    );
                }
                $output['custom_meta_fields'] = NNAXFUF_Helpers::normalize_custom_meta_fields( $fields );
            }
        }

        if ( array_key_exists( 'allowed_types', $input ) ) {
            $output['allowed_types'] = implode( ',', NNAXFUF_Helpers::normalize_safe_upload_extension_list( $input['allowed_types'] ) );
        }

        if ( array_key_exists( 'load_plugin_uikit', $input ) ) {
            $output['load_plugin_uikit'] = ! empty( $input['load_plugin_uikit'] ) ? 1 : 0;
        } else {
            $output['load_plugin_uikit'] = ! empty( $output['load_plugin_uikit'] ) ? 1 : 0;
        }

        if ( array_key_exists( 'enforce_mime_check', $input ) ) {
            $output['enforce_mime_check'] = ! empty( $input['enforce_mime_check'] ) ? 1 : 0;
        } else {
            $output['enforce_mime_check'] = ! empty( $output['enforce_mime_check'] ) ? 1 : 0;
        }

        if ( array_key_exists( 'delete_all_on_uninstall', $input ) ) {
            $output['delete_all_on_uninstall'] = ! empty( $input['delete_all_on_uninstall'] ) ? 1 : 0;
        } else {
            $output['delete_all_on_uninstall'] = ! empty( $output['delete_all_on_uninstall'] ) ? 1 : 0;
        }

        if ( array_key_exists( 'max_file_size_mb', $input ) ) {
            $max_file_size_mb = floatval( str_replace( ',', '.', (string) $input['max_file_size_mb'] ) );
            $output['max_file_size_mb'] = max( 0, $max_file_size_mb );
        } else {
            $output['max_file_size_mb'] = max( 0, (float) $output['max_file_size_mb'] );
        }

        if ( array_key_exists( 'blocked_types', $input ) ) {
            $blocked = '';
            if ( ! empty( $input['blocked_types'] ) ) {
                $parts = explode( ',', (string) $input['blocked_types'] );
                $parts = array_map( 'trim', $parts );
                $parts = array_filter( $parts );
                $parts = array_map(
                    function ( $ext ) {
                        $ext = ltrim( strtolower( $ext ), '.' );
                        return preg_replace( '/[^a-z0-9]/', '', $ext );
                    },
                    $parts
                );
                $blocked = implode( ',', array_unique( $parts ) );
            }
            $output['blocked_types'] = $blocked;
        }

        if ( array_key_exists( 'share_options', $input ) && is_array( $input['share_options'] ) ) {
            $output['share_options']['allow_time_limit'] = ! empty( $input['share_options']['allow_time_limit'] ) ? 1 : 0;
            $output['share_options']['allow_owner_rights'] = ! empty( $input['share_options']['allow_owner_rights'] ) ? 1 : 0;
            $output['share_options']['allow_shared_folder_file_delete'] = ! empty( $input['share_options']['allow_shared_folder_file_delete'] ) ? 1 : 0;
            $output['share_options']['allow_role_sharing'] = ! empty( $input['share_options']['allow_role_sharing'] ) ? 1 : 0;
            
            if ( isset( $input['share_options']['default_notification_msg'] ) ) {
                $output['share_options']['default_notification_msg'] = wp_kses_post( wp_unslash( $input['share_options']['default_notification_msg'] ) );
            } else {
                $output['share_options']['default_notification_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' );
            }

            if ( isset( $input['share_options']['allowed_target_roles'] ) && is_array( $input['share_options']['allowed_target_roles'] ) ) {
                $allowed_targets = array();
                foreach ( $input['share_options']['allowed_target_roles'] as $role_key => $targets ) {
                    if ( is_array( $targets ) ) {
                        $allowed_targets[ $role_key ] = array_map( 'sanitize_key', $targets );
                    }
                }
                $output['share_options']['allowed_target_roles'] = $allowed_targets;
            } else {
                $output['share_options']['allowed_target_roles'] = array();
            }
        } else {
            $current_share_options = isset( $output['share_options'] ) && is_array( $output['share_options'] ) ? $output['share_options'] : array();
            $output['share_options']['allow_time_limit'] = ! empty( $current_share_options['allow_time_limit'] ) ? 1 : 0;
            $output['share_options']['allow_owner_rights'] = ! empty( $current_share_options['allow_owner_rights'] ) ? 1 : 0;
            $output['share_options']['allow_shared_folder_file_delete'] = ! empty( $current_share_options['allow_shared_folder_file_delete'] ) ? 1 : 0;
            $output['share_options']['allow_role_sharing'] = ! empty( $current_share_options['allow_role_sharing'] ) ? 1 : 0;
            $output['share_options']['allowed_target_roles'] = isset( $current_share_options['allowed_target_roles'] ) ? $current_share_options['allowed_target_roles'] : array();
            
            $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' );
            $output['share_options']['default_notification_msg'] = isset( $current_share_options['default_notification_msg'] ) ? $current_share_options['default_notification_msg'] : $default_msg;
        }

        if ( array_key_exists( 'quota', $input ) ) {
            $output['quota'] = array();
            if ( ! empty( $input['quota'] ) && is_array( $input['quota'] ) ) {
                foreach ( $input['quota'] as $role => $data ) {
                    $max_files = isset( $data['max_files'] ) ? intval( $data['max_files'] ) : 0;
                    $max_mb    = isset( $data['max_mb'] ) ? floatval( str_replace( ',', '.', (string) $data['max_mb'] ) ) : 0;

                    $output['quota'][ $role ] = array(
                        'max_files' => max( 0, $max_files ),
                        'max_mb'    => max( 0, $max_mb ),
                    );
                }
            }
        }

        $ui_defs      = NNAXFUF_Helpers::get_ui_color_definitions();
        $ui_keys      = array_keys( $ui_defs );
        $default_ui   = ( isset( $defaults['ui_colors'] ) && is_array( $defaults['ui_colors'] ) ) ? $defaults['ui_colors'] : array();
        $current_ui   = ( isset( $output['ui_colors'] ) && is_array( $output['ui_colors'] ) ) ? $output['ui_colors'] : array();
        $output_ui    = array();

        foreach ( $ui_keys as $k ) {
            $current_hex = isset( $current_ui[ $k ] ) ? sanitize_hex_color( (string) $current_ui[ $k ] ) : false;
            if ( $current_hex ) {
                $output_ui[ $k ] = $current_hex;
            } elseif ( isset( $default_ui[ $k ] ) ) {
                $output_ui[ $k ] = sanitize_hex_color( (string) $default_ui[ $k ] ) ?: '';
            } else {
                $output_ui[ $k ] = '';
            }
        }

        if ( array_key_exists( 'ui_colors', $input ) && is_array( $input['ui_colors'] ) ) {
            foreach ( $ui_keys as $k ) {
                if ( ! array_key_exists( $k, $input['ui_colors'] ) ) {
                    continue;
                }

                $raw = trim( (string) $input['ui_colors'][ $k ] );
                $hex = sanitize_hex_color( $raw );
                if ( $hex ) {
                    $output_ui[ $k ] = $hex;
                }
            }
        }
        $output['ui_colors'] = $output_ui;

        $badge_defs      = NNAXFUF_Helpers::get_badge_color_definitions();
        $badge_keys      = array_keys( $badge_defs );
        $default_badges  = ( isset( $defaults['badge_colors'] ) && is_array( $defaults['badge_colors'] ) ) ? $defaults['badge_colors'] : array();
        $current_badges  = ( isset( $output['badge_colors'] ) && is_array( $output['badge_colors'] ) ) ? $output['badge_colors'] : array();
        $output_badges   = array();

        foreach ( $badge_keys as $k ) {
            $current_hex = isset( $current_badges[ $k ] ) ? sanitize_hex_color( (string) $current_badges[ $k ] ) : false;
            if ( $current_hex ) {
                $output_badges[ $k ] = $current_hex;
            } elseif ( isset( $default_badges[ $k ] ) ) {
                $output_badges[ $k ] = sanitize_hex_color( (string) $default_badges[ $k ] ) ?: '';
            } else {
                $output_badges[ $k ] = '';
            }
        }

        if ( array_key_exists( 'badge_colors', $input ) && is_array( $input['badge_colors'] ) ) {
            foreach ( $badge_keys as $k ) {
                if ( ! array_key_exists( $k, $input['badge_colors'] ) ) {
                    continue;
                }

                $raw = trim( (string) $input['badge_colors'][ $k ] );
                $hex = sanitize_hex_color( $raw );
                if ( $hex ) {
                    $output_badges[ $k ] = $hex;
                }
            }
        }
        $output['badge_colors'] = $output_badges;

        return $output;
    }

    private function get_page_context() {
        $defaults = NNAXFUF_Helpers::get_default_settings();
        $settings = NNAXFUF_Helpers::get_settings();

        global $wp_roles;
        $roles = isset( $wp_roles->roles ) ? $wp_roles->roles : array();

        return array(
            'defaults'  => $defaults,
            'settings'  => $settings,
            'roles'     => $roles,
        );
    }

    private function render_settings_page_template( $template, $context = array() ) {
        if ( ! is_array( $context ) ) {
            $context = array();
        }

        extract( $context, EXTR_SKIP );

        $template_path = NNAXFUF_PLUGIN_PATH . 'includes/settings-pages/' . $template . '.php';
        if ( file_exists( $template_path ) ) {
            require $template_path;
        }
    }

    public function render_general_page() {
        if ( ! current_user_can( 'manage_options' ) ) {
            return;
        }

        $ctx = $this->get_page_context();
        $settings = $ctx['settings'];
        $roles = $ctx['roles'];

        $custom_meta_fields = isset( $settings['custom_meta_fields'] ) && is_array( $settings['custom_meta_fields'] )
            ? $settings['custom_meta_fields']
            : array();
        $allowed = isset( $settings['allowed_types'] ) ? $settings['allowed_types'] : '';

        $this->render_settings_page_template(
            'general',
            array(
                'settings'           => $settings,
                'roles'              => $roles,
                'custom_meta_fields' => $custom_meta_fields,
                'allowed'            => $allowed,
            )
        );
    }

    public function render_design_page() {
        if ( ! current_user_can( 'manage_options' ) ) {
            return;
        }

        $ctx = $this->get_page_context();
        $settings = $ctx['settings'];
        $defaults = $ctx['defaults'];

        $badge_colors = ! empty( $settings['badge_colors'] ) ? $settings['badge_colors'] : array();
        $ui_colors    = ! empty( $settings['ui_colors'] ) ? $settings['ui_colors'] : array();

        $this->render_settings_page_template(
            'design',
            array(
                'settings'     => $settings,
                'defaults'     => $defaults,
                'badge_colors' => $badge_colors,
                'ui_colors'    => $ui_colors,
            )
        );
    }

    public function render_upload_page() {
        if ( ! current_user_can( 'manage_options' ) ) {
            return;
        }

        $ctx = $this->get_page_context();
        $settings = $ctx['settings'];
        $roles = $ctx['roles'];
        $allowed = isset( $settings['allowed_types'] ) ? $settings['allowed_types'] : '';

        $this->render_settings_page_template(
            'upload',
            array(
                'settings' => $settings,
                'roles'    => $roles,
                'allowed'  => $allowed,
            )
        );
    }

    public function render_sharing_page() {
        if ( ! current_user_can( 'manage_options' ) ) {
            return;
        }

        $ctx = $this->get_page_context();
        $settings = $ctx['settings'];
        $roles = $ctx['roles'];

            // If the Sharing Addon is active it will provide the full page.
            // When the addon is not active we render the placeholder template so
            // admins see a helpful message (same UX as Migration placeholder).
            if ( class_exists( 'NNAXFUF_Sharing_Addon_Admin' ) ) {
                return;
            }

            $ctx = $this->get_page_context();
            $settings = $ctx['settings'];
            $roles = $ctx['roles'];

            // Prefer a dedicated placeholder template if present.
            $template_name = file_exists( NNAXFUF_PLUGIN_PATH . 'includes/settings-pages/sharing-placeholder.php' )
                ? 'sharing-placeholder'
                : 'sharing';

            $this->render_settings_page_template(
                $template_name,
                array(
                    'settings' => $settings,
                    'roles'    => $roles,
                )
            );
    }

    public function render_migration_page() {
        if ( ! current_user_can( 'manage_options' ) ) {
            return;
        }

        $this->render_settings_page_template(
            'migration-placeholder',
            array()
        );
    }

    public function render_licenses_page() {
        if ( ! current_user_can( 'manage_options' ) ) {
            return;
        }

        $manager = new NNAXFUF_License_Manager();
        $this->render_settings_page_template(
            'licenses',
            array(
                'license_manager' => $manager,
                'products'        => $manager->get_products(),
            )
        );
    }
}
