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

class UAMT_Admin_Settings
{
    /**
     * Summary of instance
     * @return self
     */
    public static function instance()
    {
        static $instance = null;
        if (null === $instance) {
            $instance = new self();
        }
        return $instance;
    }

    /**
     * Summary of uamt_admin_page
     * @return void
     */
    public function uamt_admin_page()
    {
        // Handle form submission
        if (isset($_POST['uamt_save_settings'])) {
            check_admin_referer('uamt_settings_nonce');

            // Save allowed mimes
            if (isset($_POST['uamt_mimes'])) {
                $allowed_mimes = array_map('sanitize_text_field', wp_unslash($_POST['uamt_mimes']));
                update_option('uamt_allowed_mimes', $allowed_mimes);
            } else {
                update_option('uamt_allowed_mimes', []);
            }

            // Get existing custom mimes
            $existing_custom_mimes = get_option('uamt_custom_mimes', []);
            $new_custom_mimes = [];

            // Save custom mimes
            if (isset($_POST['custom_mimes'])) {
                // First unslash the entire array
                $custom_mimes_data = wp_unslash($_POST['custom_mimes']);

                // Then sanitize each element
                $custom_mimes_data = uamt_sanitize_mime_data($custom_mimes_data);

                $allowed_mimes = get_option('uamt_allowed_mimes', []);
                $existing_extensions = array_map(function ($type) {
                    return $type['ext'];
                }, UAMT_Mime_Types_Handler::uamt_get_default_mime_types());

                if (
                    is_array($custom_mimes_data['desc']) &&
                    is_array($custom_mimes_data['mime']) &&
                    is_array($custom_mimes_data['ext'])
                ) {
                    foreach ($custom_mimes_data['desc'] as $index => $desc) {
                        if (isset(
                            $custom_mimes_data['desc'][$index],
                            $custom_mimes_data['mime'][$index],
                            $custom_mimes_data['ext'][$index]
                        )) {
                            $clean_desc = $custom_mimes_data['desc'][$index];
                            $clean_mime = $custom_mimes_data['mime'][$index];
                            $clean_ext = $custom_mimes_data['ext'][$index];

                            if (!empty($clean_desc) && !empty($clean_mime) && !empty($clean_ext)) {
                                if (in_array($clean_ext, $existing_extensions)) {
                                    add_settings_error(
                                        'uamt_messages',
                                        'uamt_message',
                                        sprintf('Extension "%s" already exists in default MIME types. Please use a different extension.', $clean_ext),
                                        'error'
                                    );
                                    continue;
                                }

                                $new_custom_mimes[] = [
                                    'desc' => $clean_desc,
                                    'mime' => $clean_mime,
                                    'ext' => $clean_ext
                                ];

                                if (!in_array($clean_ext, $allowed_mimes)) {
                                    $allowed_mimes[] = $clean_ext;
                                }
                            }
                        }
                    }

                    // Merge existing and new custom mimes, avoiding duplicates
                    $merged_custom_mimes = $existing_custom_mimes;
                    foreach ($new_custom_mimes as $new_mime) {
                        $exists = false;
                        foreach ($merged_custom_mimes as $existing_mime) {
                            if ($existing_mime['ext'] === $new_mime['ext']) {
                                $exists = true;
                                break;
                            }
                        }
                        if (!$exists) {
                            $merged_custom_mimes[] = $new_mime;
                        }
                    }

                    update_option('uamt_custom_mimes', $merged_custom_mimes);
                    update_option('uamt_allowed_mimes', $allowed_mimes);
                }
            }

            add_settings_error(
                'uamt_messages',
                'uamt_message',
                __('Settings saved successfully.', 'upload-any-mime-types'),
                'updated'
            );
        }
        // Handle MIME type deletion
        if (isset($_GET['delete_mime']) && isset($_GET['_wpnonce'])) {
            $nonce = sanitize_text_field(wp_unslash($_GET['_wpnonce']));
            $ext_to_delete = sanitize_key(wp_unslash($_GET['delete_mime']));

            if (wp_verify_nonce($nonce, 'delete_mime_' . $ext_to_delete)) {
                $custom_mimes = get_option('uamt_custom_mimes', []);
                $allowed_mimes = get_option('uamt_allowed_mimes', []);

                $custom_mimes = array_filter($custom_mimes, function ($mime) use ($ext_to_delete) {
                    return $mime['ext'] !== $ext_to_delete;
                });

                $allowed_mimes = array_filter($allowed_mimes, function ($ext) use ($ext_to_delete) {
                    return $ext !== $ext_to_delete;
                });

                update_option('uamt_custom_mimes', $custom_mimes);
                update_option('uamt_allowed_mimes', $allowed_mimes);

                add_settings_error(
                    'uamt_messages',
                    'uamt_message',
                    __('MIME type deleted successfully.', 'upload-any-mime-types'),
                    'updated'
                );

                wp_redirect(remove_query_arg(['delete_mime', '_wpnonce']));
                exit;
            }
        }

        /**
         * Sanitize MIME type data
         */
        function uamt_sanitize_mime_data($data)
        {
            $sanitized = [];

            if (isset($data['desc']) && is_array($data['desc'])) {
                $sanitized['desc'] = array_map('sanitize_text_field', $data['desc']);
            }

            if (isset($data['mime']) && is_array($data['mime'])) {
                $sanitized['mime'] = array_map('sanitize_text_field', $data['mime']);
            }

            if (isset($data['ext']) && is_array($data['ext'])) {
                $sanitized['ext'] = array_map('sanitize_key', $data['ext']);
            }

            return $sanitized;
        }
        settings_errors('uamt_messages');

        $allowed_mimes = get_option('uamt_allowed_mimes', []);
        $custom_mimes = get_option('uamt_custom_mimes', []);
        $default_mimes = UAMT_Mime_Types_Handler::uamt_get_default_mime_types();
?>
        <div class="upload-anything-wrap-main">
            <div class="wrap-main-header">
                <img class="img-fluid" src="<?php echo esc_url(UAMT_ASSETS . '/images/logo.png') ?>" alt="general">
                <div class="sub-header-text-right">
                    <p><?php esc_html_e('Need some help?', 'upload-any-mime-types'); ?></p>
                    <a href="https://softlabbd.com/support/" target="_blank"><span class="dashicons dashicons-admin-users"></span> <?php esc_html_e('Support', 'upload-any-mime-types'); ?></a>
                </div>
            </div>

            <div class="upload-anything-wrap-item">
                <div class="upload-anything-wrap">
                    <form method="post" action="">
                        <?php wp_nonce_field('uamt_settings_nonce'); ?>
                        <div class="ua-header-area-main">
                            <div class="ua-header-area">
                                <div class="header-left">
                                    <h3><?php esc_html_e('Add Upload Any MIME Types', 'upload-any-mime-types'); ?></h3>
                                    <p><?php esc_html_e('Below is the list of files types that can be enabled, not including the files WordPress allows by default.', 'upload-any-mime-types'); ?></p>
                                </div>
                                <div class="search-right">
                                    <input type="text" id="ua-search-input" placeholder="<?php esc_attr_e('Search file types...', 'upload-any-mime-types'); ?>">
                                </div>
                                <button type="submit" name="uamt_save_settings" class=" uamt-button-primary">
                                    <span class="dashicons dashicons-yes" style="vertical-align: middle; margin-right: 5px;"></span>
                                    <?php _e('Save', 'upload-any-mime-types'); ?>
                                </button>
                            </div>
                        </div>

                        <div class="ua-table-container">
                            <table class="widefat">
                                <thead class="mime-head">
                                    <tr>
                                        <th><?php esc_html_e('Action', 'upload-any-mime-types'); ?></th>
                                        <th><?php esc_html_e('Description', 'upload-any-mime-types'); ?></th>
                                        <th><?php esc_html_e('MIME Type', 'upload-any-mime-types'); ?></th>
                                        <th><?php esc_html_e('Extension', 'upload-any-mime-types'); ?></th>
                                        <th><?php esc_html_e('Delete', 'upload-any-mime-types'); ?></th>
                                    </tr>
                                </thead>

                                <tbody class="uamt_table">
                                    <?php foreach ($custom_mimes as $type): ?>
                                        <tr>
                                            <td>
                                                <label class="switch">
                                                    <input type='checkbox' checked id='toggle-<?php echo esc_attr($type['ext']); ?>' class='checkbox' name='uamt_mimes[]' value='<?php echo esc_attr($type['ext']); ?>' <?php checked(in_array($type['ext'], $allowed_mimes)); ?>>
                                                    <span class="slider"></span>
                                                </label>
                                            </td>
                                            <td><?php echo esc_html($type['desc']); ?></td>
                                            <td><?php echo esc_html($type['mime']); ?></td>
                                            <td>.<?php echo esc_html($type['ext']); ?></td>
                                            <td>
                                                <a href="#" class="button button-small delete-mime"
                                                    data-extension="<?php echo esc_attr($type['ext']); ?>"
                                                    title="<?php esc_attr_e('Delete this MIME type', 'upload-any-mime-types'); ?>">
                                                    <span class="dashicons dashicons-trash"></span>
                                                </a>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>

                                    <?php foreach ($default_mimes as $type): ?>
                                        <tr>
                                            <td>
                                                <label class="switch">
                                                    <input type='checkbox' id='toggle-<?php echo esc_attr($type['ext']); ?>' class='checkbox' name='uamt_mimes[]' value='<?php echo esc_attr($type['ext']); ?>' <?php checked(in_array($type['ext'], $allowed_mimes)); ?>>
                                                    <span class="slider"></span>
                                                </label>
                                            </td>
                                            <td><?php echo esc_html($type['desc']); ?></td>
                                            <td><?php echo esc_html($type['mime']); ?></td>
                                            <td>.<?php echo esc_html($type['ext']); ?></td>

                                            <td>
                                                <a href="#" class="button button-small delete-mime"
                                                    data-extension="<?php echo esc_attr($type['ext']); ?>"
                                                    title="<?php esc_attr_e('Delete this MIME type', 'upload-any-mime-types'); ?>">
                                                    <span class="dashicons dashicons-trash"></span>
                                                </a>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                        <p><?php esc_html_e(' Don\'t see what you need? No problem, add your custom file types.', 'upload-any-mime-types'); ?></p>
                        <div class="custom-file-types-button">
                            <a href="#" id="toggle-custom-section"><span class="dashicons dashicons-plus-alt2"></span> <?php esc_html_e('Add Custom File Types', 'upload-any-mime-types'); ?></a>
                        </div>

                        <div class="ua-custom-section" style="display: none;">
                            <h3><?php esc_html_e('Add Custom File Types', 'upload-any-mime-types'); ?></h3>

                            <div id="mime-drop-area">
                                <p><?php esc_html_e('Drop files here to detect MIME types automatically', 'upload-any-mime-types'); ?></p>
                                <p><?php esc_html_e('or', 'upload-any-mime-types'); ?></p>
                                <input type="file" id="mimeFileInput" multiple style="display: none;">
                                <button type="button" id="select-files-btn" class="button"><?php esc_html_e('Select Files', 'upload-any-mime-types'); ?></button>
                            </div>

                            <div id="customMimeContainer">
                                <div class="mime-row">
                                    <input type="text" name="custom_mimes[desc][]" placeholder="<?php esc_attr_e('File Description', 'upload-any-mime-types'); ?>" style="flex: 2;">
                                    <input type="text" id="custom_mime_type" name="custom_mimes[mime][]" placeholder="<?php esc_attr_e('MIME Type', 'upload-any-mime-types'); ?>" style="flex: 2;">
                                    <input type="text" name="custom_mimes[ext][]" placeholder="<?php esc_attr_e('Extension (without dot)', 'upload-any-mime-types'); ?>" style="flex: 1;" class="extension-input">
                                    <div class="mime-row-button">
                                        <button type="button" class="button add-row">+</button>
                                        <button type="button" class="button remove-row"><span class="dashicons dashicons-trash"></span></button>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <button type="submit" name="uamt_save_settings" class=" uamt-button-primary">
                            <span class="dashicons dashicons-yes" style="vertical-align: middle; margin-right: 5px;"></span>
                            <?php _e('Save', 'upload-any-mime-types'); ?>
                        </button>
                        <button type="button" id="uamt-reset-settings" class="uamt-button-secondary btn-danger" style="margin-left: 10px;">
                            <span class="dashicons dashicons-update" style="vertical-align: middle; margin-right: 5px;"></span>
                            <?php _e('Reset', 'upload-any-mime-types'); ?>
                        </button>
                    </form>
                </div>
                <div class="products-list-area">

                    <h3><?php esc_html_e('You might like our other products', 'upload-any-mime-types'); ?></h3>

                    <p><?php esc_html_e('File Upload Types is built by the team behind some of the most popular WordPress plugins.', 'upload-any-mime-types'); ?></p>

                    <!-- Plugin install links -->
                    <?php
                    $install_url_igd = esc_url(admin_url("plugin-install.php?tab=plugin-information&plugin=integrate-google-drive"));
                    $install_url_rp = esc_url(admin_url("plugin-install.php?tab=plugin-information&plugin=radio-player"));
                    $install_url_dd = esc_url(admin_url("plugin-install.php?tab=plugin-information&plugin=dracula-dark-mode"));
                    $install_url_eacf7 = esc_url(admin_url("plugin-install.php?tab=plugin-information&plugin=essential-addons-for-contact-form-7"));

                    ?>
                    <div class="products-list-area-item">
                        <div class="products-sub-item">
                            <div class="plugin-details">
                                <a href="https://wordpress.org/plugins/integrate-google-drive/" target="_blank" class="products-item">
                                    <div class="products-img">
                                        <img class="img-fluid" src="<?php echo esc_url(UAMT_ASSETS . '/images/integrate-google-drive-new.png'); ?>" alt="Integrate Google Drive">
                                    </div>
                                    <div class="products-content">
                                        <p class="uamt-product-title integrate-google-drive"><?php echo esc_html__('Integrate Google Drive', 'upload-any-mime-types'); ?></p>
                                        <p><?php echo esc_html__('Complete Google Drive Cloud Solution For WordPress.', 'upload-any-mime-types'); ?></p>
                                    </div>

                                </a>
                            </div>
                            <div class="products-buttons">
                                <a class="products-button-install" href="<?php echo esc_url($install_url_igd); ?>"><span class="dashicons dashicons-admin-plugins"></span> Install</a>
                                <a class="products-button-learn-more" href="https://softlabbd.com/integrate-google-drive/" target="_blank"><span class="dashicons dashicons-external"></span> Learn More</a>
                            </div>
                        </div>

                        <div class="products-sub-item">
                            <div class="plugin-details">
                                <a href="https://wordpress.org/plugins/radio-player/" target="_blank" class="products-item">
                                    <div class="products-img">
                                        <img class="img-fluid" src="<?php echo esc_url(UAMT_ASSETS . '/images/radio-player-new.png') ?>" alt="general">
                                    </div>
                                    <div class="products-content">
                                        <p class="uamt-product-title radio-player" class=""><?php echo esc_html__('Radio Player', 'upload-any-mime-types'); ?></p>
                                        <p><?php echo esc_html__('Live Shoutcast, Icecast and Audio Stream Player for WordPress.', 'upload-any-mime-types'); ?></p>
                                    </div>
                                </a>
                            </div>
                            <div class="products-buttons">
                                <a class="products-button-install" href="<?php echo esc_url($install_url_rp); ?>"><span class="dashicons dashicons-admin-plugins"></span> Install</a>
                                <a class="products-button-learn-more" href="https://softlabbd.com/radio-player/" target="_blank"><span class="dashicons dashicons-external"></span> Learn More</a>
                            </div>
                        </div>

                        <div class="products-sub-item">
                            <div class="plugin-details">
                                <a href="https://wordpress.org/plugins/dracula-dark-mode/" target="_blank" class="products-item">
                                    <div class="products-img">
                                        <img class="img-fluid" src="<?php echo esc_url(UAMT_ASSETS . '/images/dracula-icon.png') ?>" alt="general">
                                    </div>
                                    <div class="products-content">
                                        <p class="uamt-product-title dracula-dark-mode"><?php echo esc_html__('Dracula Dark Mode', 'upload-any-mime-types'); ?></p>
                                        <p><?php echo esc_html__('AI-Powered Dark Mode for WordPress', 'upload-any-mime-types'); ?></p>
                                    </div>
                                </a>
                            </div>
                            <div class="products-buttons">
                                <a class="products-button-install" href="<?php echo esc_url($install_url_dd); ?>"><span class="dashicons dashicons-admin-plugins"></span> Install</a>
                                <a class="products-button-learn-more" href="https://softlabbd.com/dracula-dark-mode/" target="_blank"><span class="dashicons dashicons-external"></span> Learn More</a>
                            </div>
                        </div>

                        <div class="products-sub-item">
                            <div class="plugin-details">
                                <a href="https://wordpress.org/plugins/essential-addons-for-contact-form-7/" target="_blank" class="products-item">
                                    <div class="products-img">
                                        <img class="img-fluid" src="<?php echo esc_url(UAMT_ASSETS . '/images/essential-addons-for-contact-form-7.png') ?>" alt="general">
                                    </div>
                                    <div class="products-content">
                                        <p class="uamt-product-title essential-addons-for-contact-form-7"><?php echo esc_html__('Essential Addons for Contact Form 7', 'upload-any-mime-types'); ?></p>
                                        <p><?php echo esc_html__('50+ Essential Fields, Features & Integrations Add-ons for Contact Form 7', 'upload-any-mime-types'); ?></p>
                                    </div>
                                </a>
                            </div>
                            <div class="products-buttons">
                                <a class="products-button-install" href="<?php echo esc_url($install_url_eacf7); ?>"><span class="dashicons dashicons-admin-plugins"></span> Install</a>
                                <a class="products-button-learn-more" href="https://softlabbd.com/essential-addons-for-contact-form-7/" target="_blank"><span class="dashicons dashicons-external"></span> Learn More</a>
                            </div>
                        </div>
                    </div>

                </div>
            </div>
    <?php

    }
}

UAMT_Admin_Settings::instance();
