<?php


if ( isset($_GET['ff_clear_content']) ) {

    $post_id = get_queried_object_id();

    if ( ! $post_id ) {
        wp_die('Post not found.');
    }

    if ( ! current_user_can('edit_post', $post_id) ) {
        wp_die('You do not have permission to clear this content.');
    }

    // Get current post so we can preserve title & status
    $current_post = get_post( $post_id );

    // Empty only the content
    wp_update_post([
        'ID'           => $post_id,
        'post_title'   => $current_post->post_title,
        'post_status'  => $current_post->post_status,
        'post_content' => ''
    ]);

    // Show confirmation screen (no redirect)
    $return_url = get_permalink($post_id);

    ?>
    <!DOCTYPE html>
    <html>
    <head>
        <title>Content Deleted</title>
        <style>
            body {
                font-family: Arial, sans-serif;
                text-align: center;
                margin-top: 80px;
            }
            .button {
                display: inline-block;
                margin-top: 20px;
                padding: 10px 20px;
                background: #0073aa;
                color: white;
                text-decoration: none;
                border-radius: 4px;
            }
            .button:hover {
                background: #005f8d;
            }
        </style>
    </head>
    <body>
        <h2>Content has been deleted.</h2>
        <p>Your page content has been cleared successfully.</p>
        <a href="<?php echo esc_url($return_url); ?>" class="button" style="color:white;">Continue to blank page</a>

<a href="/?ff_section_add_with_template=1&post_id=<?php echo $post_id; ?>" 
   class="button" 
   style="color:white;">
    Add a new section
</a>
    </body>
    </html>
    <?php

    exit; // Stop page execution here
}


