<?php
defined('ABSPATH') or die('No!');

/**
 * Renders the admin form for the one-card game customization.
 *
 * @param string $selected_game The selected game identifier.
 */
function tarotxhoroscope_one_card_admin_form($selected_game)
{
    // Enqueue scripts and styles.
    wp_enqueue_style('wp-color-picker');
    wp_enqueue_script('wp-color-picker');
    wp_enqueue_media();

    // Default settings.
    $default_settings = array(
        'enable_card_meaning' => true,
        'enable_chat' => false,
        'button_bg_color' => '#246ae2',
        'button_text_color' => '#ffffff',
        'button_font_size' => '18px',
        'round_edges' => 4,
        'card_name_font_family' => 'Helvetica',
        'card_name_font_size' => '32px',
        'card_meaning_font_family' => 'Helvetica',
        'card_meaning_font_size' => '16px',
        'card_name_text_color' => '#000000',
        'card_meaning_text_color' => '#000000',
        'number_of_cards' => 8,
        'card_back_image' => TAROTXHOROSCOPE_PLUGIN_URL . 'games/images/cardbacks/TarotandHoroscope-cardbg1.png',
        'game_width' => '500px',
    );

    // Get saved settings and merge with defaults.
    $saved_settings = get_option('tarotxhoroscope_one_card_settings', array());
    $settings = wp_parse_args($saved_settings, $default_settings);

    // Enqueue admin script.
    wp_enqueue_script('onecard-admin', TAROTXHOROSCOPE_PLUGIN_URL . 'admin/gamestyles/admin.js', array('jquery', 'wp-color-picker'), '1.0.4', true);

    // Get card back images.
    $path_to_images = TAROTXHOROSCOPE_PLUGIN_DIR . 'games/images/cardbacks/*.png';
    $card_backs = glob($path_to_images);
    $card_backs_urls = array_map(function ($path) {
        return TAROTXHOROSCOPE_PLUGIN_URL . 'games/images/cardbacks/' . basename($path);
    }, $card_backs);

    // Localize script for card backs.
    wp_localize_script('onecard-admin', 'cardBacks', $card_backs_urls);

    // Output the form.
?>
    <div class="tarot-admin-container">
        <div class="tarot-admin-form">
            <form method="post" action="">
                <?php wp_nonce_field('tarotxhoroscope_one_card_settings_nonce', 'tarotxhoroscope_one_card_nonce'); ?>
                <input type="hidden" name="selected_game" value="<?php echo esc_attr($selected_game); ?>" />
                <div style="display: flex; justify-content: space-between;">
                    <!-- Left Column -->
                    <div style="flex: 1; padding-right: 10px;">
                        <h2 style="display: inline-block; width: 160px; text-decoration: underline;">Game Shortcode</h2>
                        <p style="display: inline-block;"><strong>[tarotxhoroscope_onecard]</strong></p>
                        <br>Use the shortcode above to display this game anywhere on your website. Custom changes made here will reflect on this shortcode only. Refresh the page with your embedded shortcode to view the changes. For more help, <a href="https://tarotandhoroscope.com/support/" target="_blank">view the support documentation here</a>.</br>
                        <h2 style="display: inline-block; width: 160px;text-decoration: underline;">Live Chat</h2>
                        <br>
                        <label for="enable_chat"><strong>Enable Chat:</strong></label>
                        <input type="checkbox" name="enable_chat" id="enable_chat" <?php checked($settings['enable_chat'], true); ?> />
                        <p>This will enable the live chatbox feature on this game. Style the chatbox from the "Select Game" menu above. For more help, <a href="https://tarotandhoroscope.com/support/" target="_blank">view the support documentation here</a>.</p>
                        <h2 style="display: inline-block; width: 160px;text-decoration: underline;">Card Back Settings</h2>
                        <p>
                            <label for="number_of_cards" style="display: inline-block; width: 160px;"><strong>Number of Cards:</strong></label>
                            <select name="number_of_cards" id="number_of_cards">
                                <?php for ($i = 1; $i <= 8; $i++) : ?>
                                    <option value="<?php echo intval($i); ?>" <?php selected($settings['number_of_cards'], $i); ?>><?php echo intval($i); ?></option>
                                <?php endfor; ?>
                            </select>
                        </p>
                        <p>Choose how many cards the player can choose from.</p>
                        <p>
                            <label for="card_back_image" style="display: inline-block; width: 160px;"><strong>Card Back Image:</strong></label>
                            <select name="card_back_image" id="card_back_image" onchange="document.getElementById('card_back_image_preview').src = this.value;">
                                <?php
                                $current_image_url = esc_url($settings['card_back_image'] ?? '');
                                foreach ($card_backs_urls as $image_url) {
                                    $selected = ($settings['card_back_image'] ?? '') == $image_url ? ' selected' : '';
                                    echo "<option value='" . esc_url($image_url) . "' " . esc_attr($selected) . ">" . esc_html(basename($image_url)) . "</option>";
                                }
                                ?>
                            </select>
                        </p>
                        <p>Select an image for the card back.</p>
                        <p> Pro plans have access to many more card backs.</p>
                        <img id="card_back_image_preview" src="<?php echo esc_url($current_image_url); ?>" alt="Card Back Image" width="200" height="300" />
                        <br>
                    </div>
                    <!-- Middle Column -->
                    <div style="flex: 1; padding-left: 20px; padding-right: 5px;">
                        <h2 style="display: inline-block; width: 160px;text-decoration: underline;">Game Width</h2>
                        <p>
                            <label for="game_width">Game Width:</label>
                            <input type="text" id="game_width" name="game_width" size=6 value="<?php echo esc_attr($settings['game_width']); ?>" />
                        </p>
                        <p class="description">Set the width of the game (between 200px and 800px).<br>Inspect the changes with the shortcode.</p>
                        <h2 style="display: inline-block; width: 160px;text-decoration: underline;">Card Name Font</h2>
                        <?php tarotxhoroscope_generate_font_dropdown('card_name_font_family', $settings['card_name_font_family'], array('Open Sans', 'Verdana', 'Helvetica', 'Tahoma', 'Times New Roman', 'Georgia', 'Garamond', 'Courier New', 'Brush Script MT', 'Arial')); ?>
                        <?php tarotxhoroscope_generate_font_size_dropdown('card_name_font_size', $settings['card_name_font_size'], 10, 36); ?>
                        <p>
                            <label for="card_name_text_color" style="display: inline-block; width: 160px;"><strong>Card Name Text Color:</strong></label>
                            <input type="text" class="color-field" name="card_name_text_color" id="card_name_text_color" value="<?php echo esc_attr($settings['card_name_text_color']); ?>" />
                        </p>
                        <h2 style="display: inline-block; width: 160px;text-decoration: underline;">Card Meaning Font</h2>
                        <?php tarotxhoroscope_generate_font_dropdown('card_meaning_font_family', $settings['card_meaning_font_family'], array('Open Sans', 'Verdana', 'Helvetica', 'Tahoma', 'Times New Roman', 'Georgia', 'Garamond', 'Courier New', 'Brush Script MT', 'Arial')); ?>
                        <?php tarotxhoroscope_generate_font_size_dropdown('card_meaning_font_size', $settings['card_meaning_font_size'], 10, 22); ?>
                        <p>
                            <label for="card_meaning_text_color" style="display: inline-block; width: 160px;"><strong>Card Meaning Text Color:</strong></label>
                            <input type="text" class="color-field" name="card_meaning_text_color" id="card_meaning_text_color" value="<?php echo esc_attr($settings['card_meaning_text_color']); ?>" />
                        </p>
                        <label for="enable_card_meaning">
                            <input type="checkbox" id="enable_card_meaning" name="enable_card_meaning" <?php checked($settings['enable_card_meaning'], true); ?> />
                            Enable Card Meaning
                        </label>
                        <p>
                        <h2 style="display: inline-block; width: 160px;text-decoration: underline;">Draw Again Button</h2>
                        <p>
                            <label for="button_bg_color" style="display: inline-block; width: 160px;"><strong>Button Background Color:</strong></label>
                            <input type="text" class="color-field" name="button_bg_color" id="button_bg_color" value="<?php echo esc_attr($settings['button_bg_color']); ?>" />
                        </p>
                        <p>
                            <label for="button_text_color" style="display: inline-block; width: 160px;"><strong>Button Text Color:</strong></label>
                            <input type="text" class="color-field" name="button_text_color" id="button_text_color" value="<?php echo esc_attr($settings['button_text_color']); ?>" />
                        </p>
                        <p>
                            <label for="button_font_size" style="display: inline-block; width: 160px;"><strong>Button Font Size:</strong></label>
                            <select name="button_font_size" id="button_font_size">
                                <?php foreach (array('12px', '14px', '16px', '18px', '20px') as $size) : ?>
                                    <option value="<?php echo esc_attr($size); ?>" <?php selected($settings['button_font_size'], $size); ?>><?php echo esc_html($size); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </p>
                        <p>
                            <label for="round_edges" style="display: inline-block; width: 160px;"><strong>Round Edges:</strong></label>
                            <select name="round_edges" id="round_edges">
                                <?php for ($i = 0; $i <= 8; $i++) : ?>
                                    <option value="<?php echo intval($i); ?>" <?php selected($settings['round_edges'], $i); ?>><?php echo intval($i); ?></option>
                                <?php endfor; ?>
                            </select>
                        </p>
                        </p>
                        <input type="submit" name="update_one_card_settings" style="background-color:#007f30; color: white; border: none; padding: 10px; border-radius: 4px; cursor: pointer; margin-top: 20px;" value="Save All Settings" />
                        <input type="submit" name="reset_to_default" style="background-color:#d32f2f; color: white; border: none; padding: 10px; border-radius: 4px; cursor: pointer; margin-top: 20px;" value="Reset to Default" />
                    </div>
                    <!-- Right Column (3rd Column) -->
                    <div style="flex: 1; padding-right: 200px; text-align: center;">
                        <p id="cardNamePreview" style="margin:0em; font-family: <?php echo esc_attr($settings['card_name_font_family']); ?>; font-size: <?php echo esc_attr($settings['card_name_font_size']); ?>; color: <?php echo esc_attr($settings['card_name_text_color']); ?>;">Wheel of Fortune</p>
                        <br>
                        <div>
                            <!-- Note: Static image bundled with plugin; not intended for media library.-->
                            <img src="<?php echo esc_url(TAROTXHOROSCOPE_PLUGIN_URL . 'games/images/tarotcards/Wheel-Of-Fortune-Tarot-Card.png'); ?>" alt="Centered Image" width="200" height="300" style="display: block; margin: 0 auto;">
                        </div>
                        <br>
                        <p id="cardMeaningPreview" style="margin: 0.1em; font-family: <?php echo esc_attr($settings['card_meaning_font_family']); ?>; font-size: <?php echo esc_attr($settings['card_meaning_font_size']); ?>; color: <?php echo esc_attr($settings['card_meaning_text_color']); ?>;">The Wheel of Fortune card has been drawn in your reading, indicating that you are currently experiencing a cyclical change in your life. You may feel like you're on a rollercoaster ride, with ups and downs that can be both thrilling and terrifying.<br><br>However, know that every experience is a lesson and you can learn to take comfort in the cyclical nature of life. You may feel as if you have no control over your circumstances, but the hub of the wheel represents your eternal self, which remains constant throughout the changes. Be patient and trust that things will change for the better, even if it doesn't seem that way right now.</p>
                        <br>
                        <button id="drawAgainButtonPreview" style="font-size: <?php echo esc_attr($settings['button_font_size']); ?>; background-color: <?php echo esc_attr($settings['button_bg_color']); ?>; color: <?php echo esc_attr($settings['button_text_color']); ?>; padding: 10px 20px; border-radius: <?php echo esc_attr($settings['round_edges']); ?>px; cursor: pointer; display: inline-block; border: none;" onclick="event.preventDefault(); event.stopPropagation(); return false;">
                            Draw Again
                        </button>
                    </div>
                </div>
            </form>
        </div>
    </div>
<?php
}

