<?php

// Prevent direct access to the file if ABSPATH is not defined.
if (! defined('ABSPATH')) {
    exit; // Exit if accessed directly.
}

// ======================
// Handle Form Submission
// ======================
$default_selected_platforms  = [
    'facebook',
    'twitter',
    'square-x-twitter',
    'linkedin',
    'instagram',
    'youtube',
    'github',
    'pinterest',
    'tiktok',
    'snapchat',
    'whatsapp',
    'telegram',
    'discord',
    'twitch',
    'medium',
    'bluesky',
    'mastodon',
    'threads',
];

$saved_platforms = get_option('author_kit_selected_platforms', $default_selected_platforms);
$saved_link_attributes = get_transient('author_kit_link_attributes');

if ($saved_link_attributes === false) {
    $saved_link_attributes = get_option('author_kit_link_attributes', [
        'target' => '_blank',
        'rel' => ['noopener', 'noreferrer']
    ]);
    set_transient('author_kit_link_attributes', $saved_link_attributes, YEAR_IN_SECONDS);
}

/**
 * Fetch current byline compatibility settings
 *
 * @return array
 */
function author_kit_get_byline_settings(): array
{
    $current_theme = wp_get_theme()->get('Name');
    $normalized_theme = ucwords(strtolower($current_theme));

    $manual_selector = get_option('author_kit_manual_byline_selector', '');
    $compatibility_status = get_option('author_kit_byline_compatibility_status', '');

    return [
        'current_theme'        => $current_theme,
        'normalized_theme'     => $normalized_theme,
        'manual_selector'      => sanitize_text_field($manual_selector),
        'compatibility_status' => sanitize_text_field($compatibility_status)
    ];
}

$author_kit_byline_settings = author_kit_get_byline_settings();

// ======================
// Save Settings on POST
// ======================
if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'POST' && check_admin_referer('author_kit_platform_save')) {

    // Save selected platforms
    $saved_platforms = isset($_POST['selected_platforms']) ? array_map('sanitize_text_field', wp_unslash($_POST['selected_platforms'])) : [];
    update_option('author_kit_selected_platforms', $saved_platforms);

    // Save link attributes
    $saved_link_attributes = [
        'target' => isset($_POST['link_target']) ? sanitize_text_field(wp_unslash($_POST['link_target'])) : '_blank',
        'rel' => isset($_POST['link_rel']) ? array_map('sanitize_text_field', wp_unslash($_POST['link_rel'])) : []
    ];
    update_option('author_kit_link_attributes', $saved_link_attributes);
    set_transient('author_kit_link_attributes', $saved_link_attributes, YEAR_IN_SECONDS);

    // Save manual selector
    $manual_selector = isset($_POST['author_kit_manual_byline_selector']) ? sanitize_text_field(wp_unslash($_POST['author_kit_manual_byline_selector'])) : '';
    update_option('author_kit_manual_byline_selector', $manual_selector);

    // Save display author bio option
    $display_author_bio = isset($_POST['display_author_bio']) ? 1 : 0;
    update_option('author_kit_display_author_bio', $display_author_bio);

    // Save include subscribers option
    $include_subscribers = isset($_POST['include_subscribers']) ? 1 : 0;
    update_option('author_kit_include_subscribers', $include_subscribers);

    // Save delete plugin data setting
    $delete_plugin_data = isset($_POST['delete_plugin_data']) ? 1 : 0;
    update_option('author_kit_delete_plugin_data', $delete_plugin_data);

    // Clear and refresh platform meta cache
    Author_Kit_Social_Profile::clear_selected_platforms_cache();
    Author_Kit_Social_Profile::get_selected_platforms_with_meta();

    // Reload settings
    $author_kit_byline_settings = author_kit_get_byline_settings();
}


// ======================
// Load Platforms
// ======================
$supported_platforms = Author_Kit_Social_Profile::get_supported_platforms();
$selected_platforms_list = [];
$unselected_platforms_list = [];

