<?php

/**
 * Mark whether the logged-in user is Jeff.
 * Put this in functions.php or a small helper plugin.
 */
add_action( 'init', function () {
	// Always declare the variable first so it exists everywhere.
	global $thisisjeff;
	$thisisjeff = false;        // default

	$current_user = wp_get_current_user();
	if ( ! $current_user->exists() ) {
		return;                 // nobody logged in
	}

	$username  = $current_user->user_login;
	$useremail = $current_user->user_email;

	if ( $username === 'rainbowdev' || $useremail === 'drjeffsimmonds@gmail.com' ) {
		$thisisjeff = true;
	}
} );


if (
    current_user_can('manage_options') &&
    isset($_POST['submit_new_images']) &&
    wp_verify_nonce($_POST['firefly_gallery_nonce'] ?? '', 'firefly_gallery_nonce')
) {
    $post_id = absint($_POST['firefly_post_id'] ?? 0);


    $user_id = get_current_user_id();



    if ($post_id && !empty($_FILES['thing_new_images']['name'][0])) {
        $gallery = get_post_meta($post_id, 'thing_gallery', true);
        if (!is_array($gallery)) $gallery = [];

        require_once ABSPATH . 'wp-admin/includes/file.php';
        require_once ABSPATH . 'wp-admin/includes/image.php';
        require_once ABSPATH . 'wp-admin/includes/media.php';

       foreach ( $_FILES['thing_new_images']['name'] as $index => $name ) {

	/* skip files that failed to upload */
	if ( $_FILES['thing_new_images']['error'][ $index ] !== UPLOAD_ERR_OK ) {
		continue;
	}

	$file_array = [
		'name'     => $_FILES['thing_new_images']['name'][ $index ],
		'type'     => $_FILES['thing_new_images']['type'][ $index ],
		'tmp_name' => $_FILES['thing_new_images']['tmp_name'][ $index ],
		'error'    => $_FILES['thing_new_images']['error'][ $index ],
		'size'     => $_FILES['thing_new_images']['size'][ $index ],
	];

	$attachment_id = media_handle_sideload( $file_array, $post_id );

	if ( ! is_wp_error( $attachment_id ) ) {

		/* 1️⃣ add to gallery list */
		$gallery[] = $attachment_id;

		/* 2️⃣ build ALT text: "(ref) Post Title" or just "Post Title" */
		$ref = trim( get_post_meta( $post_id, 'ref', true ) );
		$alt = trim( ( $ref ? $ref . ' ' : '' ) . get_the_title( $post_id ) );

		if ( $alt !== '' ) {
			update_post_meta(
				$attachment_id,
				'_wp_attachment_image_alt',
				$alt
			);
		}

		/* 3️⃣ (optional) inline debug – view-source to see it */
		echo "\n<!-- firefly-dbg NEW image #{$attachment_id} ALT='{$alt}' -->\n";
	}
}



        // 7.5 Reset all subcategory checkboxes to 0 if not explicitly checked
$slug = get_post_field('post_name', $post_id);
$subcats_raw = get_theme_mod("firefly_thing_subcategories_$slug", '');
$subcategories = array_filter(array_map('trim', explode("\n", $subcats_raw)));

foreach ($subcategories as $subcat) {
    $subcat_key = sanitize_title($subcat);
    if (!isset($_POST['thing_meta'][$subcat_key])) {
        update_post_meta($post_id, $subcat_key, 0);
    }
}


        update_post_meta($post_id, 'thing_gallery', $gallery);
        wp_redirect(add_query_arg(['edit_thng_pictures' => $post_id], get_permalink()));
        exit;
    }
}



