<?php

if (!defined('ABSPATH')) {
    exit;
}

// Add admin menu page under Tools
add_action('admin_menu', 'bibldare_bible_schedule_add_admin_menu');

function bibldare_bible_schedule_add_admin_menu()
{
    add_management_page(
        __('Bible Reading Plan', 'bible-reading-plan'),
        __('Bible Reading Plan', 'bible-reading-plan'),
        'manage_options',
        'bible-daily-reading-plan',
        'bibldare_bible_schedule_tools_page'
    );
}

// Clear cache action
add_action('admin_post_clear_bible_cache', function () {
    if (!current_user_can('manage_options')) {
        wp_die('Unauthorized');
    }

    check_admin_referer('clear_bible_cache_nonce');
    bibldare_clear_bible_schedule_cache();

    wp_redirect(add_query_arg('cache_cleared', '1', admin_url('tools.php?page=bible-daily-reading-plan')));
    exit;
});

function bibldare_clear_bible_schedule_cache($day = null)
{
    if ($day !== null) {
        delete_transient('bibldare_schedule_day_' . $day);
    } else {
        for ($i = 1; $i <= 365; $i++) {
            delete_transient('bibldare_schedule_day_' . $i);
        }
    }
}

// Handle schedule data save
function bibldare_handle_schedule_data_save()
{

    // -----------------------------------------------------------------
    if (empty($_POST['schedule_data'])) {
        return [
            'success' => false,
            'message' => __('No data provided.', 'bible-reading-plan'),
        ];
    }

    // Remove slashes added by magic quotes, then strip any HTML/JS
    $schedule_json = sanitize_text_field(wp_unslash($_POST['schedule_data']));



    $raw_data = json_decode($schedule_json, true);

    if (json_last_error() !== JSON_ERROR_NONE) {
        return [
            'success' => false,
            'message' => sprintf(
                __('Invalid JSON: %s', 'bible-reading-plan'),
                json_last_error_msg()
            ),
        ];
    }


    $validated = bibldare_validate_and_sanitize_schedule($raw_data);


    if (is_wp_error($validated)) {
        return [
            'success' => false,
            'message' => $validated->get_error_message(),
        ];
    }


    if (bibldare_save_schedule_data($validated)) {
        bibldare_clear_bible_schedule_cache();

        return [
            'success' => true,
            'message' => __('Schedule saved successfully.', 'bible-reading-plan'),
        ];
    }

    return [
        'success' => false,
        'message' => __('Failed to save schedule data.', 'bible-reading-plan'),
    ];
}

