<?php
// Horoscope game styling
defined('ABSPATH') or die('No!');

function tarotxhoroscope_register_preview_image()
{
    $image_path = TAROTXHOROSCOPE_PLUGIN_DIR . 'games/images/horoscopes/aries.png';
    $image_url = TAROTXHOROSCOPE_PLUGIN_URL . 'games/images/horoscopes/aries.png';
    $upload_dir = wp_upload_dir();

    // Check if the image is already registered
    $attachment_id = get_option('tarotxhoroscope_aries_attachment_id');

    if (!$attachment_id) {
        $filename = basename($image_path);
        $wp_filetype = wp_check_filetype($filename, null);
        $attachment = array(
            'post_mime_type' => $wp_filetype['type'],
            'post_title' => 'Aries Horoscope Preview Image',
            'post_content' => '',
            'post_status' => 'inherit'
        );

        // Insert the attachment
        $attachment_id = wp_insert_attachment($attachment, $image_path);
        if (!is_wp_error($attachment_id)) {
            require_once ABSPATH . 'wp-admin/includes/image.php';
            $metadata = wp_generate_attachment_metadata($attachment_id, $image_path);
            wp_update_attachment_metadata($attachment_id, $metadata);
            update_option('tarotxhoroscope_aries_attachment_id', $attachment_id);
        }
    }
}

// Hook to register image on plugin activation
register_activation_hook(__FILE__, 'tarotxhoroscope_register_preview_image');