add_action('customize_register', function ($wp_customize) {
    if (class_exists('WP_Customize_Control')) {
        class Firefly_Radio_Colour_Control_Thing extends WP_Customize_Control {
            public $type = 'radio';
            public $choices = [];

            public function render_content() {
                if (empty($this->choices)) return;

                echo '<span class="customize-control-title">' . esc_html($this->label) . '</span>';
                foreach ($this->choices as $value => $args) {
                    $id = esc_attr("{$this->id}_$value");
                    $checked = checked($this->value(), $value, false);
                    echo "<label style='display:inline-block;margin-right:10px'>";
                    echo "<input type='radio' name='{$this->id}' value='" . esc_attr($value) . "' $checked />";
                    echo "<span style='display:inline-block;width:20px;height:20px;background:{$args['color']};border:1px solid #ccc;margin-left:5px'></span>";
                    echo "</label>";
                }
            }
        }
    }

    // === Create the Panel
    $wp_customize->add_panel('firefly_things_panel', [
        'title'       => __('Firefly Things', 'firefly'),
        'priority'    => 60,
        'description' => __('Manage your Firefly Things setup.', 'firefly'),
    ]);

    // === Main "Things List" Section
    $wp_customize->add_section('firefly_things_list_section', [
        'title'    => __('Things list', 'firefly'),
        'panel'    => 'firefly_things_panel',
        'priority' => 10,
    ]);

    $wp_customize->add_setting('firefly_things_list_textarea', [
        'default'           => '',
        'sanitize_callback' => 'sanitize_textarea_field',
    ]);

    $wp_customize->add_control('firefly_things_list_textarea_control', [
        'label'       => __("What are your things?", 'firefly'),
        'section'     => 'firefly_things_list_section',
        'settings'    => 'firefly_things_list_textarea',
        'type'        => 'textarea',
        'description' => __('Put one item per line.', 'firefly'),
    ]);

    // === Define shared colour choices
    $colour_choices = [
        'colour1' => ['label' => 'Colour 1', 'color' => get_theme_mod('firefly_colour_1', '#0b3d32')],
        'colour2' => ['label' => 'Colour 2', 'color' => get_theme_mod('firefly_colour_2', '#65b32e')],
        'colour3' => ['label' => 'Colour 3', 'color' => get_theme_mod('firefly_colour_3', '#d3f5d1')],
        'colour4' => ['label' => 'Colour 4', 'color' => get_theme_mod('firefly_colour_4', '#e4f1ce')],
        'black'   => ['label' => 'Black', 'color' => '#000'],
        'white'   => ['label' => 'White', 'color' => '#fff'],
    ];

    $font_sizes = [];
    for ($fs = 10; $fs <= 36; $fs++) {
        $font_sizes["{$fs}px"] = "{$fs}px";
    }

    // === Get list of "thing types"
    $theme = get_option('stylesheet');
    $mods = get_option("theme_mods_$theme");
    $raw = isset($mods['firefly_things_list_textarea']) ? $mods['firefly_things_list_textarea'] : '';
    $categories = array_filter(array_map('trim', explode("\n", $raw)));

    // === Get shared field names
    $raw_fields = get_theme_mod('firefly_thing_fields', '');
    $fields = array_filter(array_map('trim', explode("\n", $raw_fields)));

    foreach ($categories as $i => $label) {
        $slug = sanitize_title($label);
        $section_id = "firefly_things_section_$slug";

        $wp_customize->add_section($section_id, [
            'title'    => $label,
            'panel'    => 'firefly_things_panel',
            'priority' => 30 + $i,
        ]);


        $wp_customize->add_setting("firefly_thing_subcategories_$slug", [
    'default'           => '',
    'sanitize_callback' => 'sanitize_textarea_field',
]);

$wp_customize->add_control("firefly_thing_subcategories_{$slug}_control", [
    'label'       => __("Sub-categories (optional)", 'firefly'),
    'section'     => $section_id,
    'settings'    => "firefly_thing_subcategories_$slug",
    'type'        => 'textarea',
    'description' => __('Put each sub-category on a new line.', 'firefly'),
]);


        $wp_customize->add_setting("firefly_thing_label_singular_$slug", [
            'default'           => '',
            'sanitize_callback' => 'sanitize_text_field',
        ]);

        $wp_customize->add_control("firefly_thing_label_singular_{$slug}_control", [
            'label'       => __("Ten $slug; one:", 'firefly'),
            'section'     => $section_id,
            'settings'    => "firefly_thing_label_singular_$slug",
            'type'        => 'text',
        ]); 

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

        $wp_customize->add_control("firefly_thing_link_to_page_{$slug}_control", [
            'label'    => __("Link each " . (get_theme_mod("firefly_thing_label_singular_$slug", 'thing')) . " to its own page", 'firefly'),
            'section'  => $section_id,
            'settings' => "firefly_thing_link_to_page_$slug",
            'type'     => 'checkbox',
        ]);



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

        $wp_customize->add_control("firefly_thing_can_be_sold_{$slug}_control", [
            'label'    => __("Allow a " . (get_theme_mod("firefly_thing_label_singular_$slug", 'thing')) . " to be 'SOLD'" . (get_theme_mod("firefly_thing_label_singular_$slug", 'thing')) . " to its own page", 'firefly'),
            'section'  => $section_id,
            'settings' => "firefly_thing_can_be_sold_$slug",
            'type'     => 'checkbox',
        ]);



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

        $wp_customize->add_control("firefly_thing_can_be_sold_out_{$slug}_control", [
            'label'    => __("Allow a " . (get_theme_mod("firefly_thing_label_singular_$slug", 'thing')) . " to be 'SOLD OUT'" , 'firefly'),
            'section'  => $section_id,
            'settings' => "firefly_thing_can_be_sold_out_$slug",
            'type'     => 'checkbox',
        ]);




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

        $wp_customize->add_control("firefly_thing_print_page_icon_{$slug}_control", [
            'label'    => __("Show a 'Print' icon with a print-friendly page'", 'firefly'),
            'section'  => $section_id,
            'settings' => "firefly_thing_print_page_icon_$slug",
            'type'     => 'checkbox',
        ]);
        

  
        $wp_customize->add_setting("firefly_thing_image_display_mode_$slug", [
    'default'           => 'single',
    'sanitize_callback' => function($value) {
        return in_array($value, ['single', 'gallery']) ? $value : 'single';
    },
]);

$wp_customize->add_control("firefly_thing_image_display_mode_{$slug}_control", [
    'label'    => __("On pages that display all " . (get_theme_mod("firefly_thing_label_plural_$slug", 'things')) . ", show:", 'firefly'),
    'section'  => $section_id,
    'settings' => "firefly_thing_image_display_mode_$slug",
    'type'     => 'radio',
    'choices'  => [
        'single'  => __('One picture', 'firefly'),
        'gallery' => __('A rotating picture gallery', 'firefly'),
    ],
]);



        // === Custom fields 1 (List view)
        $wp_customize->add_setting("firefly_thing_fields_list_$slug", [
            'default' => '',
            'sanitize_callback' => 'sanitize_textarea_field',
        ]);

        $wp_customize->add_control("firefly_thing_fields_list_{$slug}_control", [
            'label'       => __("Custom fields 1 (appearing on list of all $label)", 'firefly'),
            'section'     => $section_id,
            'settings'    => "firefly_thing_fields_list_$slug",
            'type'        => 'textarea',
            'description' => __('Put each field name on a new line. Example: price⏎colour⏎size', 'firefly'),
        ]);

        // === Custom fields 2 (Detail view)
        $wp_customize->add_setting("firefly_thing_fields_detail_$slug", [
            'default' => '',
            'sanitize_callback' => 'sanitize_textarea_field',
        ]);

        $wp_customize->add_control("firefly_thing_fields_detail_{$slug}_control", [
            'label'       => __("Custom fields 2 (appear when you view individual $label)", 'firefly'),
            'section'     => $section_id,
            'settings'    => "firefly_thing_fields_detail_$slug",
            'type'        => 'textarea',
            'description' => __('Put each field name on a new line. Example: year⏎berth⏎features', 'firefly'),
        ]);

        // === Custom fields 3 (checkboxes)
        $wp_customize->add_setting("firefly_thing_fields_checkboxes_$slug", [
            'default' => '',
            'sanitize_callback' => 'sanitize_textarea_field',
        ]);

        $wp_customize->add_control("firefly_thing_fields_checkboxes_{$slug}_control", [
            'label'       => __("Custom fields 3 (yes/no checkboxes for $label)", 'firefly'),
            'section'     => $section_id,
            'settings'    => "firefly_thing_fields_checkboxes_$slug",
            'type'        => 'textarea',
            'description' => __('These are yes/no fields (eg "For sale", "Has reversing camera", "Plays weddings"', 'firefly'),
        ]);

        // === Layout
        $wp_customize->add_setting("firefly_thing_layout_$slug", [
            'default' => 'panels-below',
            'sanitize_callback' => function ($input) {
                return in_array($input, ['panels-below', 'panels-right', 'list', 'pic-only']) ? $input : 'panels-below';
            },
        ]);
        $wp_customize->add_control("firefly_thing_layout_{$slug}_control", [
            'label'    => __('Layout style', 'firefly'),
            'section'  => $section_id,
            'settings' => "firefly_thing_layout_$slug",
            'type'     => 'radio',
            'choices'  => [
                'panels-below' => __('Panels (text below image)', 'firefly'),
                'panels-right' => __('Panels (text to right)', 'firefly'),
                'list'         => __('List view', 'firefly'),
                'pic-only'     => __('Picture only (no text)', 'firefly'),
            ],
        ]);

        // === Font size
        $wp_customize->add_setting("firefly_thing_heading_size_$slug", [
            'default' => '16px',
            'sanitize_callback' => 'sanitize_text_field',
        ]);
        $wp_customize->add_control("firefly_thing_heading_size_{$slug}_control", [
            'label'    => __('Font size of heading', 'firefly'),
            'section'  => $section_id,
            'settings' => "firefly_thing_heading_size_$slug",
            'type'     => 'select',
            'choices'  => $font_sizes,
        ]);

        // === Font weight (headings only)
        $wp_customize->add_setting("firefly_thing_heading_weight_$slug", [
            'default'           => 'normal',
            'transport'         => 'refresh',
            'sanitize_callback' => function($input) {
                return in_array($input, ['normal', 'bold']) ? $input : 'normal';
            },
        ]);
        $wp_customize->add_control("firefly_thing_heading_weight_{$slug}_control", [
            'label'    => __('Font weight of heading', 'firefly'),
            'section'  => $section_id,
            'settings' => "firefly_thing_heading_weight_$slug",
            'type'     => 'radio',
            'choices'  => [
                'normal' => __('Plain', 'firefly'),
                'bold'   => __('Bold', 'firefly'),
            ],
        ]);

        $wp_customize->add_setting("firefly_thing_description_font_size_$slug", [
            'default' => '16px',
            'sanitize_callback' => 'sanitize_text_field',
        ]);
        $wp_customize->add_control("firefly_thing_description_font_size_{$slug}_control", [
            'label'    => __('Font size of description', 'firefly'),
            'section'  => $section_id,
            'settings' => "firefly_thing_description_font_size_$slug",
            'type'     => 'select',
            'choices'  => $font_sizes,
        ]);

        $wp_customize->add_setting("firefly_thing_custom_fields_font_size_$slug", [
            'default' => '16px',
            'sanitize_callback' => 'sanitize_text_field',
        ]);
        $wp_customize->add_control("firefly_thing_custom_fields_font_size_{$slug}_control", [
            'label'    => __('Font size of custom fields', 'firefly'),
            'section'  => $section_id,
            'settings' => "firefly_thing_custom_fields_font_size_$slug",
            'type'     => 'select',
            'choices'  => $font_sizes,
        ]);

        // === Border width
        $wp_customize->add_setting("firefly_thing_border_$slug", [
            'default' => '1px',
            'sanitize_callback' => 'sanitize_text_field',
        ]);
        $wp_customize->add_control("firefly_thing_border_{$slug}_control", [
            'label'    => __('Border width (px)', 'firefly'),
            'section'  => $section_id,
            'settings' => "firefly_thing_border_$slug",
            'type'     => 'select',
            'choices'  => [
                '0px' => '0px',
                '1px' => '1px',
                '2px' => '2px',
                '3px' => '3px',
                '4px' => '4px',
            ],
        ]);

        $wp_customize->add_setting("firefly_thing_image_padding_$slug", [
            'default' => '0px',
            'sanitize_callback' => 'sanitize_text_field',
        ]);

        $wp_customize->add_control("firefly_thing_image_padding_{$slug}_control", [
            'label'    => __('Padding around image (inside border)', 'firefly'),
            'section'  => $section_id,
            'settings' => "firefly_thing_image_padding_$slug",
            'type'     => 'select',
            'choices'  => array_combine(
                array_map(fn($n) => "{$n}px", range(0, 50)),
                array_map(fn($n) => "{$n}px", range(0, 50))
            ),
        ]);

        $wp_customize->add_setting("firefly_thing_panel_margin_$slug", [
            'default' => '10px',
            'sanitize_callback' => 'sanitize_text_field',
        ]);

        $wp_customize->add_control("firefly_thing_panel_margin_{$slug}_control", [
            'label'    => __('Space between ' . $label . ' (outside border)', 'firefly'),
            'section'  => $section_id,
            'settings' => "firefly_thing_panel_margin_$slug",
            'type'     => 'select',
            'choices'  => array_combine(
                array_map(fn($n) => "{$n}px", range(0, 50)),
                array_map(fn($n) => "{$n}px", range(0, 50))
            ),
        ]);








    

// === Colour pickers (styled radios)

foreach ([

     'background_colour' => 'Background colour (outside panel)',
      'panel_colour'       => 'Inside panel colour',
    'line_colour'       => 'Line colour',
    'heading_colour'       => 'Heading colour',
    'text_colour'       => 'Text colour'

] as $type => $label_text) {



    $setting_id = "firefly_thing_{$type}_$slug";



    $wp_customize->add_setting($setting_id, [

        'default'           => $type === 'text_colour' ? 'black' : 'white',

        'sanitize_callback' => 'sanitize_text_field',

        'transport'         => 'refresh',

    ]);



    $wp_customize->add_control(new Firefly_Radio_Colour_Control_text($wp_customize, "{$setting_id}_control", [

        'label'    => __($label_text, 'firefly'),

        'section'  => $section_id,

        'settings' => $setting_id,

        'choices'  => $colour_choices,

    ]));

}








        $font_keys = [
            'my_plugin_h1_font',
            'my_plugin_h2_font',
            'my_plugin_h3_font',
            'my_plugin_body_font',
        ];

        // Get fonts from theme mods
        $fonts = [];
        foreach ($font_keys as $key) {
            $font = trim(get_theme_mod($key));
            if ($font !== '') {
                $fonts[] = $font;
            }
        }

        // Add fallback
        $fonts[] = 'Arial, Helvetica';

        // Make unique list
        $unique_fonts = array_unique($fonts);

        // Build choices array for radio buttons
        $font_choices = [];
        foreach ($unique_fonts as $font) {
            $font_choices[$font] = $font;
        }

        // === Heading Font
        $wp_customize->add_setting("firefly_thing_heading_font_$slug", [
            'default'           => get_theme_mod('my_plugin_h1_font', 'Arial, Helvetica'),
            'sanitize_callback' => 'sanitize_text_field',
        ]);

        $wp_customize->add_control("firefly_thing_heading_font_{$slug}_control", [
            'label'    => __('Heading font', 'firefly'),
            'section'  => $section_id,
            'settings' => "firefly_thing_heading_font_$slug",
            'type'     => 'radio',
            'choices'  => $font_choices,
        ]);

        // === Description Font
        $wp_customize->add_setting("firefly_thing_description_font_$slug", [
            'default'           => get_theme_mod('my_plugin_body_font', 'Arial, Helvetica'),
            'sanitize_callback' => 'sanitize_text_field',
        ]);

        $wp_customize->add_control("firefly_thing_description_font_{$slug}_control", [
            'label'    => __('Description font', 'firefly'),
            'section'  => $section_id,
            'settings' => "firefly_thing_description_font_$slug",
            'type'     => 'radio',
            'choices'  => $font_choices,
        ]);

        $wp_customize->add_setting("firefly_thing_thumb_height_$slug", [
            'default'           => '300',
            'sanitize_callback' => 'absint',
        ]);

        $wp_customize->add_control("firefly_thing_thumb_height_{$slug}_control", [
            'label'    => __('Thumbnail height', 'firefly'),
            'section'  => $section_id,
            'settings' => "firefly_thing_thumb_height_$slug",
            'type'     => 'number',
            'input_attrs' => [
                'min' => 50,
                'max' => 1000,
                'step' => 10,
                'style' => 'width:80px;display:inline-block;margin-right:5px;',
            ],
            'description' => 'px',
        ]);

        $wp_customize->add_setting("firefly_thing_thumb_width_$slug", [
            'default'           => '300',
            'sanitize_callback' => 'absint',
        ]);

        $wp_customize->add_control("firefly_thing_thumb_width_{$slug}_control", [
            'label'    => __('Thumbnail width', 'firefly'),
            'section'  => $section_id,
            'settings' => "firefly_thing_thumb_width_$slug",
            'type'     => 'number',
            'input_attrs' => [
                'min' => 50,
                'max' => 1000,
                'step' => 10,
                'style' => 'width:80px;display:inline-block;margin-right:5px;',
            ],
            'description' => 'px',
        ]);

        //================================
        // Optional options
        //================================

        // Dummy setting just for heading
        $wp_customize->add_setting("firefly_optional_options_heading_$slug", [
            'default' => '',
            'sanitize_callback' => 'sanitize_text_field',
        ]);

        $wp_customize->add_control("firefly_optional_options_heading_{$slug}_control", [
            'label'       => __('Optional Options', 'firefly'),
            'section'     => $section_id,
            'settings'    => "firefly_optional_options_heading_$slug",
            'type'        => 'text',
            'input_attrs' => [
                'style' => 'display:none;', // Hides the actual input
            ],
            'description' => 'The following options are used in some, but not all styles, so some may be irrelevant.',
        ]);

        //===================================
        // extract x words from description
        //===================================
        $wp_customize->add_setting("firefly_thing_excerpt_length_$slug", [
            'default'           => 0,
            'sanitize_callback' => 'absint',
        ]);

        $wp_customize->add_control("firefly_thing_excerpt_length_{$slug}_control", [
            'label'       => __('Show the following number of words from the description on the list of all things', 'firefly'),
            'section'     => $section_id,
            'settings'    => "firefly_thing_excerpt_length_$slug",
            'type'        => 'number',
            'input_attrs' => [
                'min'   => 0,
                'step'  => 1,
                'style' => 'width:80px;margin-right:10px;',
            ],
            'description' => __('(Default: 0 — show nothing)', 'firefly'),
        ]);

        $wp_customize->add_setting("firefly_thing_panel_width_$slug", [
            'default'           => '300',
            'sanitize_callback' => 'absint',
        ]);

        $wp_customize->add_control("firefly_thing_panel_width_{$slug}_control", [
            'label'    => __('Panel width', 'firefly'),
            'section'  => $section_id,
            'settings' => "firefly_thing_panel_width_$slug",
            'type'     => 'number',
            'input_attrs' => [
                'min' => 50,
                'max' => 1000,
                'step' => 10,
                'style' => 'width:80px;display:inline-block;margin-right:5px;',
            ],
            'description' => 'px',
        ]);

        $margin_padding_choices = [];
        for ($i = 0; $i <= 50; $i++) {
            $margin_padding_choices["{$i}px"] = "{$i}px";
        }


        // === Margin Top
        $wp_customize->add_setting("firefly_panel_margin_top_$slug", [
            'default'           => '0px',
            'sanitize_callback' => 'sanitize_text_field',
        ]);
        $wp_customize->add_control("firefly_panel_margin_top_{$slug}_control", [
            'label'    => __('Container margin top', 'firefly'),
            'section'  => $section_id,
            'settings' => "firefly_panel_margin_top_$slug",
            'type'     => 'select',
            'choices'  => $margin_padding_choices,
        ]);

        // === Margin Bottom
        $wp_customize->add_setting("firefly_panel_margin_bottom_$slug", [
            'default'           => '0px',
            'sanitize_callback' => 'sanitize_text_field',
        ]);
        $wp_customize->add_control("firefly_panel_margin_bottom_{$slug}_control", [
            'label'    => __('Container margin bottom', 'firefly'),
            'section'  => $section_id,
            'settings' => "firefly_panel_margin_bottom_$slug",
            'type'     => 'select',
            'choices'  => $margin_padding_choices,
        ]);



          // === container padding top
        $wp_customize->add_setting("firefly_container_padding_top_$slug", [
            'default'           => '0px',
            'sanitize_callback' => 'sanitize_text_field',
        ]);
        $wp_customize->add_control("firefly_container_padding_top_{$slug}_control", [
            'label'    => __('Container padding top', 'firefly'),
            'section'  => $section_id,
            'settings' => "firefly_container_padding_top_$slug",
            'type'     => 'select',
            'choices'  => $margin_padding_choices,
        ]);


        
          // ===  container padding  Bottom
        $wp_customize->add_setting("firefly_container_padding_bottom_$slug", [
            'default'           => '0px',
            'sanitize_callback' => 'sanitize_text_field',
        ]);
        $wp_customize->add_control("firefly_container_padding_bottom_{$slug}_control", [
            'label'    => __('Container padding bottom', 'firefly'),
            'section'  => $section_id,
            'settings' => "firefly_container_padding_bottom_$slug",
            'type'     => 'select',
            'choices'  => $margin_padding_choices,
        ]);


        // === Padding Top
        $wp_customize->add_setting("firefly_panel_padding_top_$slug", [
            'default'           => '0px',
            'sanitize_callback' => 'sanitize_text_field',
        ]);
        $wp_customize->add_control("firefly_panel_padding_top_{$slug}_control", [
            'label'    => __('Padding top (inside panel)', 'firefly'),
            'section'  => $section_id,
            'settings' => "firefly_panel_padding_top_$slug",
            'type'     => 'select',
            'choices'  => $margin_padding_choices,
        ]);

        // === Padding Bottom
        $wp_customize->add_setting("firefly_panel_padding_bottom_$slug", [
            'default'           => '0px',
            'sanitize_callback' => 'sanitize_text_field',
        ]);
        $wp_customize->add_control("firefly_panel_padding_bottom_{$slug}_control", [
            'label'    => __('Padding bottom (inside panel)', 'firefly'),
            'section'  => $section_id,
            'settings' => "firefly_panel_padding_bottom_$slug",
            'type'     => 'select',
            'choices'  => $margin_padding_choices,
        ]);

        $wp_customize->add_setting("firefly_panel_padding_leftright_$slug", [
            'default'           => '0px',
            'sanitize_callback' => 'sanitize_text_field',
        ]);
        $wp_customize->add_control("firefly_panel_padding_leftright_{$slug}_control", [
            'label'    => __('Padding left and right (inside panel)', 'firefly'),
            'section'  => $section_id,
            'settings' => "firefly_panel_padding_leftright_$slug",
            'type'     => 'select',
            'choices'  => $margin_padding_choices,
        ]);

        // === Padding Bottom
        $wp_customize->add_setting("firefly_panel_heading_padding_top_$slug", [
            'default'           => '0px',
            'sanitize_callback' => 'sanitize_text_field',
        ]);
        $wp_customize->add_control("firefly_panel_heading_padding_top_{$slug}_control", [
            'label'    => __('Space above heading', 'firefly'),
            'section'  => $section_id,
            'settings' => "firefly_panel_heading_padding_top_$slug",
            'type'     => 'select',
            'choices'  => $margin_padding_choices,
        ]);

        // === Padding Bottom
        $wp_customize->add_setting("firefly_panel_heading_padding_bottom_$slug", [
            'default'           => '0px',
            'sanitize_callback' => 'sanitize_text_field',
        ]);
        $wp_customize->add_control("firefly_panel_heading_padding_bottom_{$slug}_control", [
            'label'    => __('Space below heading', 'firefly'),
            'section'  => $section_id,
            'settings' => "firefly_panel_heading_padding_bottom_$slug",
            'type'     => 'select',
            'choices'  => $margin_padding_choices,
        ]);

        // === Padding Bottom
        $wp_customize->add_setting("firefly_panel_description_padding_bottom_$slug", [
            'default'           => '0px',
            'sanitize_callback' => 'sanitize_text_field',
        ]);
        $wp_customize->add_control("firefly_panel_description_padding_bottom_{$slug}_control", [
            'label'    => __('Space below description', 'firefly'),
            'section'  => $section_id,
            'settings' => "firefly_panel_description_padding_bottom_$slug",
            'type'     => 'select',
            'choices'  => $margin_padding_choices,
        ]);

        // === Optional options subheading
        $wp_customize->add_control(new WP_Customize_Control($wp_customize, "firefly_optional_options_heading_$slug", [
            'label'    => __('Optional options (the following options may not appear or be used on every style)', 'firefly'),
            'section'  => $section_id,
            'type'     => 'hidden',
            'description' => '<strong>' . __('Optional options (the following options may not appear or be used on every style)', 'firefly') . '</strong>',
        ]));

        // === Text alignment
        $wp_customize->add_setting("firefly_thing_text_align_$slug", [
            'default'           => 'left',
            'sanitize_callback' => function ($input) {
                return in_array($input, ['left', 'center']) ? $input : 'left';
            },
        ]);

        $wp_customize->add_control("firefly_thing_text_align_{$slug}_control", [
            'label'    => __('Text alignment', 'firefly'),
            'section'  => $section_id,
            'settings' => "firefly_thing_text_align_$slug",
            'type'     => 'radio',
            'choices'  => [
                'left'   => __('Left', 'firefly'),
                'center' => __('Center', 'firefly'),
            ],
        ]);



           // Add this right after your padding controls
        $wp_customize->add_setting("firefly_align_price_bottom_$slug", [
            'default'           => false,
            'sanitize_callback' => 'wp_validate_boolean',
        ]);

        $wp_customize->add_control("firefly_align_price_bottom_{$slug}_control", [
            'label'       => __('Align prices (if they exist) to the bottom of the panel', 'firefly'),
            'section'     => $section_id,
            'settings'    => "firefly_align_price_bottom_$slug",
            'type'        => 'checkbox',
            'priority'    => 20, // Adjust as needed to fit your control order
        ]);


        // Add this right after your padding controls
        $wp_customize->add_setting("firefly_show_thing_borders_$slug", [
            'default'           => false,
            'sanitize_callback' => 'wp_validate_boolean',
        ]);

        $wp_customize->add_control("firefly_show_thing_borders_{$slug}_control", [
            'label'       => __('Show borders around divs', 'firefly'),
            'section'     => $section_id,
            'settings'    => "firefly_show_thing_borders_$slug",
            'type'        => 'checkbox',
            'description' => __('Enable borders around content containers', 'firefly'),
            'priority'    => 20, // Adjust as needed to fit your control order
        ]);
            }
});