/**
 * Saves the one-card game settings.
 */
function tarotxhoroscope_one_card_admin_save()
{
    if (!current_user_can('manage_options')) {
        wp_die('You do not have sufficient permissions to access this page.');
    }

    // Check if form is submitted and nonce is valid
    if (isset($_POST['update_one_card_settings']) && isset($_POST['tarotxhoroscope_one_card_nonce']) && wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['tarotxhoroscope_one_card_nonce'])), 'tarotxhoroscope_one_card_settings_nonce')) {
        $settings = array(
            'enable_card_meaning' => isset($_POST['enable_card_meaning']),
            'enable_chat' => isset($_POST['enable_chat']),
            'button_bg_color' => isset($_POST['button_bg_color']) ? sanitize_hex_color(wp_unslash($_POST['button_bg_color'])) : '#246ae2',
            'button_text_color' => isset($_POST['button_text_color']) ? sanitize_hex_color(wp_unslash($_POST['button_text_color'])) : '#ffffff',
            'button_font_size' => isset($_POST['button_font_size']) ? sanitize_text_field(wp_unslash($_POST['button_font_size'])) : '18px',
            'card_back_image' => isset($_POST['card_back_image']) ? esc_url_raw(wp_unslash($_POST['card_back_image'])) : TAROTXHOROSCOPE_PLUGIN_URL . 'games/images/cardbacks/TarotandHoroscope-cardbg1.png',
            'number_of_cards' => isset($_POST['number_of_cards']) ? intval(wp_unslash($_POST['number_of_cards'])) : 8,
            'card_name_font_family' => isset($_POST['card_name_font_family']) ? sanitize_text_field(wp_unslash($_POST['card_name_font_family'])) : 'Helvetica',
            'card_name_font_size' => isset($_POST['card_name_font_size']) ? sanitize_text_field(wp_unslash($_POST['card_name_font_size'])) : '32px',
            'card_meaning_font_family' => isset($_POST['card_meaning_font_family']) ? sanitize_text_field(wp_unslash($_POST['card_meaning_font_family'])) : 'Helvetica',
            'card_meaning_font_size' => isset($_POST['card_meaning_font_size']) ? sanitize_text_field(wp_unslash($_POST['card_meaning_font_size'])) : '16px',
            'card_name_text_color' => isset($_POST['card_name_text_color']) ? sanitize_hex_color(wp_unslash($_POST['card_name_text_color'])) : '#000000',
            'card_meaning_text_color' => isset($_POST['card_meaning_text_color']) ? sanitize_hex_color(wp_unslash($_POST['card_meaning_text_color'])) : '#000000',
            'game_width' => isset($_POST['game_width']) ? sanitize_text_field(wp_unslash($_POST['game_width'])) : '500px',
            'round_edges' => isset($_POST['round_edges']) ? intval(wp_unslash($_POST['round_edges'])) : 4,
        );

        // Validate game width.
        $game_width_value = $settings['game_width'];
        if (substr($game_width_value, -2) !== 'px') {
            $game_width_value .= 'px';
        }
        $numeric_value = str_replace('px', '', $game_width_value);
        if (ctype_digit($numeric_value)) {
            $numeric_value = intval($numeric_value);
            if ($numeric_value < 200) {
                $numeric_value = 200;
            } elseif ($numeric_value > 800) {
                $numeric_value = 800;
            }
            $game_width_value = $numeric_value . 'px';
        } else {
            $game_width_value = '500px';
        }
        $settings['game_width'] = $game_width_value;

        update_option('tarotxhoroscope_one_card_settings', $settings);
    }

    // Handle reset to default
    if (isset($_POST['reset_to_default'])) {
        $default_settings = array(
            'enable_card_meaning' => true,
            'enable_chat' => false,
            'button_bg_color' => '#0074bc',
            'button_text_color' => '#ffffff',
            'button_font_size' => '18px',
            'round_edges' => 4,
            'card_name_font_family' => 'Tahoma',
            'card_name_font_size' => '26px',
            'card_meaning_font_family' => 'Tahoma',
            'card_meaning_font_size' => '16px',
            'card_name_text_color' => '#0074bc',
            'card_meaning_text_color' => '#333333',
            'number_of_cards' => 8,
            'game_width' => '600px',
            'card_back_image' => TAROTXHOROSCOPE_PLUGIN_URL . 'games/images/cardbacks/TarotandHoroscope-cardbg1.png',
        );
        update_option('tarotxhoroscope_one_card_settings', $default_settings);
    }
}