foreach ($supported_platforms as $key => $platform) {
    if (in_array($key, $saved_platforms, true)) {
        $selected_platforms_list[$key] = $platform;
    } else {
        $unselected_platforms_list[$key] = $platform;
    }
}

$ordered_platforms = $selected_platforms_list + $unselected_platforms_list;
?>

<div id="author-kit-settings-page">
    <div class="wrap author-kit-platform-wrap">
        <form method="post">
            <?php wp_nonce_field('author_kit_platform_save'); ?>

            <!-- SOCIAL ICON SETTINGS -->
            <h3><?php esc_html_e('Select Social Platforms & Link Attributes', 'author-kit'); ?></h3>
            <div class="custom-multiselect-wrap">
                <div class="custom-select-display" id="selected-platforms-display">
                    <?php echo count($saved_platforms); ?>
                </div>
                <select name="selected_platforms[]" id="platform-multiselect" multiple>
                    <?php foreach ($ordered_platforms as $key => $platform) : ?>
                        <option value="<?php echo esc_attr($key); ?>"
                            data-icon="fa fa-brands fa-<?php echo esc_attr($key); ?>"
                            data-color="<?php echo esc_attr($platform['color']); ?>"
                            <?php echo in_array($key, $saved_platforms) ? 'selected' : ''; ?>>
                            <?php echo esc_html($platform['name']); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>

            <!-- LINK ATTRIBUTES SETTINGS -->
            <div id="link-attributes-selectors">
                <section>
                    <h3><?php esc_html_e('Link Attributes', 'author-kit'); ?></h3>
                    <div class="link-attributes-settings">
                        <label>
                            <input type="radio" name="link_target" value="_blank" <?php echo $saved_link_attributes['target'] === '_blank' ? 'checked' : ''; ?>>
                            <?php esc_html_e('Open in New Tab (_blank)', 'author-kit'); ?>
                        </label>
                        <label>
                            <input type="radio" name="link_target" value="_self" <?php echo $saved_link_attributes['target'] === '_self' ? 'checked' : ''; ?>>
                            <?php esc_html_e('Open in Same Tab (_self)', 'author-kit'); ?>
                        </label>
                    </div>
                </section>

                <section>
                    <h3><?php esc_html_e('Rel Attributes', 'author-kit'); ?></h3>
                    <div class="rel-attributes-settings">
                        <?php foreach (['noopener', 'noreferrer', 'nofollow'] as $rel_option) : ?>
                            <label>
                                <input type="checkbox" name="link_rel[]" value="<?php echo esc_attr($rel_option); ?>"
                                    <?php echo in_array($rel_option, $saved_link_attributes['rel'], true) ? 'checked' : ''; ?>>
                                <?php echo esc_html($rel_option); ?>
                            </label>
                        <?php endforeach; ?>
                    </div>
                </section>

            </div>

            <!-- BYLINE COMPATIBILITY SETTINGS -->
            <div class="author-kit-byline-compatibility-section" id="author-kit-setting-section">
                <h3><?php esc_html_e('Byline Compatibility', 'author-kit'); ?></h3>
                <p>
                    <strong><?php esc_html_e('Current Theme:', 'author-kit'); ?></strong>
                    <?php echo esc_html($author_kit_byline_settings['current_theme']); ?> —
                    <?php
                    $status = $author_kit_byline_settings['compatibility_status'];
                    $status_class = $status === 'Compatible' ? 'author-kit-compatible' : 'author-kit-incompatible';
                    ?>
                    <span class="<?php echo esc_attr($status_class); ?>">
                        <strong><?php echo esc_html($status); ?></strong>
                    </span>
                </p>


                <label for="author_kit_manual_byline_selector">
                    <?php

                    $compat_status = isset($author_kit_byline_settings['compatibility_status']) ? $author_kit_byline_settings['compatibility_status'] : '';

                    if ($compat_status === 'Incompatible') {
                        printf(
                            wp_kses(
                                __('Enter Byline ID or Class (e.g. <code>.entry-meta</code> or <code>#author-name</code>):', 'author-kit'),
                                ['code' => []]
                            )
                        );
                    } elseif ($compat_status === 'Compatible') {
                        echo '<span class="description">' .
                            esc_html__('Hurrah! Your theme is compatible with Author Kit. Enjoy advanced bylines with co-author support.', 'author-kit') .
                            '</span>';
                    }
                    ?>
                </label>

                <br>

                <input
                    style="margin-top: 10px;"
                    type="text"
                    id="author_kit_manual_byline_selector"
                    name="author_kit_manual_byline_selector"
                    value="<?php echo esc_attr($author_kit_byline_settings['manual_selector']); ?>"
                    placeholder="<?php esc_html_e('Enter byline ID or class here', 'author-kit'); ?>"
                    class="regular-text"
                    <?php echo $author_kit_byline_settings['compatibility_status'] === 'Compatible' ? 'disabled' : ''; ?>>

                <p class="description" style="margin-top: 6px;">
                    <?php echo $author_kit_byline_settings['compatibility_status'] === 'Compatible'
                        ? esc_html__('Your theme is compatible with Author Kit. No action needed.', 'author-kit')
                        : esc_html__('Your theme is not compatible. You can enter a custom selector to enable byline replacement.', 'author-kit'); ?>
                </p>
            </div>

            <!-- AUTHOR KIT DISPLAY SETTINGS -->