add_shortcode('things', function ($atts) {
   
$query = null;


      ob_start();

    // Handle ?edit_thng_pictures=ID request BEFORE any returns
    if (current_user_can('manage_options') && isset($_GET['edit_thng_pictures'])) {
        $pic_post_id = absint($_GET['edit_thng_pictures']);

       if ($pic_post_id && get_post_status($pic_post_id)) {
    $gallery_ids = get_post_meta($pic_post_id, 'thing_gallery', true);
    if (!is_array($gallery_ids)) {
        $gallery_ids = [];
    }

    $atts = shortcode_atts(['show' => ''], $atts);
    $show = sanitize_text_field(trim($atts['show']));
    $slug = firefly_find_slug_for_subcategory($show);

 //    echo "<h1>=$show=$slug=</h1>";
    echo '<div class="firefly-admin-5" style="margin-top:30px;padding:20px;border:2px dashed #ccc;background:#f9f9f9">';
    echo '<h2>Edit Pictures (#' . esc_html($pic_post_id) . ')</h2>';

       echo '<p><a href="' . esc_url(remove_query_arg('edit_thng_pictures')) . '">Back</a></p>';


       echo ' <div id="firefly-upload-overlay">
            <div id="firefly-spinner"></div>
            <div>Processing images...</div>
        </div>
        
        
        <style>



    
        
          #firefly-upload-overlay {
                position: fixed;
                z-index: 9999;
                background: rgba(0, 0, 0, 0.6);
                color: white;
                font-size: 20px;
                top: 0; left: 0; right: 0; bottom: 0;
                display: none;
                align-items: center;
                justify-content: center;
                flex-direction: column;
            }
            #firefly-spinner {
                border: 6px solid #f3f3f3;
                border-top: 6px solid #3498db;
                border-radius: 50%;
                width: 40px;
                height: 40px;
                animation: spin 1s linear infinite;
                margin-bottom: 15px;
            }
            @keyframes spin {
                0% { transform: rotate(0deg); }
                100% { transform: rotate(360deg); }
            }
                
            </style>
            ';

    if (!empty($gallery_ids)) {
wp_enqueue_script( 'jquery-ui-sortable' );
        echo '<div id="firefly-sortable" class="thing-gallery" style="display:flex;flex-wrap:wrap;gap:10px;margin-bottom:20px;margin-left:50px;">';


        echo '<div class="thing-gallery" style="display:flex;flex-wrap:wrap;gap:10px;margin-bottom:20px;margin-left:50px;">';
      foreach ($gallery_ids as $img_id) {
                $mime = get_post_mime_type($img_id);
                $img_url = wp_get_attachment_url($img_id);
                if (!$img_url || strpos($mime, 'image/') !== 0) continue;

                $img_html = wp_get_attachment_image($img_id, 'medium', false, [
                    'style' => 'border-radius:6px;max-width:150px;height:auto;box-shadow:0 0 3px rgba(0,0,0,0.3);'
                ]);

                  echo '<div class="gallery-thumb-wrapper"'
       . ' id="img-' . esc_attr( $img_id ) . '"'      // <-- NEW
       . ' data-img-id="' . esc_attr( $img_id ) . '"'
       . ' style="position:relative;text-align:center;">';
                echo '<button class="delete-gallery-image" data-post-id="' . esc_attr($pic_post_id) . '" data-img-id="' . esc_attr($img_id) . '" style="position:absolute;top:-10px;right:-10px;background:red;color:white;border:none;border-radius:50%;width:24px;height:24px;cursor:pointer;font-weight:bold;line-height:20px;">×</button>';
                echo $img_html;
                echo '</div>';
            }

 '</div> </div> '  ;




/* ------------------------------------------------------------------
 * 3️⃣  Inline JS – inject immediately after the gallery
 * ------------------------------------------------------------------ */
$nonce = wp_create_nonce( 'firefly_sort_' . $pic_post_id );
$ajax  = admin_url( 'admin-ajax.php' );

echo <<<JS
<script>
jQuery(function ($) {

    $('#firefly-sortable').sortable({
        items: '.gallery-thumb-wrapper',
        tolerance: 'pointer',
        cursor: 'move',
        stop: function () {
            // Build array of IDs in their new order
            const ids = $('#firefly-sortable .gallery-thumb-wrapper')
                        .map(function () { return $(this).data('img-id'); })
                        .get();

         $.post('$ajax', {
            
    action:   'firefly_save_gallery_order',
    
    post_id:  $pic_post_id,
    order:    ids,
    featured: ids[0],
    _wpnonce: '$nonce'
}).done(function (rsp) {
    console.log('save_gallery_order →', rsp);          // SHOULD be {success: true}
}).fail(function (xhr) {
    alert('Save failed: ' + xhr.responseText);         // shows 403/500 details
});
        }
    });

});
</script>
JS;


    } else {
        echo '<p><em>No images found in gallery.</em></p>';
    }

 
    echo '</div>';
}




 echo '</div><div style="width:100%;clear:both;"></div><h3 style="margin-top:30px;">Add more pictures</h3>';


 echo '<div style="padding-left:50px;">

<form id="firefly-gallery-form" method="post" enctype="multipart/form-data" style="margin-top:30px;">


    <input type="file" name="thing_new_images[]" multiple accept="image/*"><br><br>
    <input type="hidden" name="firefly_post_id" value="' . esc_attr($pic_post_id) . '">
    <input type="hidden" name="firefly_gallery_nonce" value="' . esc_attr(wp_create_nonce('firefly_gallery_nonce')) . '">
    <button type="submit" name="submit_new_images" style="padding:10px 20px;">Upload Images</button>
</form>


<style>
@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}
</style>
<script>
document.addEventListener("DOMContentLoaded", function () {
    const galleryForm = document.getElementById("firefly-gallery-form");
    if (galleryForm) {
        galleryForm.addEventListener("submit", function () {
            document.getElementById("firefly-upload-overlay").style.display = "flex";
        });
    }
});
</script>