function tarotxhoroscope_horoscope_admin_form($selected_game)
{
    wp_enqueue_style('wp-color-picker');
    wp_enqueue_script('wp-color-picker');
    wp_enqueue_media();

    $default_settings = array(
        'font_family' => 'Tahoma',
        'font_size' => '16px',
        'text_color' => '#000000',
        'image_shown' => 1,
        'image_position' => 'top',
        'show_date' => 1,
        'border_enabled' => 1,
        'border_color' => '#b7b7b7',
        'border_width' => 3,
        'border_radius' => 15,
        'width' => 800,
    );

    $saved_settings = get_option('tarotxhoroscope_horoscope_settings', array());
    $settings = wp_parse_args($saved_settings, $default_settings);

    wp_enqueue_script('tarotxhoroscope-horoscope-admin-js', TAROTXHOROSCOPE_PLUGIN_URL . 'admin/gamestyles/horoscope-admin.js', array('jquery', 'wp-color-picker'), '1.0.4', true);
    wp_localize_script('tarotxhoroscope-horoscope-admin-js', 'horoscopeAdminData', array(
        'imageUrl' => TAROTXHOROSCOPE_PLUGIN_URL . 'games/images/horoscopes/aries.png'
    ));

    $aries_attachment_id = get_option('tarotxhoroscope_aries_attachment_id');
?>
    <div class="tarot-admin-container">
        <div class="tarot-admin-form">
            <form method="post" action="<?php echo esc_url(admin_url('admin.php?page=tarotxhoroscope_games&selected_game=' . esc_attr($selected_game))); ?>">
                <?php wp_nonce_field('tarotxhoroscope_horoscope_settings_nonce', 'tarotxhoroscope_horoscope_nonce'); ?>
                <input type="hidden" name="selected_game" value="<?php echo esc_attr($selected_game); ?>" />
                <div style="display: flex; justify-content: space-between;">
                    <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_monthly_horoscope sign="aries"]</strong></p>
                        <br>Use the shortcode above with a valid star sign (e.g., "aries", "taurus") to display the monthly horoscope on your website. Custom changes made here will reflect on this shortcode. 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>
                        <?php $fonts = array('Open Sans', 'Verdana', 'Helvetica', 'Tahoma', 'Times New Roman', 'Georgia', 'Garamond', 'Courier New', 'Brush Script MT', 'Arial'); ?>
                        <h2 style="display: inline-block; width: 160px;text-decoration: underline;">Horoscope Text Settings</h2>
                        <p>
                            <label for="font_family" style="display: inline-block; width: 160px;"><strong>Font Family:</strong></label>
                            <select name="font_family" id="font_family">
                                <?php foreach ($fonts as $font) : ?>
                                    <option value="<?php echo esc_attr($font); ?>" <?php selected($settings['font_family'], $font); ?>><?php echo esc_html($font); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </p>
                        <p>
                            <label for="font_size" style="display: inline-block; width: 160px;"><strong>Font Size:</strong></label>
                            <?php tarotxhoroscope_generate_horoscope_font_size_dropdown('font_size', $settings['font_size'], 10, 21); ?>
                        </p>
                        <p>
                            <label for="text_color" style="display: inline-block; width: 160px;"><strong>Text Color:</strong></label>
                            <input type="text" class="color-field" name="text_color" id="text_color" value="<?php echo esc_attr($settings['text_color']); ?>">
                        </p>
                        <h2 style="display: inline-block; width: 160px;text-decoration: underline;">Image Settings</h2>
                        <p>
                            <label for="image_shown" style="display: inline-block; width: 160px;"><strong>Show Image:</strong></label>
                            <input type="checkbox" name="image_shown" id="image_shown" value="1" <?php checked($settings['image_shown'], 1); ?>>
                        </p>
                        <p>
                            <label for="image_position" style="display: inline-block; width: 160px;"><strong>Image Position:</strong></label>
                            <select name="image_position" id="image_position">
                                <option value="top" <?php selected($settings['image_position'], 'top'); ?>>Top</option>
                                <option value="left" <?php selected($settings['image_position'], 'left'); ?>>Left</option>
                                <option value="right" <?php selected($settings['image_position'], 'right'); ?>>Right</option>
                            </select>
                        </p>
                        <p>Pro plans have choices of image sets.</p>
                        <h2 style="display: inline-block; width: 160px;text-decoration: underline;">Date Setting</h2>
                        <p>
                            <label for="show_date" style="display: inline-block; width: 160px;"><strong>Show Date:</strong></label>
                            <input type="checkbox" name="show_date" id="show_date" value="1" <?php checked($settings['show_date'], 1); ?>>
                        </p>
                        <h2 style="display: inline-block; width: 160px;text-decoration: underline;">Horoscope Container Settings</h2>
                        <p>
                            <label for="border_enabled" style="display: inline-block; width: 160px;"><strong>Enable Border:</strong></label>
                            <input type="checkbox" name="border_enabled" id="border_enabled" value="1" <?php checked($settings['border_enabled'], 1); ?>>
                        </p>
                        <p>
                            <label for="border_color" style="display: inline-block; width: 160px;"><strong>Border Color:</strong></label>
                            <input type="text" class="color-field" name="border_color" id="border_color" value="<?php echo esc_attr($settings['border_color']); ?>">
                        </p>
                        <p>
                            <label for="border_width" style="display: inline-block; width: 160px;"><strong>Border Width:</strong></label>
                            <select name="border_width" id="border_width">
                                <?php for ($i = 1; $i <= 10; $i++) : ?>
                                    <option value="<?php echo esc_attr($i); ?>" <?php selected($settings['border_width'], $i); ?>><?php echo esc_html($i . 'px'); ?></option>
                                <?php endfor; ?>
                            </select>
                        </p>
                        <p>
                            <label for="border_radius" style="display: inline-block; width: 160px;"><strong>Border Radius:</strong></label>
                            <select name="border_radius" id="border_radius">
                                <?php for ($i = 0; $i <= 50; $i += 5) : ?>
                                    <option value="<?php echo esc_attr($i); ?>" <?php selected($settings['border_radius'], $i); ?>><?php echo esc_html($i . 'px'); ?></option>
                                <?php endfor; ?>
                            </select>
                        </p>
                        <p>
                            <label for="width" style="display: inline-block; width: 160px;"><strong>Width:</strong></label>
                            <input type="number" name="width" id="width" value="<?php echo esc_attr($settings['width']); ?>" min="400" max="800"> px (400–800)
                        </p>
                        <input type="submit" name="update_horoscope_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>
                    <div style="flex: 1; padding-right: 200px; text-align: center;">
                        <h2 style="display: inline-block; width: 160px;text-decoration: underline;">Horoscope Preview</h2>
                        <div id="horoscope-preview" style="width: <?php echo esc_attr($settings['width'] . 'px'); ?>; font-family: <?php echo esc_attr($settings['font_family']); ?>; font-size: <?php echo esc_attr($settings['font_size']); ?>; color: <?php echo esc_attr($settings['text_color']); ?>; <?php echo $settings['border_enabled'] ? 'border: ' . esc_attr($settings['border_width'] . 'px solid ' . $settings['border_color']) . '; border-radius: ' . esc_attr($settings['border_radius'] . 'px') . ';' : ''; ?> padding: 10px; overflow: hidden; background-color: #f5f5f5; margin: 0 auto;">
                            <?php if ($settings['image_shown'] && $aries_attachment_id) : ?>
                                <?php if ($settings['image_position'] === 'top') : ?>
                                    <?php echo wp_get_attachment_image($aries_attachment_id, 'full', false, array('style' => 'display: block; margin: 0 auto 10px; max-width: min(200px, 100%); max-height: 200px; width: auto;')); ?>
                                <?php endif; ?>
                            <?php endif; ?>
                            <div style="<?php echo $settings['image_shown'] && $settings['image_position'] !== 'top' ? 'display: flex; flex-wrap: nowrap; align-items: center;' : 'text-align: center;'; ?>">
                                <?php if ($settings['image_shown'] && $settings['image_position'] === 'left' && $aries_attachment_id) : ?>
                                    <?php echo wp_get_attachment_image($aries_attachment_id, 'full', false, array('style' => 'margin-right: 10px; max-width: min(200px, 100%); max-height: 200px; width: auto;')); ?>
                                <?php endif; ?>
                                <div style="flex: 1; <?php echo $settings['image_shown'] && $settings['image_position'] === 'top' ? 'text-align: center;' : 'text-align: left;'; ?>">
                                    <?php if ($settings['show_date']) : ?>
                                        <div style="margin-bottom: 10px;"><b>Today's date:</b> <?php echo esc_html(wp_date('l, F j, Y')); ?></div>
                                    <?php endif; ?>
                                    <div><b>Sample Horoscope:</b> Love and Relationships: March 2025 ignites passionate connections for Aries as Venus dances through your sector of intimacy. Early-month tensions dissolve post-Equinox, fostering vulnerability and trust. Committed partnerships benefit from shared adventures, while singles may attract magnetic souls during the Full Moon in Libra. Balance independence with compromise to harmonize bonds.</div>
                                </div>
                                <?php if ($settings['image_shown'] && $settings['image_position'] === 'right' && $aries_attachment_id) : ?>
                                    <?php echo wp_get_attachment_image($aries_attachment_id, 'full', false, array('style' => 'margin-left: 10px; max-width: min(200px, 100%); max-height: 200px; width: auto;')); ?>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                </div>
            </form>
        </div>
    </div>
