<?php
defined('ABSPATH') || exit;

function termin_kalender_add_block_calendar_admin_menu()
{
    $page_title = esc_html__('Calendar Block', 'termin-kalender');
    $menu_title = $page_title;
    $capability = 'termin_kalender_edit';
    $menu_slug = 'terminkalender_calendar';
    $callback = 'termin_kalender_render_block_calendar_admin_menu_page';

    // Register the admin page and -  Add the hook suffix to the shared static property.
    Termin_Kalender_Plugin::$ter_kal_admin_pages_hook_suffixes[$page_title] = add_submenu_page(
        'termin-kalender',
        $page_title,
        $menu_title,
        $capability,
        $menu_slug,
        $callback,
    );
}
// add_action('admin_menu', 'termin_kalender_add_block_calendar_admin_menu', 16);

//-------------------------------------------------------------------------------------

function termin_kalender_render_block_calendar_admin_menu_page()
{
    // Check user capabilities
    if (!current_user_can('termin_kalender_edit')) {
        return;
    }
    ?>
    <div class="wrap termin-kalender-admin-container">
        <h2 class="termin-kalender-admin-page-title">
            Termin-Kalender <?php echo esc_html__('Calendar', 'termin-kalender'); ?> <span class="label label-free"
                style="vertical-align: middle; font-size: 14px; position: relative; top: -4px;">FREE</span>
        </h2>

        <div class="tk-modern-card" style="margin-bottom: 30px;">
            <div class="termin-kalender-admin-card-body">
                <h2 class="termin-kalender-admin-h2">
                    <?php echo esc_html__('Recommended: Use Gutenberg Blocks', 'termin-kalender'); ?>
                </h2>
                <p class="termin-kalender-admin-text-lead">
                    <?php echo esc_html__('The easiest and most modern way to display your calendar is using our native Gutenberg block. It integrates perfectly with your theme and requires zero coding.', 'termin-kalender'); ?>
                </p>

                <div class="termin-kalender-admin-notice-info">
                    <h3 class="termin-kalender-admin-h3">
                        <?php echo esc_html__('Page Assistant', 'termin-kalender'); ?>
                    </h3>
                    <p class="termin-kalender-admin-text-muted">
                        <?php echo esc_html__('Let us instantly create an empty page with the Calendar block already perfectly inserted for you:', 'termin-kalender'); ?>
                    </p>
                    <?php
                    // ter_kal_CHANGE: Fetch categories for magic page dialog
                    $tk_manager = class_exists('Termin_Kalender_Manager') ? Termin_Kalender_Manager::get_instance() : null;
                    $ter_kal_data = $tk_manager ? $tk_manager->get_termin_kalender_data() : [];
                    $ter_kal_categories = $ter_kal_data['TERMIN_KALENDER_KATEGORIEN'] ?? [];
                    ?>
                    <div id="tk-magic-page-wrapper">
                        <button id="tk-magic-page-show-options" type="button" class="button button-primary button-hero"
                            style="font-size: 16px;">
                            <span class="dashicons dashicons-calendar-alt termin-kalender-admin-icon-inline"></span>
                            <?php echo esc_html__('Create Page with Calendar', 'termin-kalender'); ?>
                        </button>

                        <div id="tk-magic-page-options-container" style="display: none;"
                            class="termin-kalender-admin-box-white">
                            <h4 class="termin-kalender-admin-h4">
                                <?php echo esc_html__('Which categories do you want to show in this Frontend Calendar?', 'termin-kalender'); ?>
                            </h4>
                            <div
                                style="margin-bottom: 20px; max-height: 200px; overflow-y: auto; padding-right: 10px; border: 1px solid #dcdcde; padding: 10px; border-radius: 4px; background: #f6f7f7;">
                                <?php if (!empty($ter_kal_categories)): ?>
                                    <?php foreach ($ter_kal_categories as $cat): ?>
                                        <label
                                            style="display: block; margin-bottom: 8px; font-size: 14px; cursor: pointer; color:#50575e;">
                                            <input type="checkbox" class="tk-magic-cat-checkbox"
                                                value="<?php echo esc_attr($cat['label'] ?? ''); ?>" checked>
                                            <span
                                                style="display: inline-block; width: 12px; height: 12px; background-color: <?php echo esc_attr($cat['backgroundColor'] ?? '#000'); ?>; border-radius: 50%; margin-right: 5px; margin-left: 5px; vertical-align: middle;"></span>
                                            <?php echo esc_html($cat['label'] ?? ''); ?>
                                        </label>
                                    <?php endforeach; ?>
                                <?php else: ?>
                                    <p style="margin: 0; color:#50575e;">
                                        <em><?php esc_html_e('No categories found. All future categories will be shown.', 'termin-kalender'); ?></em>
                                    </p>
                                    <input type="hidden" class="tk-magic-cat-checkbox" value="__dummy_check__" checked>
                                <?php endif; ?>
                            </div>
                            <button type="button" id="tk-magic-page-do-create" class="button button-primary">
                                <?php echo esc_html__('Create Page Now', 'termin-kalender'); ?>
                            </button>
                            <button type="button" id="tk-magic-page-cancel" class="button" style="margin-left: 10px;">
                                <?php echo esc_html__('Cancel', 'termin-kalender'); ?>
                            </button>
                        </div>
                    </div>

                    <script>
                        document.addEventListener('DOMContentLoaded', function () {
                            const showBtn = document.getElementById('tk-magic-page-show-options');
                            const container = document.getElementById('tk-magic-page-options-container');
                            const createBtn = document.getElementById('tk-magic-page-do-create');
                            const cancelBtn = document.getElementById('tk-magic-page-cancel');

                            if (showBtn && container && createBtn) {
                                showBtn.addEventListener('click', function (e) {
                                    e.preventDefault();
                                    container.style.display = 'block';
                                    showBtn.style.display = 'none';
                                });

                                cancelBtn.addEventListener('click', function (e) {
                                    e.preventDefault();
                                    container.style.display = 'none';
                                    showBtn.style.display = 'inline-block';
                                });

                                createBtn.addEventListener('click', function () {
                                    const checkboxes = document.querySelectorAll('.tk-magic-cat-checkbox');
                                    let hiddenCatsArr = [];
                                    checkboxes.forEach(function (cb) {
                                        if (!cb.checked && cb.value && cb.value !== '__dummy_check__') {
                                            hiddenCatsArr.push('tk_hide_cats[]=' + encodeURIComponent(cb.value));
                                        }
                                    });

                                    let url = '<?php echo esc_url_raw(admin_url('post-new.php?post_type=page&post_title=Termin-Kalender&tk_magic_page=calendar&tk_nonce=' . wp_create_nonce('tk_magic_page'))); ?>';

                                    if (hiddenCatsArr.length > 0) {
                                        // Append hidden categories as an array of params
                                        url += '&' + hiddenCatsArr.join('&');
                                    }

                                    window.open(url, '_blank');

                                    container.style.display = 'none';
                                    showBtn.style.display = 'inline-block';
                                });
                            }
                        });
                    </script>
                </div>

                <div style="text-align: center; margin-top:20px;">
                    <img src="<?php echo esc_url(plugins_url('assets/termin-kalender-calendar.png', dirname(__FILE__))); ?>"
                        alt="<?php esc_attr_e('Preview', 'termin-kalender'); ?>"
                        style="max-width: 100%; border-radius: 8px;">
                </div>
            </div>
        </div>

        <div class="tk-modern-card" style="margin-bottom: 30px;">
            <div class="tk-modern-card-body" style="padding: 15px 30px;">
                <h3 style="margin: 0; font-size:1.2em; color:#50575e; cursor: pointer; display: flex; align-items: center; justify-content: space-between;"
                    id="tk-toggle-shortcode-panel">
                    <span><?php echo esc_html__('Not using the Gutenberg Editor? No problem!', 'termin-kalender'); ?></span>
                    <span class="dashicons dashicons-arrow-down-alt2"></span>
                </h3>

                <div id="tk-shortcode-generator-panel"
                    style="display: none; padding-top: 20px; margin-top: 20px; border-top: 1px solid #eee;">
                    <p style="color: #50575e;">
                        <?php echo esc_html__('For Elementor, Divi, or the Classic Editor, simply copy this shortcode into a suitable text or shortcode module.', 'termin-kalender'); ?>
                    </p>

                    <!-- Shortcode Generator -->
                    <div
                        style="background: #f6f7f7; padding: 15px; border-radius: 4px; border: 1px solid #dcdcde; margin-bottom: 15px;">

                        <div style="margin-bottom: 15px;">
                            <strong
                                style="color:#1d2327; display:block; margin-bottom:5px;"><?php echo esc_html__('Time display', 'termin-kalender'); ?>:</strong>
                            <label style="margin-right: 15px; color:#50575e;"><input type="radio" name="tk_sc_show_time"
                                    value="start_end" checked>
                                <?php echo esc_html__('Start & End', 'termin-kalender'); ?></label>
                            <label style="margin-right: 15px; color:#50575e;"><input type="radio" name="tk_sc_show_time"
                                    value="start"> <?php echo esc_html__('Start only', 'termin-kalender'); ?></label>
                            <label style="color:#50575e;"><input type="radio" name="tk_sc_show_time" value="hide">
                                <?php echo esc_html__('Hide', 'termin-kalender'); ?></label>
                        </div>

                        <div style="margin-bottom: 15px;">
                            <strong
                                style="color:#1d2327; display:block; margin-bottom:5px;"><?php echo esc_html__('Which categories do you want to show?', 'termin-kalender'); ?></strong>
                            <div
                                style="max-height: 150px; overflow-y: auto; border: 1px solid #ccc; padding: 10px; background: #fff; border-radius: 3px;">
                                <?php if (!empty($ter_kal_categories)): ?>
                                    <?php foreach ($ter_kal_categories as $cat): ?>
                                        <label
                                            style="display: block; margin-bottom: 5px; font-size: 13px; color:#50575e; cursor:pointer;">
                                            <input type="checkbox" class="tk-sc-cat-checkbox"
                                                value="<?php echo esc_attr($cat['label'] ?? ''); ?>" checked>
                                            <span
                                                style="display: inline-block; width: 12px; height: 12px; background-color: <?php echo esc_attr($cat['backgroundColor'] ?? '#000'); ?>; margin-right: 5px; margin-left: 5px; border-radius: 50%; vertical-align: middle;"></span>
                                            <?php echo esc_html($cat['label'] ?? ''); ?>
                                        </label>
                                    <?php endforeach; ?>
                                <?php else: ?>
                                    <p style="margin:0; color:#50575e;">
                                        <em><?php esc_html_e('No categories found.', 'termin-kalender'); ?></em>
                                    </p>
                                    <input type="hidden" class="tk-sc-cat-checkbox" value="__dummy_check__" checked>
                                <?php endif; ?>
                            </div>
                        </div>

                        <div>
                            <label style="color:#50575e; cursor:pointer;">
                                <input type="checkbox" id="tk_sc_hide_buttons">
                                <?php echo esc_html__('Completely hide category buttons', 'termin-kalender'); ?>
                            </label>
                        </div>

                    </div>

                    <div class="termin-kalender-admin-code-box">
                        <h3 id="ter-kal-copyable-shortcode"
                            style="margin:0; color:#1d2327; user-select:all; font-family:monospace; font-size:1.2em;">
                            [termin-kalender-calendar]</h3>
                    </div>
                    <br>
                    <button type="button" id="ter-kal-copy-button" class="button">
                        <?php esc_html_e('Copy Shortcode', 'termin-kalender'); ?>
                    </button>
                </div>
            </div>
        </div>

        <script>
            document.addEventListener('DOMContentLoaded', function () {
                // Panel Toggle Logic
                const toggleBtn = document.getElementById('tk-toggle-shortcode-panel');
                const panel = document.getElementById('tk-shortcode-generator-panel');
                if (toggleBtn && panel) {
                    toggleBtn.addEventListener('click', function () {
                        const icon = toggleBtn.querySelector('.dashicons');
                        if (panel.style.display === 'none') {
                            panel.style.display = 'block';
                            icon.classList.remove('dashicons-arrow-down-alt2');
                            icon.classList.add('dashicons-arrow-up-alt2');
                        } else {
                            panel.style.display = 'none';
                            icon.classList.remove('dashicons-arrow-up-alt2');
                            icon.classList.add('dashicons-arrow-down-alt2');
                        }
                    });
                }

                // Shortcode Generator Logic
                const scResult = document.getElementById('ter-kal-copyable-shortcode');
                if (panel && scResult) {
                    const timeRadios = panel.querySelectorAll('input[name="tk_sc_show_time"]');
                    const catCheckboxes = panel.querySelectorAll('.tk-sc-cat-checkbox');
                    const hideBtnsCheckbox = document.getElementById('tk_sc_hide_buttons');

                    function updateShortcode() {
                        let sc = '[termin-kalender-calendar';

                        // Time Attribute
                        let showTime = 'start_end';
                        timeRadios.forEach(r => { if (r.checked) showTime = r.value; });
                        if (showTime !== 'start_end') {
                            sc += ' show_time="' + showTime + '"';
                        }

                        // Categories Attribute
                        let hiddenCats = [];
                        catCheckboxes.forEach(cb => {
                            if (!cb.checked && cb.value && cb.value !== '__dummy_check__') {
                                hiddenCats.push(cb.value);
                            }
                        });
                        if (hiddenCats.length > 0) {
                            sc += ' hidden_categories="' + hiddenCats.join(',') + '"';
                        }

                        // Hide Buttons Attribute
                        if (hideBtnsCheckbox && hideBtnsCheckbox.checked) {
                            sc += ' hide_category_buttons="true"';
                        }

                        sc += ']';
                        scResult.innerText = sc;
                    }

                    timeRadios.forEach(r => r.addEventListener('change', updateShortcode));
                    catCheckboxes.forEach(cb => cb.addEventListener('change', updateShortcode));
                    if (hideBtnsCheckbox) hideBtnsCheckbox.addEventListener('change', updateShortcode);

                    // Copy Button Logic
                    const copyBtn = document.getElementById('ter-kal-copy-button');
                    if (copyBtn) {
                        copyBtn.addEventListener('click', function () {
                            navigator.clipboard.writeText(scResult.innerText).then(function () {
                                let originalText = copyBtn.innerText;
                                copyBtn.innerText = '<?php echo esc_js(__('Copied!', 'termin-kalender')); ?>';
                                setTimeout(function () {
                                    copyBtn.innerText = originalText;
                                }, 2000);
                            });
                        });
                    }
                }
            });
        </script>

        <?php
        if (class_exists('Termin_Kalender_Page_Overview')) {
            Termin_Kalender_Page_Overview::render(
                ['termin-kalender/kalender-block'],
                ['termin-kalender-calendar', 'my-termin-kalender', 'termin-kalender-fullpage'],
                __('Active Calendar Pages Overview', 'termin-kalender'),
                __('The following pages currently display the frontend Calendar via Gutenberg Block or Shortcode.', 'termin-kalender'),
                'my-termin-kalender',
                __('Please edit this page and replace the old shortcode with the new unified Calendar Gutenberg block.', 'termin-kalender')
            );
        }
        ?>

        <div class="tk-modern-card">
            <div class="tk-modern-card-body" style="padding: 30px;">
                <p style="margin-top: 0; color:#50575e; font-size: 1.1em;">
                    <i style="color:#2271b1;">📌</i>
                    <strong><?php echo esc_html__('PRO Tip:', 'termin-kalender'); ?></strong>
                    <br><br>
                    <?php esc_html_e('Need more power? The PRO Termin-Kalender lets you display external Google or iCal calendars right on your website, and unlocks recurring events, forms, and custom reservation workflows.', 'termin-kalender'); ?>
                </p>
                <div style="margin-top: 15px;">
                    <a href="<?php echo esc_url(admin_url('admin.php?page=termin_kalender_setup&tab=pro_info')); ?>"
                        class="button bootstrap_button">
                        <?php echo esc_html__('See PRO Features', 'termin-kalender'); ?>
                    </a>
                </div>
            </div>
        </div>
    </div>
    <?php
} // 