';
    echo '</div><p><a href="' . esc_url(remove_query_arg('edit_thng_pictures')) . '">Back</a></p>    ';
    
    


echo '<div id="image-preview" style="display:flex;flex-wrap:wrap;gap:10px;margin-top:10px;"></div>';


echo '<input type="hidden" id="firefly-post-id" value="' . esc_attr($pic_post_id) . '">';

 $nonce = wp_create_nonce('firefly_gallery_nonce');

 
echo '<input type="hidden" id="firefly-nonce" value="' . esc_attr(wp_create_nonce('firefly_gallery_nonce')) . '">';

echo '<script>
document.addEventListener("DOMContentLoaded", function () {
    const nonce = "' . esc_js($nonce) . '";
    document.querySelectorAll(".delete-gallery-image").forEach(function(button) {
        button.addEventListener("click", function(e) {
            e.preventDefault();
            if (!confirm("Remove this image from the gallery?")) return;

            const imgId = this.dataset.imgId;
            const postId = this.dataset.postId;
            const wrapper = this.closest(".gallery-thumb-wrapper");

            fetch("' . admin_url('admin-ajax.php') . '", {
                method: "POST",
                headers: { "Content-Type": "application/x-www-form-urlencoded" },
                body: new URLSearchParams({
                    action: "firefly_remove_gallery_image",
                    post_id: postId,
                    img_id: imgId,
                    _wpnonce: nonce
                })
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error("HTTP error " + response.status);
                }
                return response.text();
            })
            .then(text => {
                try {
                    const data = JSON.parse(text);
                    if (data.success) {
                        wrapper.remove();
                    } else {
                        console.error("Server error:", data);
                        alert("Error: " + (data.message || "Unknown error"));
                    }
                } catch (e) {
                    console.error("Invalid JSON:", text);
                    alert("AJAX failed — unexpected response:\n\n" + text);
                }
            })
            .catch(err => {
                console.error("Fetch error:", err);
                alert("AJAX request failed: " + err.message);
            });

        });
    });
});
</script>';




        return ob_get_clean(); // STOP everything else from rendering
    }


// -------------------------------------------------------------
// 1.  Shortcode attributes
// -------------------------------------------------------------
$atts      = shortcode_atts( [ 'show' => '' ], $atts );
$raw_show  = trim( $atts['show'] );         // what the user typed
$show_all  = ( $raw_show === '' );          // true for plain [things]
$slug_show = sanitize_title( $raw_show );   // normalised slug

// admins see drafts as well
$post_status = current_user_can( 'manage_options' )
    ? [ 'publish', 'draft' ]
    : 'publish';

// -------------------------------------------------------------
// 2.  Build the base query (every “Thing” has _is_thing = 1)
// -------------------------------------------------------------
$args = [
    'post_type'      => 'post',
    'post_status'    => $post_status,
    'posts_per_page' => -1,
    'orderby'        => 'title',
    'order'          => 'ASC',
    'meta_query'     => [
        [
            'key'     => '_is_thing',
            'value'   => '1',
            'compare' => '=',
        ],
    ],
];

// -------------------------------------------------------------
// 3.  Decide how to filter — category • meta • all
// -------------------------------------------------------------
if ( ! $show_all ) {

    // Try category first
    $term = get_term_by( 'slug', $slug_show, 'category' );

    if ( $term ) {
        // CATEGORY MODE
        $args['category__in'] = [ $term->term_id ];
    } else {
        // META-FIELD MODE (featured, new-stock, on-behalf, …)
        $args['meta_query'][] = [
            'key'     => $slug_show,
            'value'   => '1',
            'compare' => '=',
        ];
    }
}

// -------------------------------------------------------------
// 4.  Run the query
// -------------------------------------------------------------
$q = new WP_Query( $args );

if ( ! $q->have_posts() ) {

    $therearenopostshere = "yes";
    // -------- nothing matched the filter --------
       if ( ! current_user_can( 'manage_options' ) ) {
        return;                     // visitors: show nothing
    }
}
else
{
     $therearenopostshere = "";
}
//echo "DDDD";
// -------------------------------------------------------------
// 5.  Output results (replace with your real template)
// -------------------------------------------------------------
//echo '<ul class="things-list">';
//while ( $q->have_posts() ) {
  //  $q->the_post();
 //   printf(
     //   '<li><a href="%s">%s</a></li>',
     //   esc_url( get_permalink() ),
     //   esc_html( get_the_title() )
    //);
//}
//echo '</ul>';

wp_reset_postdata();


//echo "<h1>-$show-</h1>";
    $defined_raw = get_theme_mod('firefly_things_list_textarea', '');
    $defined_things = array_filter(array_map('trim', explode("\n", $defined_raw)));
    $defined_slugs = array_map('strtolower', $defined_things);

    $is_valid_main = in_array(strtolower($show), $defined_slugs, true);

 //   $term = get_term_by('name', $show, 'category');
 
   //  $slug = sanitize_title($term->name);

    // $term = get_term_by('name', $show, 'category');
   // $slug = $term ? sanitize_title($term->name) : sanitize_title($show);





    $subcats_raw       = get_theme_mod("firefly_thing_subcategories_$slug", '');
  //  echo "<HR><h1>1. Sub cats ($slug):   $subcats_raw ==". $term->name . "==</h1>";

          //  echo "<pre>0. $slug= $subcats_raw =";
//print_r($subcats);
//echo '</pre>';

    $slug = sanitize_title($term->name);
    if (!$term) {
        if ($is_valid_main) {
            $result = wp_insert_term($show, 'category');
            if (is_wp_error($result)) {
                echo "<p>Could not create category '$show': " . $result->get_error_message() . "</p>";
                return ob_get_clean();
            }
            $term = get_term_by('name', $show, 'category');
        } else {
            
           // Try PLAN B: check if $show matches any of the defined subcategories
                
           // Plan B fallback: ignore category, just query posts with matching postmeta key
$meta_key = sanitize_title($show);


global $thisisjeff; 

if ($thisisjeff == "yes") {
  //  $meta_key = "featured";
//echo "<h3>🔎 Plan B search for posts where <code>$meta_key = 1 the slug is $slug</code></h3>";
}

//


//echo "<h1>Show 1: $show</h1>";
$query_args = [
    'post_type'      => 'post',
    'posts_per_page' => -1,
   'post_status'  => sanitize_key( $_POST['thing_status'] ?? 'draft' ),
    'meta_query'     => [
        [
            'key'     => $meta_key,
            'value'   => '1',
            'compare' => '='
        ],
        [
            'key'     => '_is_thing',
            'value'   => '1',
            'compare' => '='
        ]
    ],
    'orderby' => 'title',
    'order'   => 'ASC',
];



$meta_key = sanitize_title($show);

//echo "<h1>Show 2: $show</h1>";

$matching_posts = get_posts([
    'post_type'      => 'post',
        'post_status' => current_user_can( 'manage_options' )
                     ? [ 'publish', 'draft' ]    // admins: both
                     : 'publish',  
    'posts_per_page' => -1,
    'fields'         => 'ids', // Only get IDs
    'meta_query'     => [
        [
            'key'     => $meta_key,
            'value'   => '1',
            'compare' => '='
        ],
        [
            'key'     => '_is_thing',
            'value'   => '1',
            'compare' => '='
        ]
    ]
]);

// Store this list for use in full query
$plan_b_post_ids = $matching_posts;



$show        = isset( $atts['show'] ) ? sanitize_key( $atts['show'] ) : '';
$meta_key    = $show;                     // our meta-field name (e.g. "on-behalf")
$post_status = sanitize_key( $_POST['thing_status'] ?? 'publish' );

// 1️⃣  Quick header so you can see what’s happening.
//echo "<h3>🔎 Plan B » meta key <code>{$meta_key}</code> & post_status <code>{$post_status}</code></h3>";

$plan_b_post_ids = get_posts( [
    'post_type'      => 'post',
        'post_status' => current_user_can( 'manage_options' )
                     ? [ 'publish', 'draft' ]    // admins: both
                     : 'publish',  
    'posts_per_page' => -1,
    'fields'         => 'ids',          // only IDs – faster
    'meta_query'     => [
        [
            'key'     => $meta_key,
            'value'   => '1',
            'compare' => '=',           // e.g. featured = 1
        ],
        [
            'key'     => '_is_thing',
            'value'   => '1',
            'compare' => '=',           // narrow to “Thing” posts
        ],
    ],
] );

// -------------------------------------------------------------
//  Debug dump – remove when you’re happy
// -------------------------------------------------------------
if ( empty( $plan_b_post_ids ) ) {
 //   echo '<p><em>No matches found.</em></p>';
} else {
   // echo '<strong>Found ' . count( $plan_b_post_ids ) . " post(s):</strong><ul>";
   // foreach ( $plan_b_post_ids as $pid ) {
   //     printf(
    //        '<li>#%d – <a href="%s" target="_blank">%s</a></li>',
     //       $pid,
      //      esc_url( get_edit_post_link( $pid ) ), // edit-link is handy in dev
       //     esc_html( get_the_title( $pid ) )
       // );
   // }
    //echo '</ul>';
}

// -------------------------------------------------------------
//  $plan_b_post_ids is now an array of IDs – use it in the main
//  query or merge with your slug-based results as required.
// -------------------------------------------------------------


//print_r($plan_b_post_ids);

//echo "<h1>1150 plan B plan_b_post_ids</h1>";

// Fallback: try to determine the parent category (and slug) from the first matching post
//if (empty($slug) && !empty($plan_b_post_ids)) {
   // $post_id = $plan_b_post_ids[0]; // First matching post
  //  $categories = get_the_category($post_id);

    //if (!empty($categories)) {
      //  foreach ($categories as $cat) {
         //   if ($cat//->parent === 0) {
          //      $slug// = sanitize_title($cat->slug);
           //    break;
           // }
       // }
        // If no parent found, fallback to first category
       // if (empty($slug) && isset($categories[0])) {
        //    $slug = sanitize_title($categories[0]->slug);
       // }
    //}
//}


$slug = "";

        }
    }



    if (!$slug) {
        $atts = shortcode_atts(['show' => ''], $atts);
        $show = sanitize_text_field(trim($atts['show']));
        $slug = firefly_find_slug_for_subcategory($show);
      //  echo "There was no slug = $show - $slug";
    }
    else{
     //  echo "There is a slug";
    }


   // echo "<h1>2. Sub cats ($slug):   $subcats_raw ==". $term->name . "==</h1>";