function bibldare_reset_data()
{
    if (isset($_POST['reset_to_default']) && $_POST['reset_to_default'] === '1') {
        if (!isset($_POST['reset_schedule_nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['reset_schedule_nonce'])), 'reset_schedule_data_nonce')) {
            wp_die('Security check failed');
        }

        $backup_file = plugin_dir_path(dirname(__FILE__)) . 'data/data_backup.php';

        if (!file_exists($backup_file)) {
            add_settings_error('bible_schedule_messages', 'error', __('Backup file not found at:', 'bible-reading-plan') . ' ' . $backup_file, 'error');
            return;
        }

        $default_data = include $backup_file;

        if (!is_array($default_data)) {
            add_settings_error('bible_schedule_messages', 'error', __('Backup file format is invalid (must return an array).', 'bible-reading-plan'), 'error');
            return;
        }

        if (bibldare_save_schedule_data($default_data)) {
            bibldare_clear_bible_schedule_cache();

            add_settings_error(
                'bible_schedule_messages',
                'success',
                __('Successfully reset database to default data!', 'bible-reading-plan'),
                'success'
            );

            return true;
        } else {
            add_settings_error('bible_schedule_messages', 'error', __('Failed to update database with default data.', 'bible-reading-plan'), 'error');
            return false;
        }
    }
}

// Save Bible settings
function bibldare_save_bible_settings()
{
    if (isset($_POST['save_bible_settings'])) {
        check_admin_referer('save_bible_settings_nonce');

        update_option('bibldare_bible_cache_enabled', isset($_POST['cache_enabled']) ? 1 : 0);
        update_option('bibldare_bible_language', sanitize_text_field($_POST['language'] ?? 'eng'));
        update_option('bibldare_bible_version', sanitize_text_field($_POST['version'] ?? ''));
        update_option('bibldare_bible_background', sanitize_text_field($_POST['background'] ?? 'white'));
        update_option('bibldare_bible_timezone', sanitize_text_field($_POST['timezone'] ?? 'Asia/Tbilisi'));
        update_option('bibldare_bible_custom_background_color', sanitize_hex_color($_POST['custom_background_color'] ?? ''));
        update_option('bibldare_bible_text_color', sanitize_hex_color($_POST['text_color'] ?? ''));

        bibldare_clear_bible_schedule_cache();
    }
}

// Admin page content
function bibldare_bible_schedule_tools_page()
{
    if (!current_user_can('manage_options'))
        wp_die('Unauthorized');

    bibldare_save_bible_settings();
    if (isset($_POST['save_schedule_data'])) {
        check_admin_referer('save_schedule_data_nonce');
        bibldare_handle_schedule_data_save();
    }

    $schedule_data = bibldare_get_schedule_data();
    $schedule_json = json_encode($schedule_data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);

    $cache_enabled = get_option('bibldare_bible_cache_enabled', 1);
    $language = get_option('bibldare_bible_language', 'eng');
    $version = get_option('bibldare_bible_version', DEFAULT_VERSION);
    $background = get_option('bibldare_bible_background', 'white');
    $custom_background_color = get_option('bibldare_bible_custom_background_color', '');
    $text_color = get_option('bibldare_bible_text_color', '');
    $timezone_opt = get_option('bibldare_bible_timezone', 'Asia/Tbilisi');

    if (bibldare_reset_data()) {
        $schedule_data = bibldare_get_schedule_data();
        $schedule_json = json_encode($schedule_data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
    }

    $bibleNames = [
        "Genesis",
        "Exodus",
        "Leviticus",
        "Numbers",
        "Deuteronomy",
        "Joshua",
        "Judges",
        "Ruth",
        "1 Samuel",
        "2 Samuel",
        "1 Kings",
        "2 Kings",
        "1 Chronicles",
        "2 Chronicles",
        "Ezra",
        "Nehemiah",
        "Esther",
        "Job",
        "Psalms",
        "Proverbs",
        "Ecclesiastes",
        "Song of Solomon",
        "Isaiah",
        "Jeremiah",
        "Lamentations",
        "Ezekiel",
        "Daniel",
        "Hosea",
        "Joel",
        "Amos",
        "Obadiah",
        "Jonah",
        "Micah",
        "Nahum",
        "Habakkuk",
        "Zephaniah",
        "Haggai",
        "Zechariah",
        "Malachi",
        "Matthew",
        "Mark",
        "Luke",
        "John",
        "Acts",
        "Romans",
        "1 Corinthians",
        "2 Corinthians",
        "Galatians",
        "Ephesians",
        "Philippians",
        "Colossians",
        "1 Thessalonians",
        "2 Thessalonians",
        "1 Timothy",
        "2 Timothy",
        "Titus",
        "Philemon",
        "Hebrews",
        "James",
        "1 Peter",
        "2 Peter",
        "1 John",
        "2 John",
        "3 John",
        "Jude",
        "Revelation"
    ];

    ?>

    <div class="wrap">
        <h1><?php echo esc_html(__('Bible Schedule Tools', 'bible-reading-plan')); ?></h1>

        <?php settings_errors('bible_schedule_messages'); ?>

        <?php if (isset($_GET['cache_cleared'])): ?>
            <div class="notice notice-success is-dismissible">
                <p><strong><?php echo esc_html(__('Cache cleared successfully!', 'bible-reading-plan')); ?></strong>
                    <?php echo esc_html(__('All cached Bible data has been removed.', 'bible-reading-plan')); ?></p>
            </div>
        <?php endif; ?>

        <?php if (isset($save_result)): ?>
            <?php if ($save_result['success']): ?>
                <div class="notice notice-success is-dismissible">
                    <p><strong><?php echo esc_html($save_result['message']); ?></strong></p>
                </div>
            <?php else: ?>
                <div class="notice notice-error is-dismissible">
                    <p><strong><?php echo esc_html(__('Error:', 'bible-reading-plan')); ?></strong>
                        <?php echo esc_html($save_result['message']); ?></p>
                </div>
            <?php endif; ?>
        <?php endif; ?>

        <div style="display: flex; justify-content: flex-start; gap: 20px; margin-top: 20px; align-items: stretch;">

            <div class="card" style="width: 100%; margin: 0; padding: 20px; background: #fff; border: 1px solid #c3c4c7;">
                <h2 class="title" style="margin-top: 0;">
                    <?php echo esc_html(__('Cache Management', 'bible-reading-plan')); ?>
                </h2>

                <div style="margin-bottom: 24px;">
                    <p class="description" style="margin-bottom: 15px;">
                        <?php echo esc_html(__('Force the plugin to fetch fresh Bible data on the next page load.', 'bible-reading-plan')); ?>
                    </p>
                    <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
                        <input type="hidden" name="action" value="clear_bible_cache">
                        <?php wp_nonce_field('clear_bible_cache_nonce'); ?>
                        <button type="submit"
                            class="button button-secondary"><?php echo esc_html(__('Clear All Cache', 'bible-reading-plan')); ?></button>
                    </form>
                </div>

                <hr style="border: 0; border-top: 1px solid #eee; margin: 20px 0;">

                <div>
                    <form method="post">
                        <?php wp_nonce_field('save_bible_settings_nonce'); ?>
                        <input type="hidden" name="save_bible_settings" value="1">
                        <p>
                            <label style="display: flex; align-items: center; gap: 8px;">
                                <input type="checkbox" name="cache_enabled" <?php checked($cache_enabled, 1); ?> value="1">
                                <span><?php echo esc_html(__('Enable Cache', 'bible-reading-plan')); ?></span>
                            </label>
                        </p>
                        <button type="submit"
                            class="button button-primary"><?php echo esc_html(__('Save Settings', 'bible-reading-plan')); ?></button>
                    </form>
                </div>
            </div>

            <div
                style="width: 100%; position: relative; padding: 0.7em 2em 1em; padding-top: 20px; border: 1px solid #c3c4c7; box-shadow: 0 1px 1px rgba(0, 0, 0, 0.04); background: #fff; box-sizing: border-box;">
                <h2 class="title" style="margin-top: 0; margin-bottom: 24px;">
                    <?php echo esc_html(__('Language and Version Settings', 'bible-reading-plan')); ?>
                </h2>
                <form method="post" id="bibldare-language-form">
                    <?php wp_nonce_field('save_bible_settings_nonce'); ?>
                    <input type="hidden" name="save_bible_settings" value="1">

                    <div style="display: flex; flex-direction: column; gap: 24px;">
                        <div>
                            <h3 style="margin: 0 0 8px 0; font-size: 14px; font-weight: 600;">
                                <?php echo esc_html(__('Language', 'bible-reading-plan')); ?>
                            </h3>
                            <select name="language" id="bibldare_language_select"
                                style="width: 100%; max-width: 420px; padding: 6px 8px; border: 1px solid #8c8f94; border-radius: 4px; font-size: 14px;">
                                <option value="eng" <?php selected($language, 'eng'); ?>>
                                    <?php echo esc_html(__('English', 'bible-reading-plan')); ?>
                                </option>
                                <option value="geo" <?php selected($language, 'geo'); ?>>
                                    <?php echo esc_html(__('Georgian', 'bible-reading-plan')); ?>
                                </option>
                            </select>
                        </div>

                        <div>
                            <h3 style="margin: 0 0 8px 0; font-size: 14px; font-weight: 600;">
                                <?php echo esc_html(__('Version', 'bible-reading-plan')); ?>
                            </h3>
                            <select name="version" id="bibldare_version_select"
                                style="width: 100%; max-width: 420px; padding: 6px 8px; border: 1px solid #8c8f94; border-radius: 4px; font-size: 14px;">
                            </select>
                        </div>

                        <div>
                            <h3 style="margin: 0 0 8px 0; font-size: 14px; font-weight: 600;">
                                <?php echo esc_html(__('Background Color', 'bible-reading-plan')); ?>
                            </h3>
                            <select name="background"
                                style="width: 100%; max-width: 420px; padding: 6px 8px; border: 1px solid #8c8f94; border-radius: 4px; font-size: 14px;">
                                <option value="white" <?php selected($background, 'white'); ?>>
                                    <?php echo esc_html(__('White', 'bible-reading-plan')); ?>
                                </option>
                                <option value="black" <?php selected($background, 'black'); ?>>
                                    <?php echo esc_html(__('Black', 'bible-reading-plan')); ?>
                                </option>
                                <option value="cream" <?php selected($background, 'cream'); ?>>
                                    <?php echo esc_html(__('Cream', 'bible-reading-plan')); ?>
                                </option>
                            </select>
                        </div>

                        <div>
                            <h3 style="margin: 0 0 8px 0; font-size: 14px; font-weight: 600;">
                                <?php echo esc_html(__('Timezone', 'bible-reading-plan')); ?>
                            </h3>
                            <select name="timezone" id="bibldare_timezone_select"
                                style="width: 100%; max-width: 420px; padding: 6px 8px; border: 1px solid #8c8f94; border-radius: 4px; font-size: 14px;">
                                <?php echo wp_timezone_choice($timezone_opt); ?>
                            </select>
                        </div>

                        <div>
                            <h3 style="margin: 0 0 8px 0; font-size: 14px; font-weight: 600;">
                                <?php echo esc_html(__('Custom Background Color (optional)', 'bible-reading-plan')); ?>
                            </h3>
                            <input type="text" name="custom_background_color" value="<?php echo esc_attr($custom_background_color); ?>" class="bibldare-color-picker" data-default-color="#ffffff" />
                        </div>

                        <div>
                            <h3 style="margin: 0 0 8px 0; font-size: 14px; font-weight: 600;">
                                <?php echo esc_html(__('Custom Text Color (optional)', 'bible-reading-plan')); ?>
                            </h3>
                            <input type="text" name="text_color" value="<?php echo esc_attr($text_color); ?>" class="bibldare-color-picker" data-default-color="#000000" />
                        </div>

                        <?php
                        $shortcode = '[bibldare_bible_reading_plan';
                        if (!empty($language))
                            $shortcode .= ' lang="' . esc_attr($language) . '"';
                        if (!empty($version))
                            $shortcode .= ' version="' . esc_attr($version) . '"';
                        if (!empty($background))
                            $shortcode .= ' background="' . esc_attr($background) . '"';
                        if (!empty($custom_background_color))
                            $shortcode .= ' custom_background_color="' . esc_attr($custom_background_color) . '"';
                        if (!empty($text_color))
                            $shortcode .= ' text_color="' . esc_attr($text_color) . '"';
                        if (!empty($timezone_opt))
                            $shortcode .= ' timezone="' . esc_attr($timezone_opt) . '"';
                        $shortcode .= ']';
                        ?>

                        <div>
                            <h3 style="margin: 0 0 8px 0; font-size: 14px; font-weight: 600;">
                                <?php echo esc_html(__('Shortcode:', 'bible-reading-plan')); ?>
                            </h3>
                            <input id="bibldareShortcodeInput" type="text" readonly onclick="this.select()"
                                value="<?php echo esc_attr($shortcode); ?>"
                                style="width: 100%; padding: 8px; font-family: monospace; background: #f6f7f7; border: 1px solid #c3c4c7; border-radius: 4px; box-sizing: border-box;">
                        </div>
                    </div>
                </form>
            </div>
        </div>

        <div class="card" style="max-width: 100%; margin-top: 20px;">
            <h2 class="title"><?php echo esc_html(__('Edit Schedule Data', 'bible-reading-plan')); ?></h2>

            <p><strong><?php echo esc_html(__('Note:', 'bible-reading-plan')); ?></strong>
                <?php echo esc_html(__('Schedule data is stored securely in your WordPress database. Edit the JSON below to customize your reading schedule.', 'bible-reading-plan')); ?>
            </p>

            <?php if (file_exists(plugin_dir_path(BIBLDARE_PLUGIN_PATH) . 'assets/images/data-structure.png')): ?>
                <img src="<?php echo esc_url(plugin_dir_url(BIBLDARE_PLUGIN_PATH) . 'assets/images/data-structure.png'); ?>"
                    alt="Data Structure Example" style="width: 100%; max-width: 500px; border-radius: 5px; margin: 15px 0;" />
            <?php endif; ?>

            <div class="bible-schedule">
                <h3><?php echo esc_html(__('Book Indexes', 'bible-reading-plan')); ?></h3>
                <ul style="column-count: 5; column-gap: 20px; list-style-position: inside;">
                    <?php foreach ($bibleNames as $index => $book): ?>
                        <li><?php echo esc_html(($index + 1) . ': ' . $book); ?></li>
                    <?php endforeach; ?>
                </ul>
            </div>

            <p><?php echo esc_html(__("Today's index is:", 'bible-reading-plan')); ?>
                <strong><?php echo esc_html(bibldare_get_today_index()); ?></strong>
            </p>

            <form method="post" style="margin-top: 15px;">
                <?php wp_nonce_field('save_schedule_data_nonce'); ?>
                <input type="hidden" name="save_schedule_data" value="1">
                <textarea name="schedule_data" id="bible_schedule_editor"
                    style="width: 100%; height: 500px; font-family: monospace; font-size: 14px; padding: 10px; border: 1px solid #ddd; border-radius: 4px;"
                    spellcheck="false"><?php echo esc_textarea($schedule_json); ?></textarea>
                <p class="submit" style="margin-top: 15px;">
                    <button type="submit" class="button button-primary"
                        onclick="return confirm('<?php echo esc_js(__('Are you sure you want to save changes?', 'bible-reading-plan')); ?>');">
                        <?php echo esc_html(__('Save Changes', 'bible-reading-plan')); ?>
                    </button>
                    <button type="button" class="button" onclick="location.reload();">
                        <?php echo esc_html(__('Cancel / Reload', 'bible-reading-plan')); ?>
                    </button>
                </p>
            </form>

            <form method="post" style="margin-top: 10px;">
                <?php wp_nonce_field('reset_schedule_data_nonce', 'reset_schedule_nonce'); ?>
                <input type="hidden" name="reset_to_default" value="1">
                <p class="submit" style="margin-top: 0;">
                    <button type="submit" class="button button-secondary"
                        onclick="return confirm('<?php echo esc_js(__('Are you sure you want to reset to default data? This will replace all current content.', 'bible-reading-plan')); ?>');"
                        style="background: #dc3545; border-color: #dc3545; color: #fff;">
                        <?php echo esc_html(__('Reset to Default', 'bible-reading-plan')); ?>
                    </button>
                </p>
            </form>
        </div>

        <div class="card" style="max-width: 100%; margin-top: 20px;">
            <h2 class="title"><?php echo esc_html(__('Cache Information', 'bible-reading-plan')); ?></h2>
            <?php
            $cached_days = 0;
            for ($i = 1; $i <= 365; $i++) {
                if (get_transient('bibldare_schedule_day_' . $i) !== false) {
                    $cached_days++;
                }
            }
            ?>
            <p><strong><?php echo esc_html(__('Cached Days:', 'bible-reading-plan')); ?></strong>
                <?php echo esc_html($cached_days); ?> / 365</p>
            <p><strong><?php echo esc_html(__('Cache Duration:', 'bible-reading-plan')); ?></strong>
                <?php echo esc_html(__('30 days', 'bible-reading-plan')); ?></p>
            <p><strong><?php echo esc_html(__('Storage:', 'bible-reading-plan')); ?></strong>
                <?php echo esc_html(__('WordPress database (shared across all users)', 'bible-reading-plan')); ?></p>
        </div>
    </div>

    <?php
}