<?php
/**
 * Firefly Admin Customizer Panel
 * Appears in the Appearance → Customize menu
 */

function firefly_register_admin_customizer($wp_customize) {
    // Add a new panel at the bottom
    $wp_customize->add_panel('firefly_admin_panel', [
        'title'       => __('Firefly Admin...', 'firefly'),
        'priority'    => 999, // Appear at the bottom
    ]);

    // Add a section inside that panel
    $wp_customize->add_section('firefly_admin_settings_section', [
        'title'    => __('Show/Hide admin features', 'firefly'),
        'panel'    => 'firefly_admin_panel',
        'priority' => 1,
    ]);



    // --------------------------------------------------
// Blog / Posts behaviour
// --------------------------------------------------

// Show posts (blog)
$wp_customize->add_setting('my_plugin_show_posts', [
    'default'           => 'no',
    'sanitize_callback' => function ($val) {
        return in_array($val, ['yes', 'no'], true) ? $val : 'no';
    },
]);

$wp_customize->add_control('my_plugin_show_posts', [
    'type'     => 'radio',
    'section'  => 'firefly_admin_settings_section',
    'label'    => __('Show posts', 'firefly'),
    'choices'  => [
        'no'  => __('No (posts redirect to home page)', 'firefly'),
        'yes' => __('Yes (has a blog page)', 'firefly'),
    ],
]);

// Show featured images on post page
$wp_customize->add_setting('my_plugin_show_post_thumbnails', [
    'default'           => 'no',
    'sanitize_callback' => function ($val) {
        return in_array($val, ['yes', 'no'], true) ? $val : 'no';
    },
]);

$wp_customize->add_control('my_plugin_show_post_thumbnails', [
    'type'     => 'radio',
    'section'  => 'firefly_admin_settings_section',
    'label'    => __('Show featured images on post page', 'firefly'),
    'choices'  => [
        'no'  => __('No (featured images are hidden)', 'firefly'),
        'yes' => __('Yes', 'firefly'),
    ],
]);



    if (1==2) {
        // Add a new section: Change log and bug report
        $wp_customize->add_section('firefly_changelog_section', [
            'title'    => __('Change log and bug report', 'firefly'),
            'panel'    => 'firefly_admin_panel',
            'priority' => 99,
        ]);

        $wp_customize->add_setting('firefly_changelog_iframe', [
            'sanitize_callback' => '__return_null',
        ]);

        $rand = rand(9999,9999999);
        $wp_customize->add_control(new WP_Customize_Control(
            $wp_customize,
            'firefly_changelog_iframe',
            [
                'section'     => 'firefly_changelog_section',
                'settings'    => 'firefly_changelog_iframe',
                'label'       => '',
                'description' => '<div style="margin-top:10px;">
                    <iframe src="https://rainbowdigital.co.nz/firefly/firefly-WP-theme-changelog.php?x=' . $rand . '" width="100%" height="600" style="border:1px solid #ccc;"></iframe>
                </div>',
                'type'        => 'hidden',
            ]
        ));
    }

    // List of admin options
    $admin_options = [
        'show_page_admin_links'     => 'Show page admin links',
        'show_story_admin_links'    => 'Show story admin links',
        'show_picture_admin_links'  => 'Show picture admin links',
        'show_document_admin_links' => 'Show document admin links',
        'show_event_admin_links'    => 'Show event admin links',
        'show_form_admin_links'     => 'Show form admin links',
        'show_product_admin_links'  => 'Show product admin links',
        'show_gallery_admin_links'  => 'Show gallery admin links',
    ];

    foreach ($admin_options as $key => $label) {
        $setting_id = "my_plugin_{$key}";

        $wp_customize->add_setting($setting_id, [
            'default'           => false,
            'sanitize_callback' => 'wp_validate_boolean',
        ]);

        $wp_customize->add_control($setting_id, [
            'type'     => 'checkbox',
            'section'  => 'firefly_admin_settings_section',
            'label'    => __($label, 'firefly'),
        ]);
    }

    // Add "Site is set up" toggle
    $wp_customize->add_setting('my_plugin_setup_complete', [
        'default'           => false,
        'sanitize_callback' => 'wp_validate_boolean',
    ]);

    $wp_customize->add_control('my_plugin_setup_complete', [
        'type'     => 'checkbox',
        'section'  => 'firefly_admin_settings_section',
        'label'    => __('Site is set up', 'firefly'),
    ]);

    // Add "Do not connect to ManageWP" toggle
    $wp_customize->add_setting('my_plugin_do_not_connect_to_manageWP', [
        'default'           => false,
        'sanitize_callback' => 'wp_validate_boolean',
    ]);

    $wp_customize->add_control('my_plugin_do_not_connect_to_manageWP', [
        'type'     => 'checkbox',
        'section'  => 'firefly_admin_settings_section',
        'label'    => __('Do not connect to ManageWP', 'firefly'),
    ]);

    // Add extra admin toggles
    $wp_customize->add_setting('my_plugin_delete_mode', [
        'default'           => false,
        'sanitize_callback' => 'wp_validate_boolean',
    ]);

    $wp_customize->add_control('my_plugin_delete_mode', [
        'type'     => 'checkbox',
        'section'  => 'firefly_admin_settings_section',
        'label'    => __('Enable delete mode', 'firefly'),
    ]);

    $wp_customize->add_setting('my_plugin_add_textblock', [
        'default'           => false,
        'sanitize_callback' => 'wp_validate_boolean',
    ]);

    $wp_customize->add_control('my_plugin_add_textblock', [
        'type'     => 'checkbox',
        'section'  => 'firefly_admin_settings_section',
        'label'    => __('Enable add textblock mode', 'firefly'),
    ]);

    // Add "Show red border around textblocks" toggle
    $wp_customize->add_setting('my_plugin_show_textblock_borders', [
        'default'           => false,
        'sanitize_callback' => 'wp_validate_boolean',
    ]);

    $wp_customize->add_control('my_plugin_show_textblock_borders', [
        'type'     => 'checkbox',
        'section'  => 'firefly_admin_settings_section',
        'label'    => __('Show red border around textblocks', 'firefly'),
    ]);

    $wp_customize->add_setting('my_plugin_theme_update_access', [
        'default'           => 'jeff', // 'jeff' | 'jeff_rainbowdev' | 'anyone'
        'sanitize_callback' => 'ff_sanitize_theme_update_access',
    ]);

    $wp_customize->add_control('my_plugin_theme_update_access', [
        'type'     => 'radio',
        'section'  => 'firefly_admin_settings_section',
        'label'    => __('Who can update the FireflyWP theme', 'firefly'),
        'choices'  => [
            'jeff'            => __('Only Jeff', 'firefly'),
            'jeff_rainbowdev' => __('Jeff and rainbowdev', 'firefly'),
            'anyone'          => __('Anyone', 'firefly'),
        ],
    ]);

    $wp_customize->add_setting('my_plugin_show_all_settings_note', [
        'sanitize_callback' => '__return_null',
    ]);

    $wp_customize->add_control(new WP_Customize_Control(
        $wp_customize,
        'my_plugin_show_all_settings_note',
        [
            'section'     => 'firefly_admin_settings_section',
            'settings'    => 'my_plugin_show_all_settings_note',
            'label'       => '',
            'description' => '<a href="/?show_all_settings=1" target="_blank" style="display:inline-block;margin-top:10px;">Show all settings</a>',
            'type'        => 'hidden',
        ]
    ));

    // Add "This site is live" toggle
    $wp_customize->add_setting('this_site_is_live', [
        'default'           => false,
        'sanitize_callback' => 'wp_validate_boolean',
    ]);

    $wp_customize->add_control('this_site_is_live', [
        'type'     => 'checkbox',
        'section'  => 'firefly_admin_settings_section',
        'label'    => __('This site is live', 'firefly'),
    ]);

    // Add a new section: Modules on this site
    $wp_customize->add_section('firefly_modules_section', [
        'title'    => __('Modules on this site', 'firefly'),
        'panel'    => 'firefly_admin_panel',
        'priority' => 2,
    ]);

    $modules = [
        'has_menu'                => ['label' => 'Menu',                 'default' => true],
        'module_gallery'          => ['label' => 'Gallery',              'default' => true],
        'module_events'           => ['label' => 'Events',               'default' => true],
        'module_event_booking'    => ['label' => 'Events booking',       'default' => false],
        'module_documents'        => ['label' => 'Documents',            'default' => true],
        'module_fluentform_pro'   => ['label' => 'FluentForm Pro',       'default' => false],
        'module_products'         => ['label' => 'Products',             'default' => false],
        'module_woocommerce'      => ['label' => 'WooCommerce',          'default' => false],
        'module_newsletter'       => ['label' => 'Newsletter',           'default' => false],
        'module_members_only'     => ['label' => 'Members only pages',   'default' => false],
        'module_site_within_site' => ['label' => 'Site within a site',   'default' => false],
        'has_background_images'   => ['label' => 'Background images',    'default' => false],
        'has_things'              => ['label' => 'Things module',        'default' => false],
    ];

    foreach ($modules as $id => $info) {
        $setting_id = "my_plugin_{$id}";

        $wp_customize->add_setting($setting_id, [
            'default'           => $info['default'],
            'sanitize_callback' => 'wp_validate_boolean',
        ]);

        $wp_customize->add_control($setting_id, [
            'type'    => 'checkbox',
            'section' => 'firefly_modules_section',
            'label'   => __($info['label'], 'firefly'),
        ]);
    }
}
add_action('customize_register', 'firefly_register_admin_customizer');