//echo "==================================";
//firefly_debug_list_all_posts_with_subcategories();
//echo "==================================";

    $list_fields_raw   = get_theme_mod("firefly_thing_fields_list_$slug", '');
    $detail_fields_raw = get_theme_mod("firefly_thing_fields_detail_$slug", '');
    $checkbox_fields_raw = get_theme_mod("firefly_thing_fields_checkboxes_$slug", '');
    $subcats_raw       = get_theme_mod("firefly_thing_subcategories_$slug", '');

    $list_fields   = array_filter(array_map('trim', explode("\n", $list_fields_raw)));
    $detail_fields = array_filter(array_map('trim', explode("\n", $detail_fields_raw)));
    $checkbox_fields = array_filter(array_map('trim', explode("\n", $checkbox_fields_raw)));
    $subcategories = array_filter(array_map('trim', explode("\n", $subcats_raw)));

    $label_singular = get_theme_mod("firefly_thing_label_singular_$slug", ucfirst(rtrim($slug, 's')));



    // === Admin Panel to Add or Edit a Thing
    if (current_user_can('manage_options')) {
        $thing_label = esc_html(ucfirst($slug));
        $form_id = 'form-' . bin2hex(random_bytes(4));

        $edit_id = isset($_GET['edit_thing']) ? intval($_GET['edit_thing']) : 0;
        $editing = $edit_id && get_post_status($edit_id);
        $edit_post = $editing ? get_post($edit_id) : null;

        echo '
        <style>


        /* these styles come from firefly-things.php */

        input[type="text"],
textarea {
    border: 1px solid #999;        /* grey border */
    font-size: 16px;               /* larger text */
    padding: 8px 10px;             /* inner space */
    border-radius: 4px;            /* optional: rounded corners */
    width: 100%;                   /* full width for consistency */
    box-sizing: border-box;        /* prevent padding from expanding width */
}

textarea {
    min-height: 100px;             /* optional: taller by default */
    resize: vertical;              /* allow vertical resizing */
}
    
            #firefly-upload-overlay {
                position: fixed;
                z-index: 9999;
                background: rgba(0, 0, 0, 0.6);
                color: white;
                font-size: 20px;
                top: 0; left: 0; right: 0; bottom: 0;
                display: none;
                align-items: center;
                justify-content: center;
                flex-direction: column;
            }
            #firefly-spinner {
                border: 6px solid #f3f3f3;
                border-top: 6px solid #3498db;
                border-radius: 50%;
                width: 40px;
                height: 40px;
                animation: spin 1s linear infinite;
                margin-bottom: 15px;
            }
            @keyframes spin {
                0% { transform: rotate(0deg); }
                100% { transform: rotate(360deg); }
            }
            .firefly-checkbox-grid {
                display: grid;
                grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
                gap: 10px 20px;
                padding: 10px 0;
            }
            .firefly-checkbox-grid label {
                display: flex;
                align-items: center;
                gap: 6px;
                font-size: 14px;
                white-space: normal;
                line-height: 1.3;
            }
        </style>

   

        <script>
        document.addEventListener("DOMContentLoaded", function () {
            const form = document.querySelector(".firefly-admin-4 form");
            const overlay = document.getElementById("firefly-upload-overlay");

            if (form && overlay) {
                form.addEventListener("submit", function () {
                    overlay.style.display = "flex";
                });
            }
        });
        </script>';




        echo '<div class="firefly-admin-1" style="text-align:left">';
        echo '<div class="firefly-admin-2">Options for ' . $thing_label . '</div>';
        echo '<div class="firefly-admin-3">';
      
global $thisisjeff;
       //  if ($term->term_id) {

                 //  if ( $thisisjeff ) {
                  //  echo "<B>Term_:id: ";
                 //   echo $term->term_id;
                  // }
                 //  else{
                  //  echo "a";
                 //  }
              //  }  else{
                   // echo "b";
      //  }
            

        if (!$term->term_id) {


      //  echo "Go to the <a href='https://prestige.rainbowdigital.co.nz/caravans/' style='color:black;text-decoration:underline !important;'>caravans page</a> to add a new caravan. Jeff is working on this!";

     //  if ( $thisisjeff ) {
         //   echo "c";
    // Try to find the category that matches this label
    // 1️⃣  safest is to compare the slug
    $debug_term = get_term_by(
        'slug',
        sanitize_title( $thing_label ),
        'category'
    );

    // 2️⃣  fall back to a case-insensitive name match if the slug lookup fails
    if ( ! $debug_term ) {
        $debug_term = get_term_by(
            'name',
            $thing_label,
            'category'
        );
    }

    // 3️⃣  Output the result
  //  if ( $debug_term && ! is_wp_error( $debug_term ) ) {
      //  echo '<strong> – ' . esc_html( $thing_label ) .
       //   ' (term_id ' . intval( $debug_term->term_id ) . ')</strong>';
 //} else {
    //  echo '<strong> – ' . esc_html( $thing_label ) .
          //   ' (no matching category yet)</strong>';
   //}
//}


    }
  //  else
  //  {
        echo '<a href="#" class="show-firefly-form" data-target="' . esc_attr($form_id) . '" style="color:black;text-decoration:none;">' . ($editing ? 'Edit this ' . esc_html(strtolower($label_singular)) : 'Add a new ' . esc_html(strtolower($label_singular))) . '</a>';

   // }
        echo '</div>'; // Close firefly-admin-3

        // Main edit form
        echo '<div class="firefly-admin-4" id="' . esc_attr($form_id) . '" style="display:' . ($editing ? 'block' : 'none') . ';margin-bottom:10px;">';
        echo "\n\r\n\r\n\r";
        
      

if ($editing) {


  $nonce_action = 'firefly_update_thing_' . $edit_id;
    
    echo '<form method="post" action="' . esc_url(admin_url('admin-post.php')) . '">';
    echo '<input type="hidden" name="action" value="update_thing">';
    echo '<input type="hidden" name="thing_id" value="' . esc_attr($edit_id) . '">';
   // echo '<input type="hidden" name="thing_category" value="' . esc_attr($term->term_id) . '">';

$term_id_for_form = $term ? $term->term_id : 0;

// Fallback for Plan B: get the parent category of the post if editing
if (!$term_id_for_form && $editing) {
    $cats = get_the_category($edit_id);
    if (!empty($cats)) {
        foreach ($cats as $cat) {
            if ($cat->parent === 0) {
                $term_id_for_form = $cat->term_id;
                break;
            }
        }
        // If no parent, just grab the first
        if (!$term_id_for_form) {
            $term_id_for_form = $cats[0]->term_id;
        }
    }
}

echo '<input type="hidden" name="thing_category" value="' . esc_attr($term_id_for_form) . '">';

//echo "ID 1: ". esc_attr($term_id_for_form) . "-$term_id-" . esc_attr($term->term_id) ;


    wp_nonce_field($nonce_action);


} else {
    echo '<form method="post" enctype="multipart/form-data" action="' . esc_url(admin_url('admin-post.php')) . '">';
    echo '<input type="hidden" name="action" value="add_thing">';
    echo '<input type="hidden" name="thing_category" value="' ;
    
    if ($term->term_id) {
        echo  esc_attr($term->term_id);
        $using   = "a: $term->term_id";
    }
    elseif ($debug_term->term_id) {
        echo  esc_attr($debug_term->term_id);
        $using   = "b: $debug_term->term_id";
    }
    elseif ($term_id_for_form) {
        echo  esc_attr($term_id_for_form);
        $using   = "c: term_id_for_form";
    }
     elseif ($term_id) {
        echo  esc_attr($term_id);
        $using   = "ad: $term_id";
    }
    else{
        $using = "";
        echo "<h2 style='color:red;'>There is a problem adding this thing - send Jeff an emaail jeff@rainbowcreative.co.nz</h2>";
    }
    echo '">';

  //echo "ID 2: a: ". esc_attr($term_id_for_form) . "<BR>b: $debug_term->term_id <BR>c: $term_id <BR>d:" . esc_attr($term->term_id) ;

    wp_nonce_field('firefly_add_thing', '_wpnonce');
}
        $title_value = $editing ? esc_attr($edit_post->post_title) : '';
        $content_value = $editing ? esc_textarea($edit_post->post_content) : '';

        echo '<p><label>Title:<br><input type="text" name="thing_title" required style="width:100%" value="' . $title_value . '"></label></p>';
        echo '<p><label>Description:<br><textarea name="thing_content" style="width:100%" rows="4">' . $content_value . '</textarea></label></p>';


// Values for edit mode
$overlay_text_value  = $editing ? get_post_meta($edit_id, 'firefly_overlay_text', true) : '';
$overlay_style_value = $editing ? get_post_meta($edit_id, 'firefly_overlay_style', true) : '';
if (empty($overlay_style_value)) { $overlay_style_value = 'green'; }
?>

<p>
  <label>Overlay text (eg “Price reduced!”):<br>
    <input type="text" name="firefly_overlay_text" style="width:100%"
           value="<?php echo esc_attr($overlay_text_value); ?>">
  </label>
</p>

<div style="margin:8px 0 16px;">

 <label for="firefly_overlay_style"><strong>Overlay colour:</strong></label><br>


<select id="firefly_overlay_style" name="firefly_overlay_style" style="padding:6px; border-radius:6px; min-width:140px;">
  <?php