/**
 * Generates a font family dropdown.
 *
 * @param string $name The name and ID of the dropdown.
 * @param string $selected_value The currently selected value.
 * @param array $fonts The list of font families.
 */
function tarotxhoroscope_generate_font_dropdown($name, $selected_value, $fonts)
{
    echo "<select name='" . esc_attr($name) . "' id='" . esc_attr($name) . "'>";
    foreach ($fonts as $font) {
        $selected = ($selected_value == $font) ? ' selected' : '';
        echo "<option value='" . esc_attr($font) . "' " . esc_attr($selected) . ">" . esc_html($font) . "</option>";
    }
    echo "</select>";
}

/**
 * Generates a font size dropdown.
 *
 * @param string $name The name and ID of the dropdown.
 * @param string $selected_value The currently selected value.
 * @param int $min The minimum font size.
 * @param int $max The maximum font size.
 */
function tarotxhoroscope_generate_font_size_dropdown($name, $selected_value, $min, $max)
{
    echo "<select name='" . esc_attr($name) . "' id='" . esc_attr($name) . "'>";
    for ($i = $min; $i <= $max; $i++) {
        $size = $i . 'px';
        $selected = ($selected_value == $size) ? ' selected' : '';
        echo "<option value='" . esc_attr($size) . "' " . esc_attr($selected) . ">" . esc_html($size) . "</option>";
    }
    echo "</select>";
}