// Sanitize radio choice
function ff_sanitize_theme_update_access( $val ) {
    $allowed = ['jeff', 'jeff_rainbowdev', 'anyone'];
    return in_array($val, $allowed, true) ? $val : 'jeff';
}

// Who is allowed to access the Updates page (Dashboard → Updates)
function ff_user_can_update_firefly_theme(): bool {
    if ( ! is_user_logged_in() ) return false;

    $mode  = get_theme_mod('my_plugin_theme_update_access', 'jeff');
    $user  = wp_get_current_user();
    $email = strtolower(trim($user->user_email));
    $login = strtolower($user->user_login);

    // Jeff’s login email
    $is_jeff       = ($email === 'drjeffsimmonds@gmail.com');
    $is_rainbowdev = ($login === 'rainbowdev');

    switch ($mode) {
        case 'anyone':
            return true;
        case 'jeff_rainbowdev':
            return ($is_jeff || $is_rainbowdev);
        case 'jeff':
        default:
            return $is_jeff;
    }
}

// Hide the Updates page from disallowed users
add_action('admin_menu', function () {
    if ( ! ff_user_can_update_firefly_theme() ) {
        // Remove "Updates" under Dashboard
        remove_submenu_page('index.php', 'update-core.php');
    }
}, 1000);

// Block direct access to update-core.php if disallowed
add_action('admin_init', function () {
    if ( ! ff_user_can_update_firefly_theme() ) {
        global $pagenow;
        if ( $pagenow === 'update-core.php' ) {
            wp_safe_redirect( admin_url('index.php') );
            exit;
        }
    }
});