$colours = [
  'red'          => 'Red',
  'darkred'      => 'Dark Red',
  'crimson'      => 'Crimson',
  'firebrick'    => 'Firebrick',
  'maroon'       => 'Maroon',
  'orangered'    => 'Orange Red',
  'orange'    => 'Orange',
  'darkorange'   => 'Dark Orange',
  'chocolate'    => 'Chocolate',
  'saddlebrown'  => 'Saddle Brown',
  'olive'        => 'Olive',
  'green'        => 'Green',
  'darkgreen'    => 'Dark Green',
  'seagreen'     => 'Sea Green',
  'teal'         => 'Teal',
  'darkcyan'     => 'Dark Cyan',
  'steelblue'    => 'Steel Blue',
  'royalblue'    => 'Royal Blue',
  'blue'         => 'Blue',
  'midnightblue' => 'Midnight Blue',
  'navy'         => 'Navy',
  'indigo'       => 'Indigo',
  'purple'       => 'Purple',
  'darkmagenta'  => 'Dark Magenta',
  'mediumvioletred' => 'Medium Violet Red',
  'deeppink'     => 'Deep Pink',
   'deeppink'         => 'Deep Pink',
  'mediumvioletred'  => 'Medium Violet Red',
  'palevioletred'    => 'Pale Violet Red',
  'hotpink'          => 'Hot Pink',
  'fuchsia'          => 'Fuchsia',
  'magenta'          => 'Magenta',
  'mediumorchid'     => 'Medium Orchid',
  'darkorchid'       => 'Dark Orchid',
  'orchid'           => 'Orchid',
  'darkmagenta'      => 'Dark Magenta',
  'violet'           => 'Violet',
  'darkslategray'=> 'Dark Slate Gray',
  'dimgray'      => 'Dim Gray',
  'black'        => 'Black'
];


  foreach ($colours as $value => $label) {
    $selected   = selected($overlay_style_value, $value, false);
    echo '<option value="' . esc_attr($value) . '" ' . $selected .
         ' style="background:' . esc_attr($value) . '; color:white;">' .
         esc_html($label) . '</option>';
  }
  ?>
</select>


</div>
<?php
        
$subcategories_raw = get_theme_mod("firefly_thing_subcategories_$slug", '');
$subcategories = array_filter(array_map('trim', explode("\n", $subcategories_raw)));

if (!empty($subcategories)) {
    echo '<div class="firefly-subcategories">';
    echo '<p><strong>Sub-categories:</strong></p>';
    
    foreach ($subcategories as $subcat) {
        $subcat_key = sanitize_title($subcat);
        $value = $editing ? (int) get_post_meta($edit_id, $subcat_key, true) : 0;

        echo '<div style="margin-bottom:10px;">';
        echo '<label style="display:block;font-weight:bold;margin-bottom:5px;">' . esc_html($subcat) . ': ';

      //  echo '<label style="margin-right:15px;">';
        echo ' <input type="radio" name="thing_meta[' . esc_attr($subcat_key) . ']" value="1"' . checked($value, 1, false) . '> Yes';
      //  echo '</label>';

       // echo '<label>';
        echo ' <input type="radio" name="thing_meta[' . esc_attr($subcat_key) . ']" value="0"' . checked($value, 0, false) . '> No';
       // echo '</label>';

        echo '</div>';
    }

    echo '</div>';
}


/* === Show / Hide status (now via post_status) === */
if ( $editing ) {
    // honour legacy meta once, then migrate ↓
    $legacy = get_post_meta( $edit_id, '_thing_status', true );
    if ( $legacy ) {
        $status = ( $legacy === 'show' ) ? 'publish' : 'draft';
        wp_update_post( [ 'ID' => $edit_id, 'post_status' => $status ] );
        delete_post_meta( $edit_id, '_thing_status' );
    }
    $status = get_post_status( $edit_id );               // 'publish', 'draft', …
} else {
    $status = 'draft';                                   // default for NEW things
}

echo '<p><strong>Status:</strong><br>';
echo '<label style="margin-right:15px;">
        <input type="radio" name="thing_status" value="publish" '
        . checked( $status, 'publish', false ) . '> Visible
      </label>';
echo '<label>
        <input type="radio" name="thing_status" value="draft" '
        . checked( $status, 'draft',   false ) . '> Hidden
      </label></p>';

//if ( !$editing ) {
        echo '<p><button type="submit" style="background-color:blue;padding:10px;color:white; border-radius: 25px;
  width: 200px;margin:0 auto;cursor:pointer;
font-size:18px;">' . ($editing ? 'Update' : 'Add') . '</button></p> ';

//}
        foreach (array_merge($list_fields, $detail_fields) as $field_raw) {
          //  $field = ltrim($field_raw, '*');
         //   $key = sanitize_key($field);


              $field = ltrim($field_raw, '*');
      //  $key = sanitize_key($field);
          
          //  $key = str_replace(" ", "", $field);
          //  $key = str_replace("/", "", $key);
          //  $key = str_replace('"', "", $key);
          //  $key = str_replace("'", "", $key);
          //  $key = strtolower($key);

                $key = thing_meta_key( $field );

            $label = esc_html(ucfirst($field));
            $value = $editing ? get_post_meta($edit_id, $key, true) : '';

            echo '<p><label>' . $label . ': ';
            echo '<input type="text" name="thing_meta[' . esc_attr($key) . ']" style="width:100%" value="' . esc_attr($value) . '">';
            echo '</label></p>';
        }

   if (!empty($checkbox_fields)) {
    echo '<div>';
    $current_section = '';
    
    foreach ($checkbox_fields as $field_raw) {
        $field = ltrim($field_raw, '*');
        $key = sanitize_key($field);

          $field = ltrim($field_raw, '*');
      //  $key = sanitize_key($field);
          
       // $key = str_replace(" ", "", $field);
          //  $key = str_replace("/", "", $key);
        //    $key = str_replace('"', "", $key);
         //   $key = str_replace("'", "", $key);
          //  $key = strtolower($key);

$key = thing_meta_key( $field );
            
        $label = esc_html(ucfirst($field));
        $value = $editing ? get_post_meta($edit_id, $key, true) : '';


        // Inside the custom fields loop (after $value assignment)
//global $thisisjeff;
//if ($thisisjeff && $editing) {
 //   $all_meta = get_post_meta($edit_id);
  //  echo '<div style="background:#ff0;color:#000;padding:10px;margin:5px 0;">';
  //  echo '<strong>DEBUG:</strong> Field: ' . esc_html($field) . '<br>';
  //  echo 'Key: ' . esc_html($key) . '<br>';
   // echo 'Value: ' . esc_html($value) . '<br>';
   // echo 'All meta keys: ' . esc_html(implode(', ', array_keys($all_meta)));
   // echo '</div>';
//}

        if (stristr($field_raw, "*")) {
            // Close previous section if one was open
            if (!empty($current_section)) {
                echo '</div>';
            }
            // Start new section
            $current_section = 'section-' . sanitize_key($field);
            echo "<hr><p><strong>$field</strong> - <a href='#' class='select-all' data-section='$current_section'>select all</a></p>";
            echo "<div class='checkbox-section' id='$current_section' >";
        } else {
            echo '<label><input type="checkbox" name="thing_meta[' . esc_attr($key) . ']" value="1"' . checked($value, 1, false) . '> ';
            echo "$label</label><br>";
        }
    }
    
    // Close the last section if one was open
    if (!empty($current_section)) {
        echo '</div>';
    }
    
    echo '</div>'; // Close the main div
    
    // Add the JavaScript
    ?>
    <script>
    document.addEventListener("DOMContentLoaded", function() {
        document.querySelectorAll(".select-all").forEach(function(link) {
            link.addEventListener("click", function(e) {
                e.preventDefault();
                var sectionId = this.getAttribute("data-section");
                var checkboxes = document.querySelectorAll("#" + sectionId + " input[type=checkbox]");
                var allChecked = Array.from(checkboxes).every(checkbox => checkbox.checked);
                
                checkboxes.forEach(function(checkbox) {
                    checkbox.checked = !allChecked;
                });
                
                this.textContent = allChecked ? "select all" : "deselect all";
            });
        });
    });
    </script>
    <?php
}


        if ($editing) {
    echo '<input type="hidden" name="action" value="update_thing">';
}else{
        echo '
        <style>
        .preview-container {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            margin-bottom: 10px;
        }
        .preview-thumb {
            position: relative;
            width: 100px;
            height: 100px;
        }
        .preview-thumb img {
            width: 100%;
            height: 100%;
            object-fit: cover;
            border: 1px solid #ccc;
            border-radius: 4px;
        }
        .preview-thumb button {
            position: absolute;
            top: -6px;
            right: -6px;
            background: red;
            color: white;
            border: none;
            border-radius: 50%;
            cursor: pointer;
            width: 20px;
            height: 20px;
            font-size: 14px;
            line-height: 18px;
        }
        </style>

        <div class="preview-container" id="image-preview"></div>
   <div id="firefly-upload-overlay">
            <div id="firefly-spinner"></div>
            <div>Processing images...</div>
        </div>
        <p><label>Images:<br>
        <input type="file" name="thing_image[]" accept="image/*" multiple id="image-input">
        </label></p>

        <input type="hidden" name="thing_gallery_data" id="firefly-gallery-data">';

        echo '<script>
        document.addEventListener("DOMContentLoaded", function () {
            const input = document.getElementById("image-input");
            const preview = document.getElementById("image-preview");
            const form = input.closest("form");
            const hiddenField = document.getElementById("firefly-gallery-data");
            const overlay = document.getElementById("firefly-upload-overlay");
            const spinner = document.getElementById("firefly-spinner");
            let filesArray = [];

            // Show processing overlay with custom message
            function showProcessing(message) {
                if (overlay) {
                    overlay.querySelector("div:last-child").textContent = message;
                    overlay.style.display = "flex";
                }
            }

            // Hide processing overlay
            function hideProcessing() {
                if (overlay) {
                    overlay.style.display = "none";
                }
            }

            // === Show thumbnails immediately when files are selected
            input.addEventListener("change", function () {
                if (!input.files.length) return;
                
                showProcessing("Generating thumbnails...");
                
                // Use setTimeout to allow the UI to update before heavy processing
                setTimeout(() => {
                    preview.innerHTML = ""; // Clear previous previews
                    filesArray = Array.from(input.files);
                    
                    let processed = 0;
                    const totalFiles = filesArray.length;
                    
                    filesArray.forEach((file, index) => {
                        if (!file.type.match("image.*")) {
                            processed++;
                            return;
                        }
                        
                        const reader = new FileReader();
                        reader.onload = function (e) {
                            const thumb = document.createElement("div");
                            thumb.className = "preview-thumb";
                            thumb.innerHTML = `
                                <img src="${e.target.result}" alt="Preview">
                                <button type="button" data-index="${index}">&times;</button>
                            `;
                            preview.appendChild(thumb);
                            
                            processed++;
                            if (processed === totalFiles) {
                                hideProcessing();
                            }
                        };
                        
                        reader.onerror = function() {
                            processed++;
                            if (processed === totalFiles) {
                                hideProcessing();
                            }
                        };
                        
                        reader.readAsDataURL(file);
                    });
                    
                    // Hide if no valid images were found
                    if (processed === totalFiles) {
                        hideProcessing();
                    }
                }, 100);
            });

            // === Remove image from preview
            preview.addEventListener("click", function (e) {
                if (e.target.tagName === "BUTTON") {
                    showProcessing("Updating thumbnails...");
                    
                    setTimeout(() => {
                        const index = parseInt(e.target.getAttribute("data-index"));
                        filesArray.splice(index, 1);
                        preview.innerHTML = "";
                        
                        filesArray.forEach((file, index) => {
                            const reader = new FileReader();
                            reader.onload = function (e) {
                                const thumb = document.createElement("div");
                                thumb.className = "preview-thumb";
                                thumb.innerHTML = `
                                    <img src="${e.target.result}" alt="Preview">
                                    <button type="button" data-index="${index}">&times;</button>
                                `;
                                preview.appendChild(thumb);
                            };
                            reader.readAsDataURL(file);
                        });
                        
                        const dt = new DataTransfer();
                        filesArray.forEach(file => dt.items.add(file));
                        input.files = dt.files;
                        
                        hideProcessing();
                    }, 100);
                }
            });

            // === Handle form submission
            form.addEventListener("submit", function (e) {
                const validFiles = Array.from(input.files).filter(file => file.type.match("image.*"));
                if (validFiles.length === 0) return;

                e.preventDefault();
                showProcessing("Uploading images...");

                const uploads = [];
                let completed = 0;
                let hasSubmitted = false;

                validFiles.forEach((file) => {
                    const reader = new FileReader();
                    reader.onload = function (event) {
                        uploads.push(event.target.result);
                        completed++;
                        if (completed === validFiles.length && !hasSubmitted) {
                            hasSubmitted = true;
                            hiddenField.value = JSON.stringify(uploads);
                            form.submit();
                        }
                    };
                    reader.onerror = function () {
                        console.error("Error reading", file.name);
                        completed++;
                    };
                    reader.readAsDataURL(file);
                });
            });
        });
        </script>';

    }

        echo '<p><button type="submit" style="background-color:blue;padding:10px;color:white; border-radius: 25px;
  width: 200px;margin:0 auto;cursor:pointer;