if (get_theme_mod('my_plugin_show_page_admin_links')) {
    if (current_user_can('manage_options') && is_singular()) {
        // Top admin toggle bar
        echo "<div style=\"z-index:9999999;position:fixed;top:40px;right:20px;background-color:lightblue;padding:5px;padding-left:20px;padding-right:20px;border:1px black solid;font-size:14px;font-family:Arial,Helvetica;\">";
        
        // Define showadminmenus variable with a default value if not set
        global $showadminmenus;
        if (!isset($showadminmenus)) {
            $showadminmenus = 'hidden';
        }
        
        if ($showadminmenus === 'hidden') {
            echo '<span id="admin-links-toggle"><a href="#" id="toggle-admin-links" style="color:black;text-decoration:none;">Show admin links</a></span>';
        } else {
            echo '<span id="admin-links-toggle"><a href="#" id="toggle-admin-links" style="color:black;text-decoration:none;">Hide admin links</a></span>';
        }
        echo "</div>";

        $edit_link = get_edit_post_link();

        if ($edit_link) {
            echo '<div class="firefly-admin-1"><div class="firefly-admin-2">Firefly page options</div><div class="firefly-admin-3">';
            echo '<a href="' . esc_url($edit_link) . '" style="color:black;text-decoration:none;">Edit this page using WordPress</a>';
 
          $add_page_url = add_query_arg(
    'ff_page_add_with_template',
    1,
    home_url( '/' )
);



global $post;

echo '<div style="font-size:11px;margin:0px;"><a href="' . esc_url( $add_page_url ) . '" style="color:black;text-decoration:none;">Add a new page with a template (beta)</a>';



$add_section_url = add_query_arg(
    array(
        'ff_section_add_with_template' => 1,
        'post_id'                      => get_the_ID(), // or $post->ID
    ),
    home_url( '/' )
);

echo ' | <a href="' . esc_url( $add_section_url  ) . '" style="color:black;text-decoration:none;">Add a section to this page (beta)</a>';



// Only show delete link to users who can delete this page
if ( 
    ! is_front_page() && 
    ! is_home() &&
    is_user_logged_in() && 
    current_user_can( 'delete_page', $post->ID ) 
) {

    // Build a trash URL with nonce
    $trash_url = wp_nonce_url(
        add_query_arg(
            array(
                'ff_trash_page' => $post->ID,
            ),
            get_permalink( $post )
        ),
        'ff_trash_page_' . $post->ID
    );


$current_user = wp_get_current_user();

if ( $current_user instanceof WP_User ) {
    if ( strtolower($current_user->user_email) === 'drjeffsimmonds@gmail.com' ) {
   
    echo ' | <a href="' . esc_url( $trash_url ) . '" 
             style="text-decoration:none;color:red;"
             onclick="return confirm(\'Are you sure you want to delete this page?\');">
             Delete this page!
          </a>';



      


                echo ' | <a href="' . esc_url(add_query_arg('show_all_settings', '1')) . '" style="text-decoration:none;color:black;">Show all settings</a>';
            
                $show_raw_code = add_query_arg( 'ff_show_raw', 1, get_permalink() );

                echo ' | <a href="' . esc_url( $show_raw_code ) . '" style="color:black;text-decoration:none;" target="_blank">Show raw code for the page</a>';

                $clear_url = add_query_arg( 'ff_clear_content', 1, get_permalink() );

echo ' | <a href="#" onclick="clearContentPrompt(\'' . esc_url( $clear_url ) . '\')" style="color:red;text-decoration:none;">Clear all the content from this page</a>';

echo "
<script>
    function clearContentPrompt(url) {
        if (confirm('Are you sure you want to delete ALL content from this page?')) {
            window.location.href = url;
        }
    }
</script>
";



            }
        
}
}
echo "</div>";

            if (is_plugin_active('Firefly-AI/Firefly-AI.php')) {
    if (get_the_ID()) {
        $refer = get_the_ID();
    } else {
        $refer = 0;
    }

    $link = admin_url('admin.php?page=firefly-ai' . ($refer ? '&from=' . $refer : ''));
    echo ' | <a href="' . esc_url($link) . ' "><span style="color:black;">Add a Firefly AI story</span></a>';
}



            if ($my_plugin_show_story_admin_links) {
             echo ' | <a href="#" onclick="openNewPagePopup();" style="color:black;text-decoration:none;">Add a new page</a>';
            } 



$setup_plugins = [
    [
        'name' => 'Fluent Forms',
        'slug' => 'fluentform',
        'file' => 'fluentform/fluentform.php',
    ],
    [
        'name' => 'Fluent SMTP',
        'slug' => 'fluent-smtp',
        'file' => 'fluent-smtp/fluent-smtp.php',
    ],
    [
        'name' => 'FooGallery',
        'slug' => 'foogallery',
        'file' => 'foogallery/foogallery.php',
    ],
    [
        'name' => 'FooBox Image Lightbox',
        'slug' => 'foobox-image-lightbox',
        'file' => 'foobox-image-lightbox/foobox-free.php',
    ],
    [
        'name' => 'WPS Hide Login',
        'slug' => 'wps-hide-login',
        'file' => 'wps-hide-login/wps-hide-login.php',
    ],
    [
        'name' => 'MetaSlider – Slider, Gallery, and Carousel',
        'slug' => 'ml-slider',
        'file' => 'ml-slider/ml-slider.php',
    ],
      [
        'name' => 'Disable Comments – Remove Comments & Stop Spam',
        'slug' => 'disable-comments',
        'file' => 'disable-comments/disable-comments.php',
    ],

];

include_once ABSPATH . 'wp-admin/includes/plugin.php';







$stufftodo = '';
$issues = [];


 if ( ! get_theme_mod('firefly_no_menu', false)) {
        if (!has_nav_menu('main-menu')) {
             $issues[] = "No menu is assigned to Main Menu.";
        }

}



   $fonts_page = get_page_by_path('firefly-view-fonts');
    if (!$fonts_page) {
        $issues[] = 'The page with slug "firefly-view-fonts" is missing.';
    }

			
if ( ! get_theme_mod( 'my_plugin_do_not_connect_to_manageWP' ) ) {
    // Check if 'ManageWP - Worker' plugin is installed and active
    include_once ABSPATH . 'wp-admin/includes/plugin.php';
    if ( ! is_plugin_active( 'worker/init.php' ) ) {
        $issues[] = 'This site is not connected to ManageWP.';
    }
}


// ✅ Banner visibility check
$header_mode = get_theme_mod('firefly_header_choice', 'logo_only');

if ($header_mode == "banner_and_logo" OR $header_mode == "banner_only") {

    $banner_desktop = get_theme_mod('firefly_banner_desktop');
    $banner_tablet  = get_theme_mod('firefly_banner_tablet');
    $banner_mobile  = get_theme_mod('firefly_banner_mobile');

    if (empty($banner_desktop)) {
        $issues[] = '🖥️ <strong>Banner:</strong> Desktop background image is not set.';
    }
    if (empty($banner_tablet)) {
        $issues[] = '📱 <strong>Banner:</strong> Tablet background image is not set.';
    }
    if (empty($banner_mobile)) {
        $issues[] = '📲 <strong>Banner:</strong> Mobile background image is not set.';
    }
}



if ($header_mode == "banner_and_logo" OR $header_mode == "logo_only") {
    $show_logo = "yes";
}
else    
{
    $show_logo = "";
}

// ✅ Logo checks
//$show_logo   = !get_theme_mod('my_plugin_hide_logo', false);
$logo_pc     = get_theme_mod('my_plugin_logo_pc');
$logo_mobile = get_theme_mod('my_plugin_logo_mobile');

if ($show_logo && empty($logo_pc)) {
    $issues[] = '⚠️ Logo is enabled, but no <strong>desktop logo</strong> has been uploaded.';
}

if ($show_logo && !empty($logo_pc) && empty($logo_mobile)) {
    $issues[] = '📱 Logo is visible, but no <strong>mobile logo</strong> has been selected.';
}




// ✅ Plugin checks
foreach ($setup_plugins as $plugin) {
    $plugin_path = $plugin['file'];
    $plugin_slug = $plugin['slug'];
    $plugin_name = $plugin['name'];

    if (!file_exists(WP_PLUGIN_DIR . '/' . $plugin_path)) {
        $install_url = wp_nonce_url(
            admin_url('update.php?action=install-plugin&plugin=' . urlencode($plugin_slug)),
            'install-plugin_' . $plugin_slug
        );
        $issues[] = '🔌 Plugin <strong>' . esc_html($plugin_name) . '</strong> is <strong>not installed</strong>. 
            <a href="' . esc_url($install_url) . '" target="_blank">Install now</a>';
    } elseif (!is_plugin_active($plugin_path)) {
        $activate_url = wp_nonce_url(
            admin_url('plugins.php?action=activate&plugin=' . urlencode($plugin_path)),
            'activate-plugin_' . $plugin_path
        );
        $issues[] = '🟡 Plugin <strong>' . esc_html($plugin_name) . '</strong> is <strong>installed but not active</strong>. 
            <a href="' . esc_url($activate_url) . '" target="_blank">Activate now</a>';
    }
}

// ✅ WPS Hide Login check
$custom_login_slug = get_option('whl_page');
if (empty($custom_login_slug)) {
    $settings_url = admin_url('options-general.php');
    $issues[] = '🔐 <strong>WPS Hide Login:</strong> Not configured. Default login is still <code>/wp-login.php</code>. 
        <a href="' . esc_url($settings_url) . '" target="_blank">Configure now</a>';
}

// ✅ User checks
$user_by_email = get_user_by('email', 'drjeffsimmonds@gmail.com');
if (!$user_by_email) {
    $add_user_url = admin_url('user-new.php');
    $issues[] = '👤 No user found with email <strong>drjeffsimmonds@gmail.com</strong>. 
        <a href="' . esc_url($add_user_url) . '" target="_blank">Add user</a>';
}

$user_by_login = get_user_by('login', 'rainbowdev');
if (!$user_by_login) {
    $add_user_url = admin_url('user-new.php');
    $issues[] = '👤 No user found with username <strong>rainbowdev</strong>. 
        <a href="' . esc_url($add_user_url) . '" target="_blank">Add user</a>';
}


  //if (!$user_by_email || !$user_by_login) {
    //    $stufftodo .= '<div style="margin-top:10px; padding:10px; background-color:white; border-radius:4px;">';
    //    $stufftodo .= '<em>Please go to <a href="' . esc_url(admin_url('user-new.php')) . '">Add New User</a> to create them.</em>';
     //   $stufftodo .= '</div>';
  //  }



// 2. Check if a page with slug 'terms-and-conditions' exists
$terms_page = get_page_by_path('terms-and-conditions');
if (!$terms_page) {
    $issues[] = '📄 <strong>Terms and Conditions</strong> page is missing. <a href="' . admin_url('post-new.php?post_type=page') . '">Add one now</a>. You can get the text from <a href="https://docs.google.com/document/d/1znBr9BRKUBAGMe0y6g3ndK0E5jMqJRmDJ436aHuOxig" target="_blank">here</a>.';
}

// 3. Check if the default "Hello world!" post exists
$hello_post = get_page_by_title('Hello world!', OBJECT, 'post');
if ($hello_post) {
    $delete_url = get_delete_post_link($hello_post->ID, '', true); // true = force delete
    $issues[] = '🗑️ <strong>Hello world!</strong> post still exists. <a href="' . esc_url($delete_url) . '">Delete it now</a>.';
}

// 1. Check plugins’ auto-update status
if ( ! function_exists( 'get_plugins' ) ) {
    require_once ABSPATH . 'wp-admin/includes/plugin.php';
}
$all_plugins   = get_plugins();
$auto_updates  = (array) get_option( 'auto_update_plugins', [] );
$not_auto      = [];

foreach ( $all_plugins as $plugin_file => $plugin_data ) {
    // Skip plugins with "Firefly" in their name
    if (stripos($plugin_data['Name'], 'Firefly') !== false) {
        continue;
    }
    
    if ( ! in_array( $plugin_file, $auto_updates, true ) ) {
        $not_auto[] = $plugin_data['Name'];
    }
}

if ( ! empty( $not_auto ) ) {
    $issues[] = '⚙️ <strong>The following plugins are not set to auto update:</strong> ' 
        . implode( ', ', $not_auto ) 
        . '.';
}


            echo <<<HTML
<div id="newPagePopup" style="
    display:none;
    position:fixed;
    top:50%;
    left:50%;
    transform:translate(-50%, -50%);
    background:#fff;
    border-radius:12px;
    box-shadow:0 8px 24px rgba(0,0,0,0.2);
    padding:30px 25px;
    z-index:9999;
    max-width:400px;
    width:90%;
    font-family:'Segoe UI', sans-serif;
    text-align:center;
">

    <h2 style="margin:0 0 20px;font-size:22px;color:#1e73be;">📝 Create a New Page</h2>

    <label for="newPageName" style="display:block;margin-bottom:8px;font-weight:500;font-size:15px;color:#333;">Page name:</label>
    
    <input type="text" id="newPageName" name="pagename" placeholder="e.g. About Us" style="
        width:100%;
        padding:10px 12px;
        border:1px solid #ccc;
        border-radius:6px;
        font-size:15px;
        box-sizing:border-box;
        margin-bottom:20px;
    ">

    <div style="display:flex;gap:10px;justify-content:center;">
        <button onclick="submitNewPage();" style="
            background-color:#1e73be;
            color:white;
            border:none;
            padding:10px 20px;
            border-radius:6px;
            font-size:14px;
            cursor:pointer;
        ">➕ Create Page</button>

        <button onclick="document.getElementById('newPagePopup').style.display='none'" style="
            background-color:#e0e0e0;
            color:#333;
            border:none;
            padding:10px 20px;
            border-radius:6px;
            font-size:14px;
            cursor:pointer;
        ">Cancel</button>
    </div>
</div>



<script>
function openNewPagePopup() {
    document.getElementById('newPagePopup').style.display = 'block';
}

function submitNewPage() {
    const pageName = document.getElementById('newPageName').value.trim();
    if (pageName) {
        // Redirect to create page logic
        const url = new URL(window.location.href);
        url.searchParams.set('create_new_page', '1');
        url.searchParams.set('pagename', pageName);
        window.location.href = url.toString();
    } else {
        alert("Please enter a page name.");
    }
}
</script>



HTML;

            // Using single quotes inside double quotes to prevent syntax issues
           // Conditionally show "Add a block" link

             if ($my_plugin_show_story_admin_links) {

if (get_theme_mod('my_plugin_add_textblock')) {
    echo ' | <a href="#" onclick="document.getElementById(\'firefly-add-blocks\').style.display=\'block\'; return false;" style="color:black;text-decoration:none;">Add a block to this page</a>';
}

// Conditionally show "Delete a block" link
if (get_theme_mod('my_plugin_delete_mode')) {
    echo '<span id="delete-links-toggle"> | <a href="#" id="toggle-delete-blocks" style="color:black;text-decoration:none;">Delete a block on this page</a></span>';
}
             }


if (get_theme_mod('this_site_is_live')) {
   

    

// ✅ Favicon check
if (empty(get_theme_mod('my_plugin_favicon')) && empty(get_site_icon_url())) {
    $issues[] = '🌟 <strong>Favicon</strong> is not set. Please upload a favicon for better branding.';
}

    $live_plugins = [
    [
        'name' => 'Cloudflare',
        'slug' => 'cloudflare',
        'file' => 'cloudflare/cloudflare.php',
    ],
    [
        'name' => 'Site Kit by Google',
        'slug' => 'google-site-kit',
        'file' => 'google-site-kit/google-site-kit.php',
    ],
    [
        'name' => 'MetaSlider',
        'slug' => 'ml-slider',
        'file' => 'ml-slider/ml-slider.php',
    ],
    [
        'name' => 'UpdraftPlus',
        'slug' => 'updraftplus',
        'file' => 'updraftplus/updraftplus.php',
    ],
    [
        'name' => 'Wordfence Security',
        'slug' => 'wordfence',
        'file' => 'wordfence/wordfence.php',
    ],
      [
        'name' => 'Yoast SEO',
        'slug' => 'wordpress-seo',
        'file' => 'wordpress-seo/wp-seo.php',
    ],
      [
        'name' => 'XML Sitemap Generator for Google',
        'slug' => 'google-sitemap-generator',
        'file' => 'google-sitemap-generator/sitemap.php',
    ],
];

// ✅ Add missing or inactive live plugin notices
// ✅ Add missing or inactive live plugin notices (with "Download plugin" link)
foreach ($live_plugins as $plugin) {
    $plugin_path = $plugin['file'];
    $plugin_name = esc_html($plugin['name']);
    $plugin_slug = $plugin['slug'];
    $wporg_url   = 'https://wordpress.org/plugins/' . urlencode($plugin_slug) . '/';

    if (!file_exists(WP_PLUGIN_DIR . '/' . $plugin_path)) {
        $install_url = wp_nonce_url(
            admin_url('update.php?action=install-plugin&plugin=' . urlencode($plugin_slug)),
            'install-plugin_' . $plugin_slug
        );
        $issues[] = '🌐 Recommended live plugin <strong>' . $plugin_name . '</strong> is <strong>not installed</strong>. ' .
            '<a href="' . esc_url($install_url) . '" target="_blank" rel="noopener">Install now</a> ';
    } elseif (!is_plugin_active($plugin_path)) {
        $activate_url = wp_nonce_url(
            admin_url('plugins.php?action=activate&plugin=' . urlencode($plugin_path)),
            'activate-plugin_' . $plugin_path
        );
        $issues[] = '🟡 Recommended live plugin <strong>' . $plugin_name . '</strong> is <strong>installed but not active</strong>. ' .
            '<a href="' . esc_url($activate_url) . '">Activate now</a> | ' ;
    }
}

//======================
// go live checklist
//======================


if (!get_theme_mod('go_live_done_cf_ssl_full')) {
    $help_url = 'https://developers.cloudflare.com/ssl/edge-certificates/full/';
    $mark_done_url = wp_nonce_url(
        add_query_arg('gl_done', 'cf_ssl_full'),
        'gl_done_cf_ssl_full'
    );

    $issues[] = '🔐 Cloudflare SSL/TLS should be set to <strong>Full</strong> (not Flexible). '

        . '<a href="' . esc_url($mark_done_url) . '">Mark done</a>';
}


// === Extra go-live issues (manual checks with "Mark done") ===

// 1) Google Site Kit owner account
if (!get_theme_mod('go_live_done_sitekit_owner')) {
    $sitekit_url = admin_url('admin.php?page=googlesitekit-dashboard');
    $issues[] = '📊 Google Site Kit should be set up with <strong>rainbowquotesandinvoices@gmail.com</strong>. '
        . '<a href="' . esc_url($sitekit_url) . '" target="_blank" rel="noopener">Open Site Kit</a> | '
        . '<a href="' . esc_url(firefly_gl_mark_done_link('sitekit_owner')) . '">Mark done</a>';
}

// 2) Cloudflare Turnstile on Fluent Forms
if (!get_theme_mod('go_live_done_ff_turnstile')) {
    $ff_url = admin_url('admin.php?page=fluent_forms');
    $docs  = 'https://developers.cloudflare.com/turnstile/';
    $issues[] = '🛡️ Add a <strong>Cloudflare Turnstile</strong> captcha to your Fluent Forms. '
        . '<a href="' . esc_url($ff_url) . '" target="_blank" rel="noopener">Open Fluent Forms</a> | '
        . '<a href="' . esc_url($docs) . '" target="_blank" rel="noopener">Turnstile docs</a> | '
        . '<a href="' . esc_url(firefly_gl_mark_done_link('ff_turnstile')) . '">Mark done</a>';
}



// 3) Portfolio thumbnail added
if ( ! get_theme_mod('go_live_done_portfolio_thumbnail') ) {
    $portfolio_url = 'https://fireflywebsites.co.nz/portfolio/';
    $issues[] = '🖼️ Add a <strong>thumbnail</strong> for this site to the Firefly Websites portfolio. '
        . '<a href="' . esc_url($portfolio_url) . '" target="_blank" rel="noopener">Open portfolio page</a> | '
        . '<a href="' . esc_url(firefly_gl_mark_done_link('portfolio_thumbnail')) . '">Mark done</a>';
}


// 4) Site marked as live on Firefly WP Theme page
if ( ! get_theme_mod('go_live_done_firefly_theme_live') ) {
    $theme_url = 'https://rainbowdigital.co.nz/firefly/firefly-WP-theme.php';
    $issues[] = '🚀 Mark this site as <strong>live</strong> on the Firefly WP Theme (R2D2) page. '
        . '<a href="' . esc_url($theme_url) . '" target="_blank" rel="noopener">Open theme page</a> | '
        . '<a href="' . esc_url(firefly_gl_mark_done_link('firefly_theme_live')) . '">Mark done</a>';
}


// 5) Firefly WP Theme page URL updated to live site
if ( ! get_theme_mod('go_live_done_firefly_theme_url') ) {
    $theme_url = 'https://rainbowdigital.co.nz/firefly/firefly-WP-theme.php';
    $issues[] = '🔗 Update the <strong>site URL</strong> on the Firefly WP Theme page so it points to the <strong>live site</strong>. '
        . '<a href="' . esc_url($theme_url) . '" target="_blank" rel="noopener">Open theme page</a> | '
        . '<a href="' . esc_url(firefly_gl_mark_done_link('firefly_theme_url')) . '">Mark done</a>';
}


// 3) Fluent Forms recipient address
if (!get_theme_mod('go_live_done_ff_recipient')) {
    $ff_url = admin_url('admin.php?page=fluent_forms');
    $issues[] = '✉️ Check the <strong>recipient address</strong> in all Fluent Forms notifications. '
        . '<a href="' . esc_url($ff_url) . '" target="_blank" rel="noopener">Open Fluent Forms</a> | '
        . '<a href="' . esc_url(firefly_gl_mark_done_link('ff_recipient')) . '">Mark done</a>';
}

// 4) Fluent SMTP uses client’s own account
if (!get_theme_mod('go_live_done_fluent_smtp_account')) {
    $smtp_url = admin_url('admin.php?page=fluent-mail');
    $issues[] = '📮 Ensure <strong>Fluent SMTP</strong> is configured with the client’s own email account (not staging). '
        . '<a href="' . esc_url($smtp_url) . '" target="_blank" rel="noopener">Open Fluent SMTP</a> | '
        . '<a href="' . esc_url(firefly_gl_mark_done_link('fluent_smtp_account')) . '">Mark done</a>';
}

// 5) Forms deliver to client (real inbox)
if (!get_theme_mod('go_live_done_forms_delivery')) {
    $smtp_logs = admin_url('admin.php?page=fluent-mail#logs');
    $issues[] = '✅ Confirm <strong>forms are delivered</strong> to the client’s inbox (check logs and do a live test). '
        . '<a href="' . esc_url($smtp_logs) . '" target="_blank" rel="noopener">Check SMTP logs</a> | '
        . '<a href="' . esc_url(firefly_gl_mark_done_link('forms_delivery')) . '">Mark done</a>';
}

// 6) Cloudflare plugin "WordPress" ideal settings
if (!get_theme_mod('go_live_done_cloudflare_wp_mode')) {
    $cf_settings = admin_url('options-general.php?page=cloudflare');
    $issues[] = '☁️ Cloudflare plugin should be set to the ideal <strong>“WordPress”</strong> settings. '
        . '<a href="' . esc_url($cf_settings) . '" target="_blank" rel="noopener">Open Cloudflare settings</a> | '
        . '<a href="' . esc_url(firefly_gl_mark_done_link('cloudflare_wp_mode')) . '">Mark done</a>';
}

// 7) Reading: Discourage search engines = UNticked
if (!get_theme_mod('go_live_done_reading_discourage')) {
    $reading = admin_url('options-reading.php');
    $status  = get_option('blog_public') == '0' ? ' ⚠️ Currently TICKED.' : ' (looks OK).';
    $issues[] = '🔎 Settings → Reading: make sure <strong>“Discourage search engines”</strong> is <strong>UNticked</strong>.' . $status . ' '
        . '<a href="' . esc_url($reading) . '" target="_blank" rel="noopener">Open Reading settings</a> | '
        . '<a href="' . esc_url(firefly_gl_mark_done_link('reading_discourage')) . '">Mark done</a>';
}


// === New go-live issues (manual checks with "Mark done") ===

// UpdraftPlus: Google Drive owner = web@rainbowcreative.co.nz
if (!get_theme_mod('go_live_done_updraft_gdrive_owner')) {
    $updraft_url = admin_url('options-general.php?page=updraftplus');
    $issues[] = '📦 UpdraftPlus: confirm it is connected to Google Drive account '
        . '<strong>web@rainbowcreative.co.nz</strong>. '
        . '<a href="' . esc_url($updraft_url) . '" target="_blank" rel="noopener">Open UpdraftPlus</a> | '
        . '<a href="' . esc_url(firefly_gl_mark_done_link('updraft_gdrive_owner')) . '">Mark done</a>';
}

// UpdraftPlus: automatic backup schedules enabled (files + DB)
if (!get_theme_mod('go_live_done_updraft_auto')) {
    $updraft_url = admin_url('options-general.php?page=updraftplus');
    $issues[] = '⏱️ UpdraftPlus: ensure automatic backup schedules are enabled (files and database). '
        . '<a href="' . esc_url($updraft_url) . '" target="_blank" rel="noopener">Open UpdraftPlus</a> | '
        . '<a href="' . esc_url(firefly_gl_mark_done_link('updraft_auto')) . '">Mark done</a>';
}

// Wordfence: free license activated with web@rainbowcreative.co.nz
if (!get_theme_mod('go_live_done_wordfence_license')) {
    $wf_url = admin_url('admin.php?page=Wordfence');
    $issues[] = '🛡️ Wordfence: activate the FREE license using '
        . '<strong>web@rainbowcreative.co.nz</strong>. '
        . '<a href="' . esc_url($wf_url) . '" target="_blank" rel="noopener">Open Wordfence</a> | '
        . '<a href="' . esc_url(firefly_gl_mark_done_link('wordfence_license')) . '">Mark done</a>';
}

// Wordfence: connected to Rainbow Creative “Wordfence Central”
if (!get_theme_mod('go_live_done_wordfence_central')) {
    $wf_url = admin_url('admin.php?page=Wordfence');
    $issues[] = '🌐 Wordfence: connect this site to the Rainbow Creative '
        . '<strong>Wordfence Central</strong> site. '
        . '<a href="' . esc_url($wf_url) . '" target="_blank" rel="noopener">Open Wordfence</a> | '
        . '<a href="' . esc_url(firefly_gl_mark_done_link('wordfence_central')) . '">Mark done</a>';
}

// Yoast: turn OFF “Show in search results?” for Posts, Categories, Tags, and Author archives
if (!get_theme_mod('go_live_done_yoast_search_off')) {
    $yoast_url = admin_url('admin.php?page=wpseo_page_settings');
    $issues[] = '🔧 Yoast: ensure <strong>“Show in search results?”</strong> is <strong>OFF</strong> for '
        . '<strong>Posts</strong>, <strong>Categories</strong>, <strong>Tags</strong>, and <strong>Author archives</strong>. '
        . '<a href="' . esc_url($yoast_url) . '" target="_blank" rel="noopener">Open Yoast settings</a> | '
        . '<a href="' . esc_url(firefly_gl_mark_done_link('yoast_search_off')) . '">Mark done</a>';
}


}



// ✅ Build output
if (!empty($issues)) {
  //  $stufftodo .= '<div style="padding:15px;background-color:pink;margin-top:10px;border-radius:6px;">';
  //  $stufftodo .= '<div style="padding:10px; background-color:#f99; border-radius:4px; margin-bottom:15px;"><strong>⚠️ Things you need to do!!</strong></div>';

    foreach ($issues as $issue) {
        $stufftodo .= '<div style="margin-bottom:8px; padding:10px; background-color:white; border-radius:4px;">' . $issue . '</div>';
    }

  
   // $stufftodo .= '</div>';
}


if ( ! empty($stufftodo) && is_user_logged_in() ) {
    $u = wp_get_current_user();

    $is_rainbowdev_admin = user_can( $u, 'manage_options' ) && strtolower( $u->user_login ) === 'rainbowdev';
    $is_dr_jeff          = strtolower( trim( $u->user_email ) ) === 'drjeffsimmonds@gmail.com';

    if ( $is_rainbowdev_admin || $is_dr_jeff ) {
        echo '<div style="padding:15px;background-color:pink;margin-top:10px;">';
        echo '<strong>⚠️ Things you need to do:</strong><br><br>';
        echo $stufftodo; // contains intentional HTML
        echo '</div>';
    }
}





echo "</div>";

            // Block picker panel - Changed to use a form instead of AJAX
       echo '
<div id="firefly-add-blocks" class="firefly-admin-3" style="display:none; font-family:Arial,Helvetica; font-size:14px; margin-top:0px;padding-top:0px;">
    <p class="firefly-admin-link"><strong style="font-weight:bold;">What would you like to add?</strong></p>

    <div style="background-color:white;padding:10px;margin-top:10px;"><B style="font-weight:bold;">Text blocks</B>
    

';


//==========================

// 1. No background
echo '
<form method="get" action="' . esc_url(admin_url("admin.php")) . '">
    <input type="hidden" name="page" value="firefly-add-textblock">
    <input type="hidden" name="page_id" value="' . get_the_ID() . '">
    <input type="hidden" name="block_style" value="is-style-plain">
    <p class="firefly-admin-link">
        <a href="#" onclick=\'this.closest("form").submit(); return false;\' style="color:black;text-decoration:none;">
            Add a text block (heading and paragraph) with no background colour
        </a>
    </p>
</form>';

// 2. Colour 1
echo '
<form method="get" action="' . esc_url(admin_url("admin.php")) . '">
    <input type="hidden" name="page" value="firefly-add-textblock">
    <input type="hidden" name="page_id" value="' . get_the_ID() . '">
    <input type="hidden" name="block_style" value="is-style-paragraph-width-coloured-background">
    <p class="firefly-admin-link">
        <a href="#" onclick=\'this.closest("form").submit(); return false;\' style="color:black;text-decoration:none;">
            Add a text block with Colour 1 background
        </a>
    </p>
</form>';

// 3. Colour 2
echo '
<form method="get" action="' . esc_url(admin_url("admin.php")) . '">
    <input type="hidden" name="page" value="firefly-add-textblock">
    <input type="hidden" name="page_id" value="' . get_the_ID() . '">
    <input type="hidden" name="block_style" value="is-style-highlight-section">
    <p class="firefly-admin-link">
        <a href="#" onclick=\'this.closest("form").submit(); return false;\' style="color:black;text-decoration:none;">
            Add a text block with Colour 2 background
        </a>
    </p>
</form>';

//==========================================
// add images and galleries
//==========================================

   echo '</div> <div style="background-color:white;padding:10px;margin-top:10px;"><B style="font-weight:bold;">Images and galleries</B>';



echo '
<form method="post" action="' . esc_url(admin_url("admin-post.php")) . '">
    <input type="hidden" name="action" value="firefly_add_scrolling_gallery">
    <input type="hidden" name="page_id" value="' . get_the_ID() . '">
    <input type="hidden" name="block_style" value="is-style-highlight-section">
    <p class="firefly-admin-link">
        <a href="#" onclick=\'this.closest("form").submit(); return false;\' style="color:black;text-decoration:none;">
            ➕ Add a scrolling banner image (wide and not very tall)
        </a>
    </p>
</form>';



//==========================

            echo '</div></div></div>';
            
            // Add server-side processing for the form submission
            // This function must be defined at the file level, outside of this function
            if (!function_exists('handle_firefly_form_submissions')) {
                function handle_firefly_form_submissions() {
                    if (isset($_POST['firefly_add_textblock']) && current_user_can('manage_options')) {
                        $page_id = isset($_POST['page_id']) ? intval($_POST['page_id']) : 0;
                        $block_content = isset($_POST['block_content']) ? wp_unslash($_POST['block_content']) : '';
                        
                        if ($page_id > 0 && !empty($block_content)) {
                            // Get current content
                            $post = get_post($page_id);
                            $content = $post->post_content;
                            
                            // Append new block to content
                            $updated_content = $content . "\n" . $block_content;
                            
                            // Update the post
                            wp_update_post(array(
                                'ID' => $page_id,
                                'post_content' => $updated_content
                            ));
                            
                            // Redirect back to the same page to see changes
                            wp_safe_redirect(get_permalink($page_id));
                            exit;
                        }
                    }
                }
            }
            
            // Hook the function to init to process before any output
            add_action('init', 'handle_firefly_form_submissions');
            
            ?>
            
            <script>
            document.addEventListener('DOMContentLoaded', function () {
                const deleteLinkWrapper = document.getElementById('delete-links-toggle');
                const deleteLink = document.getElementById('toggle-delete-blocks');
                const adminLinkWrapper = document.getElementById('admin-links-toggle');

                const doneButtonHTML = `
                    <div id="delete-mode-banner" style="
                         position: fixed;
                    top: 32px; /* Adjust for WP admin bar */
                    left: 0;
                    width: 100%;
                    background: red !important;
                    color: white;
                    padding: 10px;
                    text-align: center;
                    z-index: 9999;
                    font-weight: bold;
                    font-size: 16px;">
                        🗑️ You are in "Delete" mode. —
                        <a href="#" id="exit-delete-mode" style="color:white;text-decoration:underline;">Done</a>
                    </div>
                `;

                deleteLink.addEventListener('click', function (e) {
                    e.preventDefault();
                    document.body.classList.remove('show-admin');
                    document.body.classList.add('delete-mode');

                    // Hide admin link
                    if (adminLinkWrapper) adminLinkWrapper.style.display = 'none';

                    // Replace "Delete a block" with "Exit delete mode"
                    deleteLink.innerText = 'Exit delete mode';

                    deleteLink.addEventListener('click', exitDeleteModeOnce);

                    // Show the red banner
                    if (!document.getElementById('delete-mode-banner')) {
                        document.body.insertAdjacentHTML('afterbegin', doneButtonHTML);
                        document.getElementById('exit-delete-mode').addEventListener('click', function (e) {
                            e.preventDefault();
                            exitDeleteMode();
                        });
                    }
                });

                function exitDeleteModeOnce(e) {
                    e.preventDefault();
                    exitDeleteMode();
                }

                function exitDeleteMode() {
                    document.body.classList.remove('delete-mode');

                    // Show admin toggle link again
                    if (adminLinkWrapper) adminLinkWrapper.style.display = 'inline';

                    // Restore delete link text
                    deleteLink.innerText = 'Delete a block on this page';

                    // Remove extra click listener
                    deleteLink.removeEventListener('click', exitDeleteModeOnce);

                    // Remove red banner
                    const banner = document.getElementById('delete-mode-banner');
                    if (banner) banner.remove();
                }
            });
            </script>


            <style>
                .firefly-admin-1,
                .firefly-admin-1-no-margin {
                    display: none;
                }

                body.show-admin .firefly-admin-1,
                body.show-admin .firefly-admin-1-no-margin {
                    display: block;
                }

                bbody.show-admin .wp-block-group:not(.newsletter-container .wp-block-group) {
                    <?php
                    if (get_theme_mod('my_plugin_show_textblock_borders')) {
                       echo "
                       border: 2px solid red;
                        padding: 10px;
                    ";
                    }
                    ?>
                    clear:both;
                    max-width:90%;
                    margin:0 auto;
                    margin-top:10px;
                    margin-bottom:10px;
                }


                /* Default: hide debug icons */
.ff-debug-wrap {
    display: none;
}

/* Show debug details only when admin mode is active */
body.show-admin .ff-debug-wrap {
    display: inline-block;
}

/* Force hide in delete mode ALWAYS */
body.delete-mode .ff-debug-wrap {
    display: none !important;
}


/* Default: hide debug icons */
.ff-debug-wrap {
    display: none;
}

/* Show debug details only when admin mode is active */
body.show-admin .ff-debug-wrap {
    display: inline-block;
}

/* Force hide in delete mode ALWAYS */
body.delete-mode .ff-debug-wrap {
    display: none !important;
}



            </style>
                
<script>
document.addEventListener('DOMContentLoaded', function () {

    const toggleLink = document.getElementById('toggle-admin-links');
    const adminClass = 'show-admin';

    if (!toggleLink) {
        return; // safety
    }

    function updateLinkText() {
        const isAdmin = document.body.classList.contains(adminClass);
        toggleLink.textContent = isAdmin ? 'Hide admin links' : 'Show admin links';
    }

    function updateDisplayState() {
        const isAdmin  = document.body.classList.contains(adminClass);
        const isDelete = document.body.classList.contains('delete-mode');

        const debugEls = document.querySelectorAll('.ff-debug-wrap');
        const adminEls = document.querySelectorAll('.admin-links');

        // Debug icons
        debugEls.forEach(el => {
            if (isDelete) {
                el.style.display = 'none';
            } else {
                el.style.display = isAdmin ? '' : 'none';
            }
        });

        // Admin links (not debug icons)
        adminEls.forEach(el => {
            if (isDelete) {
                el.style.display = 'none';
            } else {
                el.style.display = isAdmin ? '' : 'none';
            }
        });

        // Also keep the toggle label in sync
        updateLinkText();
    }

    // Restore state on page load from localStorage
    if (localStorage.getItem('showAdminLinks') === '1') {
        document.body.classList.add(adminClass);
    }

    // Initial UI setup
    updateDisplayState();

    // Toggle admin mode
    toggleLink.addEventListener('click', function (e) {
        e.preventDefault();
        const isVisible = document.body.classList.toggle(adminClass);
        localStorage.setItem('showAdminLinks', isVisible ? '1' : '0');
        updateDisplayState();
    });

    // Listen for delete mode changes from your other script
    document.addEventListener('deleteModeChange', updateDisplayState);
});
</script>


      
            <script>
                document.addEventListener('DOMContentLoaded', function () {
                    const rerunLink = document.getElementById('rerun-setup-link');
                    if (rerunLink) {
                        rerunLink.addEventListener('click', function (e) {
                            const confirmReset = confirm("⚠️ Are you sure you want to re-run setup?\n\nThis will delete the current settings!\nThis cannot be undone!");
                            if (!confirmReset) {
                                e.preventDefault();
                            }
                        });
                    }
                });
            </script>
            <?php
        }
    }
}