/**
 * ==========================================================
 *  Appearance → Site Templates
 *  - Shows 400x206 thumbnails (same basename as .txt in same folder)
 *  - Clicking a thumbnail prompts "Are you sure?"
 *  - If yes: applies template immediately and redirects to home page
 * ==========================================================
 */

// Add submenu under Appearance
add_action('admin_menu', function () {
    add_theme_page(
        __('Site Templates', 'firefly'),
        __('Site Templates', 'firefly'),
        'manage_options',
        'firefly-site-templates',
        'firefly_render_site_templates_page'
    );
}, 1001);

/**
 * Return absolute path to the site-templates folder in the active theme.
 */
function firefly_site_templates_dir(): string {
    return trailingslashit(get_stylesheet_directory()) . 'site-templates';
}

/**
 * Return web URL to the site-templates folder in the active theme.
 */
function firefly_site_templates_url(): string {
    return trailingslashit(get_stylesheet_directory_uri()) . 'site-templates';
}

/**
 * Find a thumbnail for a given .txt file.
 * Looks for same basename with .png/.jpg/.jpeg/.gif (in that order)
 * Returns URL string or empty string.
 */
function firefly_site_template_thumbnail_url(string $txtFile): string {
    $base = pathinfo($txtFile, PATHINFO_FILENAME);

    $dir = firefly_site_templates_dir();
    $url = firefly_site_templates_url();

    $candidates = [
        $base . '.png',
        $base . '.jpg',
        $base . '.jpeg',
        $base . '.gif',
    ];

    foreach ($candidates as $name) {
        $path = trailingslashit($dir) . $name;
        if (is_file($path)) {
            return trailingslashit($url) . rawurlencode($name);
        }
    }

    return '';
}