font-size:18px;">' . ($editing ? 'Update' : 'Add') . '</button></p> ';
echo '<p><a href="' . esc_url(remove_query_arg('edit_thing')) . '" style="font-size:12px;">Cancel</a></p>';


  echo "<div style='font-size:9px;text-align:right'>$using</div>\n\r\n\r\n\r";

        echo "</form></div></div>\n\r\n\r";

        echo '<script>
        document.addEventListener("DOMContentLoaded", function () {
            document.querySelectorAll(".show-firefly-form").forEach(link => {
                link.addEventListener("click", function (e) {
                    e.preventDefault();
                    const target = document.getElementById(this.dataset.target);
                    if (target) target.style.display = "block";
                });
            });
            document.querySelectorAll(".cancel-firefly-form").forEach(link => {
                link.addEventListener("click", function (e) {
                    e.preventDefault();
                    const form = this.closest(".firefly-admin-4");
                    if (form) form.style.display = "none";
                });
            });

            if (window.location.search.includes("edit_thing=")) {
                const targetForm = document.querySelector(".firefly-admin-4");
                if (targetForm) targetForm.scrollIntoView({ behavior: "smooth" });
            }
        });
        </script>';
    }


    
if (function_exists('firefly_things_order_insert_controls')) {
    firefly_things_order_insert_controls($slug);
}


// there are no posts so stop the page after showing the admin form

if ($therearenopostshere) {
    return;
}

$query_args = [
    'post_type'      => 'post',
    'posts_per_page' => -1,
    'orderby'        => 'title',
    'order'          => 'ASC',
    'meta_query'     => [
        [
            'key'     => '_is_thing',
            'value'   => '1',
            'compare' => '=',
        ]
    ],
];




if ( current_user_can( 'manage_options' )) {
    // Admins (while links are visible) → include drafts
    $query_args['post_status'] = [ 'publish', 'draft' ];
} else {
    // Everyone else → published only
    $query_args['post_status'] = 'publish';
}



// ✅ Force post list to only include Plan B's matches
if (!empty($plan_b_post_ids)) {

   // echo "<h1>1746 - plan B</h1>";
    $query_args['post__in'] = $plan_b_post_ids;

  //  $slug = firefly_find_slug_for_subcategory($show);
   // echo "<h1>1. The slug is $slug</h1>";

}
else
{ // echo "<h1>2. The slug is $slug</h1>";
}


// Handle both category slug or subcategory filter
if (!empty($slug)) {
    $category = get_category_by_slug($slug);
    if ($category) {
        $query_args['category__in'] = [$category->term_id];
    } else {
        // It's a subcategory (post_meta) or multiple
        $subcats = array_map('sanitize_title', array_map('trim', explode(',', $slug)));
        foreach ($subcats as $subcat) {
            $query_args['meta_query'][] = [
                'key'     => $subcat,
                'value'   => '1',
                'compare' => '='
            ];
        }
    }
}

// Let plugin override ordering if available
if (function_exists('firefly_things_order_update_query')) {
    firefly_things_order_update_query($query_args);
}

$query = new WP_Query($query_args);


      $meta = get_post_meta(get_the_ID());




    $layout = get_theme_mod("firefly_thing_layout_$slug", 'panels-below'); // panels-below, panels-right, list
//echo "<h1>3. The layout is $layout </h1>";


    $template_file = get_stylesheet_directory() . "/firefly-thing-style-{$layout}.php";

    if (file_exists($template_file)) {
        include $template_file;
    } else {
        echo "<p>Layout style not found: firefly-thing-style-{$layout}.php</p>";
    }

    return ob_get_clean();
});

//=============================================================
// add a thing code
//=============================================================
add_action('admin_post_add_thing', function () {
    // Initialize variables
    $post_id = 0;
    $redirect_url = wp_get_referer();
    
    try {
        // === 1. Security Check ===
        if (!current_user_can('manage_options') || 
            empty($_POST['_wpnonce']) || 
            !wp_verify_nonce($_POST['_wpnonce'], 'firefly_add_thing')) {
            throw new Exception('Unauthorized request');
        }

        // === 2. Validate Inputs ===
        $title = sanitize_text_field($_POST['thing_title'] ?? '');
        $content = wp_kses_post($_POST['thing_content'] ?? '');
        $term_id = isset($_POST['thing_category']) ? (int) $_POST['thing_category'] : 0;
        $meta = isset($_POST['thing_meta']) && is_array($_POST['thing_meta']) ? $_POST['thing_meta'] : [];

        if (!$term_id || !$title) {
            throw new Exception('Missing required fields');
        }

        // === 3. Create Post ===
        $post_id = wp_insert_post([
            'post_type' => 'post',
            'post_title' => $title,
            'post_content' => $content,
            'post_status'  => sanitize_key( $_POST['thing_status'] ?? 'draft' ),
            'post_category' => [$term_id],
        ], true);

        if (is_wp_error($post_id)) {
            throw new Exception('Post creation failed: ' . $post_id->get_error_message());
        }




// === 4. Handle subcategory checkboxes FIRST ===
$slug = get_post_field('post_name', $post_id); // use the post slug as a fallback
$subcategories_raw = get_theme_mod("firefly_thing_subcategories_$slug", '');
$subcategories = array_filter(array_map('trim', explode("\n", $subcategories_raw)));

foreach ($subcategories as $subcat) {
    $key = sanitize_title($subcat);
    // If not set in POST, it's unchecked → save as 0
    if (!isset($_POST['thing_meta'][$key])) {
        update_post_meta($post_id, $key, 0);
    }
}



// === 5. Save All Other Metadata ===
foreach ($meta as $key => $value) {
    update_post_meta($post_id, sanitize_key($key), sanitize_text_field($value));
}
update_post_meta($post_id, '_is_thing', '1');


// NEW: save overlay text + style
$ov_text = isset($_POST['firefly_overlay_text'])
  ? sanitize_text_field(wp_unslash($_POST['firefly_overlay_text']))
  : '';

$ov_style = isset($_POST['firefly_overlay_style'])
  ? sanitize_text_field($_POST['firefly_overlay_style'])
  : 'green';

update_post_meta($post_id, 'firefly_overlay_text',  $ov_text);
update_post_meta($post_id, 'firefly_overlay_style', $ov_style);




        // === 5. Handle Image Uploads - Wrapped in separate try-catch ===
        $attachment_ids = [];
        
        // A. Handle base64 gallery upload
        if (!empty($_POST['thing_gallery_data'])) {
            try {
                $json_raw = $_POST['thing_gallery_data'];
                if (!is_string($json_raw)) {
                    $json_raw = json_encode($json_raw);
                }
                
                if (function_exists('firefly_handle_gallery_upload')) {
                    $gallery_ids = firefly_handle_gallery_upload($post_id, stripslashes($json_raw));
                    if (is_array($gallery_ids)) {
                        $attachment_ids = array_merge($attachment_ids, $gallery_ids);
                    }
                }
            } catch (Exception $e) {
                error_log('Base64 image upload failed: ' . $e->getMessage());
            }
        }

        // B. Handle traditional file upload
        
        if (!empty($_FILES['thing_image']) && isset($_FILES['thing_image']['name'][0])) {
            try {
                require_once ABSPATH . 'wp-admin/includes/file.php';
                require_once ABSPATH . 'wp-admin/includes/media.php';
                require_once ABSPATH . 'wp-admin/includes/image.php';

               foreach ( $_FILES['thing_image']['name'] as $key => $value ) {
	if ( $_FILES['thing_image']['error'][ $key ] === UPLOAD_ERR_OK ) {

		$file = [
			'name'     => $_FILES['thing_image']['name'][ $key ],
			'type'     => $_FILES['thing_image']['type'][ $key ],
			'tmp_name' => $_FILES['thing_image']['tmp_name'][ $key ],
			'error'    => $_FILES['thing_image']['error'][ $key ],
			'size'     => $_FILES['thing_image']['size'][ $key ],
		];

		$attachment_id = media_handle_sideload( $file, $post_id );

		if ( ! is_wp_error( $attachment_id ) ) {

			$attachment_ids[] = $attachment_id;   // keep the ID for your gallery meta ↓

			/* ───── set / update the ALT text ───── */
			$ref = trim( get_post_meta( $post_id, 'ref', true ) );
			$alt = trim( ( $ref ? $ref . ' ' : '' ) . get_the_title( $post_id ) );

			if ( $alt !== '' ) {
				// always update – remove `true` so an empty/old alt gets replaced
				update_post_meta(
					$attachment_id,
					'_wp_attachment_image_alt',
					sanitize_text_field( $alt )
				);
			}
		}
	}
}

            } catch (Exception $e) {
                error_log('File upload failed: ' . $e->getMessage());
            }
        }

        // === 6. Finalize Images ===
        if (!empty($attachment_ids)) {
            try {
                // Set featured image
                $set_thumbnail = set_post_thumbnail($post_id, $attachment_ids[0]);
                
                // Save gallery meta
                update_post_meta($post_id, 'thing_gallery', $attachment_ids);
            } catch (Exception $e) {
                error_log('Image finalization failed: ' . $e->getMessage());
            }
        }

        // === 7. Successful Redirect ===
        $redirect_url = add_query_arg('firefly_success', '1', $redirect_url);

    } catch (Exception $e) {
        // If post was created but other parts failed, include post ID in redirect
        if ($post_id) {
            $redirect_url = add_query_arg('firefly_post_id', $post_id, $redirect_url);
        }
        
        $redirect_url = add_query_arg([
            'firefly_error' => '1',
            'message' => urlencode($e->getMessage())
        ], $redirect_url);
    }

    wp_redirect($redirect_url);
    exit;
});




add_action('wp_head', 'firefly_thing_custom_styles');

function firefly_thing_custom_styles() {
    echo "
    <style>
    .firefly-checkbox-grid {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
        gap: 10px 20px;
        padding: 10px 0;
    }
    .firefly-checkbox-grid label {
        display: flex;
        align-items: center;
        gap: 6px;
        font-size: 14px;
        white-space: normal;
        line-height: 1.3;
    }
    </style>";
}