<div class="author-kit-display-settings-section" id="author-kit-setting-section">
    <section>
        <h3><?php esc_html_e('Author Bio Box Display Setting', 'author-kit'); ?></h3>
        
        <div class="author-kit-check-bio-box">
            <label>
                <input type="checkbox" name="display_author_bio"
                    <?php checked(get_option('author_kit_display_author_bio', true), 1); ?>>
                <strong><?php esc_html_e('Author Bio Box Display', 'author-kit'); ?></strong>
            </label>
            <p class="description"><?php esc_html_e('Show bio box for all authors. Uncheck to hide it for authors without a bio.', 'author-kit'); ?></p>
        </div>

    </section>
</div>


            <!-- AUTHOR KIT DISPLAY SETTINGS -->
<div class="author-kit-display-settings-section" id="author-kit-setting-section">
    <section>
        <h3><?php esc_html_e('User Table Performance', 'author-kit'); ?></h3>

        <div class="author-kit-check-subscriber">
            <label>
                <input type="checkbox" name="include_subscribers"
                    <?php checked(get_option('author_kit_include_subscribers', true), 1); ?>>
                <strong><?php esc_html_e('Include Subscribers in Author Table', 'author-kit'); ?></strong>
            </label>
            <p class="description"><?php esc_html_e('Add subscribers to author table. Uncheck if site performance drops.', 'author-kit'); ?></p>
        </div>
    </section>
</div>




            <!-- DELETE PLUGIN DATA SETTINGS -->
            <div class="author-kit-delete-plugin-data-section" id="author-kit-setting-section">

                <section>
                    <h3><?php esc_html_e('Plugin Data Uninstall Cleanup', 'author-kit'); ?></h3>
                    <div class="rel-attributes-settings">
                        <label>
                            <input type="checkbox" name="delete_plugin_data"
                                <?php checked(get_option('author_kit_delete_plugin_data', false), 1); ?>>

                            <?php esc_html_e('Delete Author Kit Plugin Data on Uninstall', 'author-kit'); ?>
                        </label>
                    </div>
                </section>
            </div>
            <br>
            <button type="submit" class="author-kit-btn" id="author-kit-settings-btn">
                <?php esc_html_e('Save Settings', 'author-kit'); ?>
            </button>
        </form>
    </div>
</div>