/**
 * List .txt template files (basename only), sorted A→Z.
 */
function firefly_list_site_template_files(): array {
    $dir = firefly_site_templates_dir();
    if (!is_dir($dir) || !is_readable($dir)) return [];

    $items = scandir($dir);
    if (!is_array($items)) return [];

    $out = [];
    foreach ($items as $item) {
        if ($item === '.' || $item === '..') continue;

        $path = trailingslashit($dir) . $item;
        if (!is_file($path)) continue;

        if (strtolower(pathinfo($path, PATHINFO_EXTENSION)) !== 'txt') continue;

        if (!is_readable($path)) continue;

        $out[] = $item;
    }

    sort($out, SORT_NATURAL | SORT_FLAG_CASE);
    return $out;
}

/**
 * Read a template file safely (by basename only).
 */
function firefly_read_site_template_file(string $basename): string {
    $basename = basename($basename); // prevents ../
    $dir      = firefly_site_templates_dir();
    $path     = trailingslashit($dir) . $basename;

    if (!is_file($path)) return '';
    if (strtolower(pathinfo($path, PATHINFO_EXTENSION)) !== 'txt') return '';
    if (!is_readable($path)) return '';

    $contents = file_get_contents($path);
    return is_string($contents) ? $contents : '';
}

/**
 * Parse your " 'key' => value, " style text into an associative array.
 */
function firefly_parse_template_text(string $raw): array {
    $settings = [];

    $pattern = "/'([^']+)'\\s*=>\\s*(.*?)(?:,\\s*(?:\\r?\\n|\\r)|,\\s*$|\\s*$)/m";

    if (!preg_match_all($pattern, $raw, $matches, PREG_SET_ORDER)) {
        return $settings;
    }

    foreach ($matches as $m) {
        $key = trim((string)$m[1]);
        if ($key === '' || ctype_digit($key)) continue;

        $valRaw = trim((string)$m[2]);
        $valRaw = preg_replace('/,\\s*$/', '', $valRaw);
        $valRaw = trim((string)$valRaw);

        $val = null;

        if (preg_match("/^'(.*)'$/s", $valRaw, $vm)) {
            $val = str_replace("\\'", "'", (string)$vm[1]);
        } elseif ($valRaw === 'true') {
            $val = true;
        } elseif ($valRaw === 'false') {
            $val = false;
        } elseif ($valRaw === 'null') {
            $val = null;
        } elseif (is_numeric($valRaw)) {
            $val = (strpos($valRaw, '.') !== false) ? (float)$valRaw : (int)$valRaw;
        } else {
            continue;
        }

        $settings[$key] = $val;
    }

    return $settings;
}

/**
 * Apply settings to the site (theme mods).
 * Returns [applied_count, skipped_count, skipped_keys[]]
 */