add_action('admin_post_update_thing', function () {
    // 1. Verify required fields exist
    if (!isset($_POST['thing_id'], $_POST['_wpnonce'])) {
        wp_die('Invalid request data', 400);
    }

    // 2. Sanitize and validate post ID
    $post_id = absint($_POST['thing_id']);
    if (!$post_id) {
        wp_die('Invalid item ID', 400);
    }

    // 3. Verify nonce
    $nonce_action = 'firefly_update_thing_' . $post_id;
    if (!wp_verify_nonce($_POST['_wpnonce'], $nonce_action)) {
        wp_die('Security check failed. Please try again.', 403);
    }

    // 4. Check user capabilities
    if (!current_user_can('edit_post', $post_id)) {
        wp_die('You do not have permission to edit this item.', 403);
    }

    // 5. Process the form data
    $title = sanitize_text_field($_POST['thing_title'] ?? '');
    $content = wp_kses_post($_POST['thing_content'] ?? '');
    $term_id = absint($_POST['thing_category'] ?? 0);
    $meta = isset($_POST['thing_meta']) && is_array($_POST['thing_meta']) ? $_POST['thing_meta'] : [];


    // Determine slug from category
$categories = get_the_category($post_id);
$slug = (!empty($categories)) ? $categories[0]->slug : '';

//$subcats_raw = get_theme_mod("firefly_thing_subcategories_$slug", '');
//$subcategories = array_filter(array_map('trim', explode("\n", $subcats_raw)));

foreach ($subcategories as $subcat) {
    $key = sanitize_title($subcat);
    if (!isset($meta[$key])) {
        $meta[$key] = 0;
    }
}




    // 6. Validate required fields
    if (empty($title) || !$term_id) {
        wp_die('Title and category are required fields.', 400);
    }

    // 7. Update the post

    $new_status = sanitize_key( $_POST['thing_status'] ?? 'draft' );


    $updated = wp_update_post([
        'ID' => $post_id,
        'post_title' => $title,
        'post_content' => $content,
        'post_status' => $new_status,
    ]);

    if (is_wp_error($updated)) {
        wp_die('Failed to update: ' . $updated->get_error_message(), 500);
    }


    // Ensure all checkboxes get set to 0 if not present in form submission
$checkbox_fields_raw = get_theme_mod("firefly_thing_fields_checkboxes_$slug", '');
$checkbox_fields = array_filter(array_map('trim', explode("\n", $checkbox_fields_raw)));

foreach ($checkbox_fields as $field_raw) {
    if (stristr($field_raw, "*")) continue; // skip section headings
    $key = thing_meta_key($field_raw);
    if (!isset($meta[$key])) {
        $meta[$key] = 0;
    }
}


    // 8. Update metadata
    foreach ($meta as $key => $value) {
        update_post_meta($post_id, sanitize_key($key), sanitize_text_field($value));
    }


    // NEW: save overlay text + style
$ov_text = isset($_POST['firefly_overlay_text'])
  ? sanitize_text_field(wp_unslash($_POST['firefly_overlay_text']))
  : '';

$ov_style = isset($_POST['firefly_overlay_style'])
  ? sanitize_text_field($_POST['firefly_overlay_style'])
  : 'green';


update_post_meta($post_id, 'firefly_overlay_text',  $ov_text);
update_post_meta($post_id, 'firefly_overlay_style', $ov_style);


    // 9. Redirect back
    $redirect_url = remove_query_arg(['edit_thing', 'updated', 'post_id'], wp_get_referer());
    wp_safe_redirect($redirect_url);
    exit;
  
});


function firefly_find_slug_for_subcategory($subcategory) {
    $mods = get_theme_mods();
    if (!$mods) return null;

    $subcategory = trim(strtolower($subcategory));

    foreach ($mods as $key => $value) {
        if (strpos($key, 'firefly_thing_subcategories_') === 0) {
            $slug = str_replace('firefly_thing_subcategories_', '', $key);
            $subcats = array_map('sanitize_title', array_map('trim', explode("\n", $value)));

            if (in_array($subcategory, $subcats)) {
                return $slug; // First matching slug found
            }
        }
    }

    return null;
}


add_action( 'admin_post_duplicate_thing', 'firefly_duplicate_thing' );

function firefly_duplicate_thing() {

    /*──── 1. Security ─────────────────────────────────────────────*/
    $orig_id = absint( $_GET['thing_id'] ?? 0 );
    $nonce   = $_GET['_wpnonce'] ?? '';

    if ( ! current_user_can( 'manage_options' ) ||
         ! $orig_id ||
         ! wp_verify_nonce( $nonce, 'duplicate_thing_' . $orig_id ) ) {
        wp_die( 'Invalid request', 403 );
    }

    /*──── 2. Fetch original post ─────────────────────────────────*/
    $orig = get_post( $orig_id );
    if ( ! $orig || $orig->post_type !== 'post' ) {
        wp_die( 'Original thing not found', 404 );
    }

    /*──── 3. Create the copy (draft) ─────────────────────────────*/
    $new_id = wp_insert_post( [
        'post_type'    => 'post',
        'post_title'   => $orig->post_title . ' (copy)',
        'post_content' => $orig->post_content,
        'post_status'  => 'draft',
        'post_category'=> wp_get_post_categories( $orig_id, [ 'fields' => 'ids' ] ),
    ], true );

    if ( is_wp_error( $new_id ) ) {
        wp_die( $new_id->get_error_message(), 500 );
    }

    /*──── 4. Copy ALL non-core meta values ───────────────────────*/
    foreach ( get_post_meta( $orig_id ) as $key => $vals ) {
        if ( in_array( $key, [ '_edit_lock', '_edit_last' ], true ) ) continue;
        foreach ( $vals as $v ) add_post_meta( $new_id, $key, maybe_unserialize( $v ) );
    }

    /*──── 5. Duplicate attachments – featured & gallery ─────────*/
    require_once ABSPATH . 'wp-admin/includes/file.php';
    require_once ABSPATH . 'wp-admin/includes/image.php';

    $map         = [];                       // old-ID → new-ID
    $uploads     = wp_upload_dir();

    $gallery_ids = (array) get_post_meta( $orig_id, 'thing_gallery', true );
    $featured_id = get_post_thumbnail_id( $orig_id );

    $attach_ids  = array_unique( array_merge( $gallery_ids, $featured_id ? [ $featured_id ] : [] ) );

    foreach ( $attach_ids as $att_id ) {

        $src_path = get_attached_file( $att_id );
        if ( ! $src_path || ! file_exists( $src_path ) ) continue;

        /* copy file to current Y/m folder with unique name */
        $filename   = wp_unique_filename( $uploads['path'], basename( $src_path ) );
        $dest_path  = $uploads['path'] . '/' . $filename;
        copy( $src_path, $dest_path );

        /* register new attachment */
        $filetype  = wp_check_filetype( $dest_path );
        $attach_id = wp_insert_attachment( [
            'post_mime_type' => $filetype['type'],
            'post_title'     => sanitize_file_name( $filename ),
            'post_status'    => 'inherit',
            'post_parent'    => $new_id,
        ], $dest_path, $new_id );

        $meta = wp_generate_attachment_metadata( $attach_id, $dest_path );
        wp_update_attachment_metadata( $attach_id, $meta );

        $map[ $att_id ] = $attach_id;        // remember new ID
    }

    /* rewrite gallery + thumbnail meta --------------------------*/
    if ( $featured_id && isset( $map[ $featured_id ] ) ) {
        set_post_thumbnail( $new_id, $map[ $featured_id ] );
    }
    if ( $gallery_ids ) {
        $new_gallery = array_map(
            fn( $id ) => $map[ $id ] ?? $id,   // fall back if copy failed
            $gallery_ids
        );
        update_post_meta( $new_id, 'thing_gallery', $new_gallery );
    }

    /*──── 6. Redirect user to edit new thing (front-end) ────────*/
    $ref = wp_get_referer() ?: home_url();
    $ref = add_query_arg( 'edit_thing', $new_id, $ref );
    wp_safe_redirect( $ref );
    exit;
}


add_action( 'wp_ajax_firefly_save_gallery_order',        'firefly_save_gallery_order' );
add_action( 'wp_ajax_nopriv_firefly_save_gallery_order', 'firefly_save_gallery_order' );

function firefly_save_gallery_order() {

    // ----------- basic sanity --------------------------------------------
    if ( empty( $_POST['post_id'] ) || empty( $_POST['order'] ) ) {
        wp_send_json_error( 'missing_params', 400 );
    }

    $post_id  = (int) $_POST['post_id'];
    $order    = array_map( 'intval', (array) $_POST['order'] );
    $featured = (int) ( $_POST['featured'] ?? 0 );

    // ----------- security -------------------------------------------------
    if ( ! wp_verify_nonce( $_POST['_wpnonce'] ?? '', "firefly_sort_{$post_id}" ) ) {
        wp_send_json_error( 'bad_nonce', 401 );
    }

    if ( ! current_user_can( 'edit_post', $post_id ) ) {
        wp_send_json_error( 'no_capability', 403 );
    }

    // ----------- persist gallery order -----------------------------------
    // Save the array of attachment IDs so your display code can read it.
    update_post_meta( $post_id, 'thing_gallery', $order );

    // If your front-end gallery is still using get_attached_media(),
    // also bump each attachment’s menu_order ↓↓↓ (skip if not needed)
    foreach ( $order as $pos => $att_id ) {
        wp_update_post( [
            'ID'         => $att_id,
            'menu_order' => $pos,
        ] );
    }

    // ----------- featured image ------------------------------------------
    if ( $featured && get_post_thumbnail_id( $post_id ) !== $featured ) {
        set_post_thumbnail( $post_id, $featured );
    }

    // ----------- done -----------------------------------------------------
    wp_send_json_success();
}

if ( ! function_exists( 'thing_meta_key' ) ) {
    function thing_meta_key( $label ) {
        // keep only a–z and 0–9
        return preg_replace( '/[^a-z0-9]/i', '', strtolower( $label ) );
    }
}


// mark things as sold or not sold

add_action( 'init', function() {
    if ( isset( $_GET['toggle_sold'] ) ) {
        $post_id = intval( $_GET['toggle_sold'] );
        if ( ! wp_verify_nonce( $_GET['_wpnonce'] ?? '', 'toggle_sold_' . $post_id ) ) {
            return;
        }
        if ( ! current_user_can( 'edit_post', $post_id ) ) {
            return;
        }

        // Toggle sold status
        if ( get_post_meta( $post_id, 'sold', true ) ) {
            delete_post_meta( $post_id, 'sold' );
        } else {
            update_post_meta( $post_id, 'sold', '1' );
        }

        // Redirect to remove query args
        wp_redirect( remove_query_arg( array( 'toggle_sold', '_wpnonce' ) ) );
        exit;
    }
});



// mark things as sold ourt or available

add_action( 'init', function() {
    if ( isset( $_GET['toggle_soldout'] ) ) {
        $post_id = intval( $_GET['toggle_soldout'] );
        if ( ! wp_verify_nonce( $_GET['_wpnonce'] ?? '', 'toggle_soldout_' . $post_id ) ) {
            return;
        }
        if ( ! current_user_can( 'edit_post', $post_id ) ) {
            return;
        }

        // Toggle sold status
        if ( get_post_meta( $post_id, 'soldout', true ) ) {
            delete_post_meta( $post_id, 'soldout' );
        } else {
            update_post_meta( $post_id, 'soldout', '1' );
        }

        // Redirect to remove query args
        wp_redirect( remove_query_arg( array( 'toggle_soldout', '_wpnonce' ) ) );
        exit;
    }
});