<?php
}

// Save or reset default horoscope game styles
function tarotxhoroscope_horoscope_admin_save()
{
    if (!current_user_can('manage_options')) {
        wp_die('You do not have sufficient permissions to access this page.');
    }

    $default_settings = array(
        'font_family' => 'Tahoma',
        'font_size' => '16px',
        'text_color' => '#000000',
        'image_shown' => 1,
        'image_position' => 'top',
        'show_date' => 1,
        'border_enabled' => 1,
        'border_color' => '#b7b7b7',
        'border_width' => 3,
        'border_radius' => 15,
        'width' => 800,
    );

    if (
        isset($_POST['update_horoscope_settings']) &&
        isset($_POST['tarotxhoroscope_horoscope_nonce']) &&
        wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['tarotxhoroscope_horoscope_nonce'])), 'tarotxhoroscope_horoscope_settings_nonce')
    ) {
        $settings = array(
            'font_family' => isset($_POST['font_family']) ? sanitize_text_field(wp_unslash($_POST['font_family'])) : $default_settings['font_family'],
            'font_size' => isset($_POST['font_size']) ? sanitize_text_field(wp_unslash($_POST['font_size'])) : $default_settings['font_size'],
            'text_color' => isset($_POST['text_color']) ? sanitize_hex_color(wp_unslash($_POST['text_color'])) : $default_settings['text_color'],
            'image_shown' => isset($_POST['image_shown']) ? 1 : 0,
            'image_position' => isset($_POST['image_position']) ? sanitize_text_field(wp_unslash($_POST['image_position'])) : $default_settings['image_position'],
            'show_date' => isset($_POST['show_date']) ? 1 : 0,
            'border_enabled' => isset($_POST['border_enabled']) ? 1 : 0,
            'border_color' => isset($_POST['border_color']) ? sanitize_hex_color(wp_unslash($_POST['border_color'])) : $default_settings['border_color'],
            'border_width' => isset($_POST['border_width']) ? intval(wp_unslash($_POST['border_width'])) : $default_settings['border_width'],
            'border_radius' => isset($_POST['border_radius']) ? intval(wp_unslash($_POST['border_radius'])) : $default_settings['border_radius'],
            'width' => isset($_POST['width']) ? max(400, min(800, intval(wp_unslash($_POST['width'])))) : $default_settings['width'],
        );
        update_option('tarotxhoroscope_horoscope_settings', $settings);
    }

    if (
        isset($_POST['reset_to_default']) &&
        isset($_POST['tarotxhoroscope_horoscope_nonce']) &&
        wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['tarotxhoroscope_horoscope_nonce'])), 'tarotxhoroscope_horoscope_settings_nonce')
    ) {
        update_option('tarotxhoroscope_horoscope_settings', $default_settings);
    }
}

function tarotxhoroscope_generate_horoscope_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';
        echo "<option value='" . esc_attr($size) . "' " . selected($selected_value, $size, false) . ">" . esc_html($size) . "</option>";
    }
    echo "</select>";
}