function firefly_apply_template_settings(array $settings): array {
    $applied = 0;
    $skipped = 0;
    $skipped_keys = [];

    // 🔴 Explicit content / identity keys to exclude
    $excluded_keys = [
        'firefly_banner_text',
        'firefly_logo_other_text',
        'firefly_footer_heading_3',
        'firefly_footer_text_3',
        'firefly_footer_heading_5',
        'firefly_footer_text_5',
        'firefly_logo_icon_1',
        'firefly_logo_icon_1_link',
        'firefly_logo_icon_2',
        'firefly_logo_icon_2_link',
        'firefly_logo_icon_3',
        'firefly_logo_icon_3_link',
        'firefly_logo_icon_4',
        'firefly_logo_icon_4_link',
        'firefly_logo_icon_height',
    ];

    foreach ($settings as $key => $value) {

        if (!preg_match('/^[A-Za-z0-9_\-]+$/', (string)$key)) {
            $skipped++;
            $skipped_keys[] = $key;
            continue;
        }

        if (in_array($key, $excluded_keys, true)) {
            $skipped++;
            $skipped_keys[] = $key;
            continue;
        }

        // Skip image-based values (URLs or filenames)
        if (is_string($value)) {
            $lower = strtolower($value);
            if (
                str_contains($lower, '.png') ||
                str_contains($lower, '.jpg') ||
                str_contains($lower, '.jpeg') ||
                str_contains($lower, '.gif')
            ) {
                $skipped++;
                $skipped_keys[] = $key;
                continue;
            }
        }

        set_theme_mod($key, $value);
        $applied++;
    }

    return [$applied, $skipped, $skipped_keys];
}


/**
 * Handle clicking a template (GET with nonce) → apply → redirect home
 */
add_action('admin_init', function () {
    if (!is_admin()) return;
    if (!current_user_can('manage_options')) return;

    if (!isset($_GET['page']) || $_GET['page'] !== 'firefly-site-templates') return;
    if (!isset($_GET['apply_template'])) return;

    check_admin_referer('firefly_apply_template_link');

    $file = sanitize_text_field(wp_unslash($_GET['apply_template']));
    $file = basename($file);

    $raw = firefly_read_site_template_file($file);
    if ($raw !== '') {
        $settings = firefly_parse_template_text($raw);
        if (!empty($settings)) {
            firefly_apply_template_settings($settings);
        }
    }

    // Redirect to home page
    wp_safe_redirect(home_url('/'));
    exit;
});


/**
 * Render admin page (thumbnails only; no code preview)
 */
function firefly_render_site_templates_page() {
    if (!current_user_can('manage_options')) {
        wp_die('No permission.');
    }

    $files = firefly_list_site_template_files();

    echo '<div class="wrap">';
    echo '<h1>' . esc_html__('Site Templates', 'firefly') . '</h1>';

    if (empty($files)) {
        echo '<div class="notice notice-warning"><p>';
        echo esc_html__('No .txt templates found. Create files in /site-templates/ inside the active theme.', 'firefly');
        echo '</p></div>';
        echo '</div>';
        return;
    }

    echo '<p style="color:#555; max-width:900px;">';
    echo esc_html__('Click a template thumbnail to apply it. You will be asked to confirm.', 'firefly');
    echo '</p>';

    echo '<div style="display:flex; flex-wrap:wrap; gap:16px;">';

    foreach ($files as $f) {
        $thumb = firefly_site_template_thumbnail_url($f);

        // Apply link (nonce protected)
        $apply_url = add_query_arg(
            [
                'page'           => 'firefly-site-templates',
                'apply_template' => rawurlencode($f),
                '_wpnonce'       => wp_create_nonce('firefly_apply_template_link'),
            ],
            admin_url('themes.php')
        );

        $title = pathinfo($f, PATHINFO_FILENAME);

        echo '<a href="' . esc_url($apply_url) . '" ';
        echo 'onclick="return confirm(\'Apply this site template: ' . esc_js($title) . ' ?\');" ';
        echo 'style="display:block; width:400px; text-decoration:none; background:#fff; border:1px solid #ccd0d4; padding:10px;">';

        if ($thumb !== '') {
            echo '<img src="' . esc_url($thumb) . '" alt="' . esc_attr($title) . '" ';
            echo 'style="width:400px; height:206px; display:block; object-fit:cover; border:1px solid #e5e5e5;">';
        } else {
            echo '<div style="width:400px; height:206px; display:flex; align-items:center; justify-content:center; ';
            echo 'border:1px dashed #bbb; background:#fafafa; color:#777;">';
            echo esc_html__('No thumbnail found', 'firefly');
            echo '</div>';
        }

        echo '<div style="margin-top:8px; font-weight:600; color:#111;">' . esc_html($title) . '</div>';
        echo '</a>';
    }

    echo '</div>';
    echo '</div>'; // wrap
}
