<?php


//ini_set('display_errors', 1);
//ini_set('display_startup_errors', 1);
//error_reporting(E_ALL);

/* =====================================================================
   Firefly Newsletters / Documents  –  “show" attribute support
   ---------------------------------------------------------------------
   Shortcode examples
     [newsletters]              → show ALL items on the page  (default)
     [newsletters show="2024"]  → show only items where 'show' == 2024
     [newsletters show="2023"]  → show only items where 'show' == 2023
   ===================================================================== */

/*--------------------------------------------------------------
  Register shortcode + upload handler
--------------------------------------------------------------*/
add_shortcode( 'newsletters', 'firefly_render_newsletters' );
add_shortcode( 'documents',  'firefly_render_newsletters' );
add_shortcode( 'PDFs',       'firefly_render_newsletters' );

add_action( 'admin_post_add_newsletter',        'firefly_handle_newsletter_upload' );
add_action( 'admin_post_nopriv_add_newsletter', fn() => wp_die( 'Unauthorized' ) );





function firefly_get_document_colour_choices_flat() {
    return [
        'colour1' => 'Colour 1',
        'colour2' => 'Colour 2',
        'colour3' => 'Colour 3',
        'colour4' => 'Colour 4',
        'black'   => 'Black',
        'white'   => 'White'
    ];
}

function firefly_get_colour_value($setting) {
    $colour_map = [
        'colour1' => get_theme_mod('firefly_colour_1', '#0b3d32'),
        'colour2' => get_theme_mod('firefly_colour_2', '#65b32e'),
        'colour3' => get_theme_mod('firefly_colour_3', '#d3f5d1'),
        'colour4' => get_theme_mod('firefly_colour_4', '#e4f1ce'),
        'black'   => '#000000',
        'white'   => '#ffffff'
    ];
    $choice = get_theme_mod($setting, 'white');
    return $colour_map[$choice] ?? '#ffffff';
}

// Register shortcode
add_shortcode('newsletters', 'firefly_render_newsletters');

// Handle form submission
add_action('admin_post_add_newsletter', 'firefly_handle_newsletter_upload');
add_action('admin_post_nopriv_add_newsletter', function() { wp_die('Unauthorized'); });


add_action('customize_register', 'firefly_customize_documents_section');




function firefly_customize_documents_section($wp_customize) {

    // Add section
    $wp_customize->add_section('firefly_documents_section', array(
        'title'       => __('Firefly Documents', 'firefly'),
        'priority'    => 80,
        'description' => __('Customize options for Firefly documents such as newsletters.', 'firefly'),
    ));

    
    //===========================
    // Shared choice sets
    //===========================
    $spacing_choices = [];
    for ($i = 0; $i <= 30; $i++) {
        $spacing_choices["{$i}px"] = "{$i}px";
    }

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

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

    $newsletter_thumb_choices = [];
    for ($i = 25; $i <= 500; $i += 5) {
        $newsletter_thumb_choices["{$i}px"] = "{$i}px";
    }

    $colour_choices_text = array(
        'colour1' => array('color' => get_theme_mod('firefly_colour_1', '#0b3d32'), 'label' => 'Colour 1'),
        'colour2' => array('color' => get_theme_mod('firefly_colour_2', '#65b32e'), 'label' => 'Colour 2'),
        'colour3' => array('color' => get_theme_mod('firefly_colour_3', '#d3f5d1'), 'label' => 'Colour 3'),
        'colour4' => array('color' => get_theme_mod('firefly_colour_4', '#e4f1ce'), 'label' => 'Colour 4'),
        'black'   => array('color' => '#000000', 'label' => 'Black'),
        'white'   => array('color' => '#ffffff', 'label' => 'White'),
    );

    $radio_choices = array();
    foreach ($colour_choices_text as $value => $info) {
        $color = esc_attr($info['color']);
        $label = esc_html($info['label']);
        $radio_choices[$value] = '<span style="background:' . $color . ';
            display:inline-block;width:12px;height:12px;
            border:1px solid #444;margin-right:6px;"></span>' . $label;
    }

    $borders = [
        '0px' => '0px',
        '1px' => '1px',
        '2px' => '2px',
        '3px' => '3px',
        '4px' => '4px',
    ];
// ===========================
// Group: Documents Section (newsletter-container)
// ===========================
$wp_customize->add_setting('firefly_heading_container_section', array(
    'sanitize_callback' => '__return_null',
));
$wp_customize->add_control(new WP_Customize_Control($wp_customize, 'firefly_heading_container_section', array(
    'settings' => 'firefly_heading_container_section',
    'label'    => __('Documents Container', 'firefly'),
    'section'  => 'firefly_documents_section',
    'type'     => 'hidden',
    'description' => '<hr><h1 style="font-weight:bold;">Document Container Settings</h1>',
)));



    $wp_customize->add_setting('firefly_document_background', array(
        'default' => 'white',
        'sanitize_callback' => 'sanitize_text_field',
    ));
    $wp_customize->add_control(new Firefly_Radio_Colour_Control_text($wp_customize, 'firefly_document_background_control', array(
          'settings' => 'firefly_document_background', // Link to setting
        'label'    => __('Background colour of document block', 'firefly'),
        'section'  => 'firefly_documents_section',
        'settings' => 'firefly_document_background',
        'choices'  => $colour_choices_text,
    )));

// Container Margins
$wp_customize->add_setting('firefly_container_margin_top', array(
    'default' => '10px',
    'sanitize_callback' => 'sanitize_text_field',
));
$wp_customize->add_control('firefly_container_margin_top_control', array(
    'settings' => 'firefly_container_margin_top',
    'label'    => __('Documents container - Margin Top', 'firefly'),
    'section'  => 'firefly_documents_section',
    'type'     => 'select',
    'choices'  => $padding_options,
));

$wp_customize->add_setting('firefly_container_margin_bottom', array(
    'default' => '10px',
    'sanitize_callback' => 'sanitize_text_field',
));
$wp_customize->add_control('firefly_container_margin_bottom_control', array(
    'settings' => 'firefly_container_margin_bottom',
    'label'    => __('Documents container - Margin Bottom', 'firefly'),
    'section'  => 'firefly_documents_section',
    'type'     => 'select',
    'choices'  => $padding_options,
));


// Container Padding
$wp_customize->add_setting('firefly_container_padding_top', array(
    'default' => '0px',
    'sanitize_callback' => 'sanitize_text_field',
));
$wp_customize->add_control('firefly_container_padding_top_control', array(
    'settings' => 'firefly_container_padding_top',
    'label'    => __('Documents container - Padding Top', 'firefly'),
    'section'  => 'firefly_documents_section',
    'type'     => 'select',
    'choices'  => $padding_options,
));

$wp_customize->add_setting('firefly_container_padding_bottom', array(
    'default' => '0px',
    'sanitize_callback' => 'sanitize_text_field',
));
$wp_customize->add_control('firefly_container_padding_bottom_control', array(
    'settings' => 'firefly_container_padding_bottom',
    'label'    => __('Documents container - Padding Bottom', 'firefly'),
    'section'  => 'firefly_documents_section',
    'type'     => 'select',
    'choices'  => $padding_options,
));

$wp_customize->add_setting('firefly_container_padding', array(
    'default' => '0px',
    'sanitize_callback' => 'sanitize_text_field',
));
$wp_customize->add_control('firefly_container_padding_control', array(
    'settings' => 'firefly_container_padding',
    'label'    => __('Documents container - Padding left and right', 'firefly'),
    'section'  => 'firefly_documents_section',
    'type'     => 'select',
    'choices'  => $padding_options,
));


// ===========================
// Group: Documents Panel (newsletter-panel)
// ===========================
$wp_customize->add_setting('firefly_heading_panel_section', array(
    'sanitize_callback' => '__return_null',
));
$wp_customize->add_control(new WP_Customize_Control($wp_customize, 'firefly_heading_panel_section', array(
    'settings' => 'firefly_heading_panel_section',
    'label'    => __('Document Panels', 'firefly'),
    'section'  => 'firefly_documents_section',
    'type'     => 'hidden',
    'description' => '<hr><h1 style="font-weight:bold;">Panel Settings</h1>',
)));


   $wp_customize->add_setting('firefly_document_panel_background', array(
        'default' => 'white',
        'sanitize_callback' => 'sanitize_text_field',
    ));
    $wp_customize->add_control(new Firefly_Radio_Colour_Control_text($wp_customize, 'firefly_document_panel_background_control', array(
        'settings' => 'firefly_document_panel_background', // Link to setting
        'label'    => __('Background colour of document panels', 'firefly'),
        'section'  => 'firefly_documents_section',
        'settings' => 'firefly_document_panel_background',
        'choices'  => $colour_choices_text,
    )));


    //===========================
    // Group: Border
    //===========================
    $wp_customize->add_setting('firefly_document_border', array(
        'default' => '0px',
        'sanitize_callback' => 'sanitize_text_field',
    ));
    $wp_customize->add_control('firefly_document_border_control', array(
         'settings' => 'firefly_document_border', // Link to setting
        'label'    => __('Border around document (in px)', 'firefly'),
        'section'  => 'firefly_documents_section',
        'type'     => 'select',
        'choices'  => $borders,
    ));

// Panel Margins
$wp_customize->add_setting('firefly_panel_margin_top', array(
    'default' => '10px',
    'sanitize_callback' => 'sanitize_text_field',
));
$wp_customize->add_control('firefly_panel_margin_top_control', array(
    'settings' => 'firefly_panel_margin_top',
    'label'    => __('Document panel - margin top', 'firefly'),
    'section'  => 'firefly_documents_section',
    'type'     => 'select',
    'choices'  => $padding_options,
));

$wp_customize->add_setting('firefly_panel_margin_bottom', array(
    'default' => '10px',
    'sanitize_callback' => 'sanitize_text_field',
));
$wp_customize->add_control('firefly_panel_margin_bottom_control', array(
    'settings' => 'firefly_panel_margin_bottom',
    'label'    => __('Document panel - margin bottom', 'firefly'),
    'section'  => 'firefly_documents_section',
    'type'     => 'select',
    'choices'  => $padding_options,
));

$wp_customize->add_setting('firefly_panel_margin', array(
    'default' => '10px',
    'sanitize_callback' => 'sanitize_text_field',
));
$wp_customize->add_control('firefly_panel_margin_control', array(
    'settings' => 'firefly_panel_margin',
    'label'    => __('Document panel - margin left and right', 'firefly'),
    'section'  => 'firefly_documents_section',
    'type'     => 'select',
    'choices'  => $padding_options,
));


// Panel Padding
$wp_customize->add_setting('firefly_panel_padding_top', array(
    'default' => '10px',
    'sanitize_callback' => 'sanitize_text_field',
));
$wp_customize->add_control('firefly_panel_padding_top_control', array(
    'settings' => 'firefly_panel_padding_top',
    'label'    => __('Document panel - padding top', 'firefly'),
    'section'  => 'firefly_documents_section',
    'type'     => 'select',
    'choices'  => $padding_options,
));

$wp_customize->add_setting('firefly_panel_padding_bottom', array(
    'default' => '10px',
    'sanitize_callback' => 'sanitize_text_field',
));
$wp_customize->add_control('firefly_panel_padding_bottom_control', array(
    'settings' => 'firefly_panel_padding_bottom',
    'label'    => __('Document panel - padding bottom', 'firefly'),
    'section'  => 'firefly_documents_section',
    'type'     => 'select',
    'choices'  => $padding_options,
));

$wp_customize->add_setting('firefly_panel_padding', array(
    'default' => '10px',
    'sanitize_callback' => 'sanitize_text_field',
));
$wp_customize->add_control('firefly_panel_padding_control', array(
    'settings' => 'firefly_panel_padding',
    'label'    => __('Document panel - Padding left and right', 'firefly'),
    'section'  => 'firefly_documents_section',
    'type'     => 'select',
    'choices'  => $padding_options,
));



// Panel Border
$wp_customize->add_setting('firefly_panel_border_width', array(
    'default' => '1px',
    'sanitize_callback' => 'sanitize_text_field',
));
$wp_customize->add_control('firefly_panel_border_width_control', array(
    'settings' => 'firefly_panel_border_width',
    'label'    => __('Border Width', 'firefly'),
    'section'  => 'firefly_documents_section',
    'type'     => 'select',
    'choices'  => $borders,
));



        $wp_customize->add_setting('firefly_document_line_colour', array(
        'default' => 'white',
        'sanitize_callback' => 'sanitize_text_field',
    ));
    $wp_customize->add_control(new Firefly_Radio_Colour_Control_text($wp_customize, 'firefly_document_line_colour_control', array(
              'settings' => 'firefly_document_line_colour', // Link to setting
        'label'    => __('Line colour', 'firefly'),
        'section'  => 'firefly_documents_section',
        'settings' => 'firefly_document_line_colour',
        'choices'  => $colour_choices_text,
    )));

    $wp_customize->add_setting('newsletter-panel-width', array(
        'default' => '250px',
    
    ));
    $wp_customize->add_control('newsletter-panel-width_control', array(
        'label'    => __('Maximum width of document panel', 'firefly'),
        'section'  => 'firefly_documents_section',
        'settings' => 'newsletter-panel-width',
        'type'     => 'select',
        'choices'  => $newsletter_thumb_choices,
    ));

        $wp_customize->add_setting('newsletter-panel-height', array(
        'default' => '350px',
        'sanitize_callback' => 'sanitize_text_field',
    ));
    $wp_customize->add_control('newsletter-panel-height_control', array(
        'label'    => __('Minimum height of document panel', 'firefly'),
        'section'  => 'firefly_documents_section',
        'settings' => 'newsletter-panel-height',
        'type'     => 'select',
        'choices'  => $newsletter_thumb_choices,
    ));


    
// ===========================
// Group: Document Image (newsletter-thumbnail)
// ===========================
$wp_customize->add_setting('firefly_heading_image_section', array(
    'sanitize_callback' => '__return_null',
));
$wp_customize->add_control(new WP_Customize_Control($wp_customize, 'firefly_heading_image_section', array(
    'settings' => 'firefly_heading_image_section',
    'label'    => __('Document Image', 'firefly'),
    'section'  => 'firefly_documents_section',
    'type'     => 'hidden',
    'description' => '<hr><h1 style="font-weight:bold;">Image Settings</h1>',
)));



   //===========================
    // Group: Thumbnails
    //===========================


        $wp_customize->add_setting('newsletter-thumbnail-width', array(
        'default' => '250px',
        'sanitize_callback' => 'sanitize_text_field',
    ));
    $wp_customize->add_control('newsletter-thumbnail-width_control', array(
        'label'    => __('Width of document thumbnail', 'firefly'),
        'section'  => 'firefly_documents_section',
        'settings' => 'newsletter-thumbnail-width',
        'type'     => 'select',
        'choices'  => $newsletter_thumb_choices,
    ));



    $wp_customize->add_setting('newsletter-thumbnail-height', array(
        'default' => '350px',
        'sanitize_callback' => 'sanitize_text_field',
    ));
    $wp_customize->add_control('newsletter-thumbnail-height_control', array(
        'label'    => __('Height of document thumbnail', 'firefly'),
        'section'  => 'firefly_documents_section',
        'settings' => 'newsletter-thumbnail-height',
        'type'     => 'select',
        'choices'  => $newsletter_thumb_choices,
    ));




//===========================
// New Checkbox: Force Fixed Size
//===========================
$wp_customize->add_setting('newsletter-force-fixed-size', array(
    'default'           => false,
    'sanitize_callback' => 'wp_validate_boolean',
));
$wp_customize->add_control('newsletter-force-fixed-size_control', array(
    'label'    => __('Force all thumbnails to be exactly this size (eg 200x290)', 'firefly'),
    'section'  => 'firefly_documents_section',
    'settings' => 'newsletter-force-fixed-size',
    'type'     => 'checkbox',
));

// Image Padding


$wp_customize->add_setting('firefly_image_padding_top', array(
    'default' => '0px',
    'sanitize_callback' => 'sanitize_text_field',
));
$wp_customize->add_control('firefly_image_padding_top_control', array(
    'settings' => 'firefly_image_padding_top',
    'label'    => __('Image - padding top', 'firefly'),
    'section'  => 'firefly_documents_section',
    'type'     => 'select',
    'choices'  => $padding_options,
));

$wp_customize->add_setting('firefly_image_padding_bottom', array(
    'default' => '0px',
));
$wp_customize->add_control('firefly_image_padding_bottom_control', array(
    'settings' => 'firefly_image_padding_bottom',
    'label'    => __('Image padding bottom', 'firefly'),
    'section'  => 'firefly_documents_section',
    'type'     => 'select',
    'choices'  => $padding_options,
));

$wp_customize->add_setting('firefly_image_padding', array(
    'default' => '0px',
    'sanitize_callback' => 'sanitize_text_field',
));
$wp_customize->add_control('firefly_image_padding_control', array(
    'settings' => 'firefly_image_padding',
    'label'    => __('Image padding left and right', 'firefly'),
    'section'  => 'firefly_documents_section',
    'type'     => 'select',
    'choices'  => $padding_options,
));





// ===========================
// Group: Document Name (.newsletter-name)
// ===========================
$wp_customize->add_setting('firefly_heading_name_section', array(
    'sanitize_callback' => '__return_null',
));


$wp_customize->add_control(new WP_Customize_Control($wp_customize, 'firefly_heading_name_section', array(
    'settings' => 'firefly_heading_name_section',
    'label'    => __('Document Name', 'firefly'),
    'section'  => 'firefly_documents_section',
    'type'     => 'hidden',
    'description' => '<hr><h1 style="font-weight:bold;">Document Name Settings</h1>',
)));


   $wp_customize->add_setting('firefly_document_name_colour', array(
        'default' => 'white',
        'sanitize_callback' => 'sanitize_text_field',
    ));
    $wp_customize->add_control(new Firefly_Radio_Colour_Control_text($wp_customize, 'firefly_document_name_colour_control', array(
              'settings' => 'firefly_document_name_colour', // Link to setting
        'label'    => __('Document name colour', 'firefly'),
        'section'  => 'firefly_documents_section',
        'settings' => 'firefly_document_name_colour',
        'choices'  => $colour_choices_text,
    )));



// Heading Font Size
$heading_sizes = [];
for ($i = 9; $i <= 36; $i++) {
    $heading_sizes["{$i}px"] = "{$i}px";
}

$wp_customize->add_setting('firefly_document_title_size', array(
    'default' => '16px',
    'sanitize_callback' => 'sanitize_text_field',
));

$wp_customize->add_control('firefly_document_title_size_control', array(
    'settings' => 'firefly_document_title_size',
    'label'    => __('Document name font size', 'firefly'),
    'section'  => 'firefly_documents_section',
    'type'     => 'select',
    'choices'  => $heading_sizes,
));


// Document name leading (line-height)
$wp_customize->add_setting('firefly_document_title_leading', array(
    'default'           => '100%',
    'sanitize_callback' => 'sanitize_text_field',
));

$wp_customize->add_control('firefly_document_title_leading_control', array(
    'settings' => 'firefly_document_title_leading',
    'label'    => __('Document name leading', 'firefly'),
    'section'  => 'firefly_documents_section',
    'type'     => 'select',
    'choices'  => array(
        '100%' => '100%',
        '102%' => '102%',
        '104%' => '104%',
        '106%' => '106%',
        '108%' => '108%',
        '110%' => '110%',
        '112%' => '112%',
        '114%' => '114%',
        '116%' => '116%',
        '118%' => '118%',
        '120%' => '120%',
        '122%' => '122%',
        '124%' => '124%',
        '126%' => '126%',
        '128%' => '128%',
        '130%' => '130%',
        '132%' => '132%',
        '134%' => '134%',
        '136%' => '136%',
        '138%' => '138%',
        '140%' => '140%',
        '142%' => '142%',
        '144%' => '144%',
        '146%' => '146%',
        '148%' => '148%',
        '150%' => '150%',
            '152%' => '152%',
        '154%' => '154%',
        '156%' => '156%',
        '158%' => '158%',
        '160%' => '160%',
        '162%' => '162%',
        '164%' => '164%',
        '166%' => '166%',
        '168%' => '168%',
        '170%' => '170%',
        '172%' => '172%',
        '174%' => '174%',
        '176%' => '176%',
        '178%' => '178%',
        '180%' => '180%',
        '182%' => '182%',
        '184%' => '184%',
        '186%' => '186%',
        '188%' => '188%',
        '190%' => '190%',
        '192%' => '192%',
        '194%' => '194%',
        '196%' => '196%',
        '198%' => '198%',
        '200%' => '200%',
    ),
));


  // 1. Position of document name
    $wp_customize->add_setting('firefly_document_title_position', array(
        'default'           => 'above',
        'sanitize_callback' => function($value) {
            return in_array($value, ['above', 'below']) ? $value : 'above';
        }
    ));
    $wp_customize->add_control('firefly_document_title_position_control', array(
        'label'    => __('Position of document name', 'firefly'),
        'section'  => 'firefly_documents_section',
        'settings' => 'firefly_document_title_position',
        'type'     => 'radio',
        'choices'  => array(
            'above' => 'Above image',
            'below' => 'Below image',
        )
    ));


// Name Padding
$wp_customize->add_setting('firefly_name_padding_top', array(
    'default' => '5px',
    'sanitize_callback' => 'sanitize_text_field',
));
$wp_customize->add_control('firefly_name_padding_top_control', array(
    'settings' => 'firefly_name_padding_top',
    'label'    => __('Document name - padding top', 'firefly'),
    'section'  => 'firefly_documents_section',
    'type'     => 'select',
    'choices'  => $padding_options,
));

$wp_customize->add_setting('firefly_name_padding_bottom', array(
    'default' => '5px',
    'sanitize_callback' => 'sanitize_text_field',
));
$wp_customize->add_control('firefly_name_padding_bottom_control', array(
    'settings' => 'firefly_name_padding_bottom',
    'label'    => __('Document name - padding bottom', 'firefly'),
    'section'  => 'firefly_documents_section',
    'type'     => 'select',
    'choices'  => $padding_options,
));






$wp_customize->add_setting('newsletter-div-borders', array(
    'default'           => false,
    'sanitize_callback' => 'wp_validate_boolean',
));
$wp_customize->add_control('newsletter-div-borders_control', array(
    'label'    => __('Show borders on divs for debugging', 'firefly'),
    'section'  => 'firefly_documents_section',
    'settings' => 'newsletter-div-borders',
    'type'     => 'checkbox',
));
 
}




// Handle inline shortcode module deletion
add_action('template_redirect', function () {
    if (
        isset($_GET['delete_block']) &&
        $_GET['delete_block'] === '1' &&
        isset($_GET['block_type']) &&
        $_GET['block_type'] === 'shortcode' &&
        isset($_GET['shortcode']) &&
        $_GET['shortcode'] === 'newsletters' &&
        isset($_GET['block_id']) &&
        current_user_can('manage_options')
    ) {
        $post_id = get_the_ID();
        if (!$post_id && is_admin()) {
            $post_id = isset($_GET['post']) ? intval($_GET['post']) : 0;
        }

        if ($post_id) {
            $post = get_post($post_id);
            $block_id = sanitize_text_field($_GET['block_id']);
            $content = $post->post_content;

            // Match block with unique form ID
            $pattern = '/<!-- wp:shortcode -->\s*\[newsletters.*?' . preg_quote($block_id, '/') . '.*?<!-- \/wp:shortcode -->/is';

            if (preg_match($pattern, $content, $matches)) {
                $content = str_replace($matches[0], '', $content);
                wp_update_post([
                    'ID' => $post_id,
                    'post_content' => $content,
                ]);
            }

            wp_safe_redirect(remove_query_arg(['delete_block', 'block_type', 'shortcode', 'block_id']));
            exit;
        }
    }
});




/*--------------------------------------------------------------
  Shortcode renderer
--------------------------------------------------------------*/
// ================================================
//  Render shortcode output (COMPLETE, UPDATED)
//  Supports optional show="2024" style filtering
// ================================================
function firefly_render_newsletters( $atts ) {

	/* ----------  1. ATTRIBUTES & PREP  ---------- */
	$atts = shortcode_atts(
		[
			'what' => 'newsletter',   // label shown in the UI
			'show' => '',             // group filter – blank = show all
		],
		$atts,
		'newsletters'
	);

	$label       = ucfirst( $atts['what'] );
	$show_group  = trim( $atts['show'] );             // '' → no filter
	$page_id     = get_queried_object_id();
	$instance_id = 'ff-' . bin2hex( random_bytes( 4 ) ); // unique per-shortcode
	$items       = get_post_meta( $page_id, 'firefly_newsletters', true ) ?: [];

	ob_start();
	echo '<div class="wp-block-group"><div class="newsletter-container">';

	/* ----------  2. ADMIN UPLOAD FORM  ---------- */
	if ( current_user_can( 'manage_options' ) ) : ?>
		
			<div class="firefly-admin-1">
				<div class="firefly-admin-2">Firefly <?php echo esc_html( $label ); ?> options</div>
				<div class="firefly-admin-3">
					<a href="#" class="show-firefly-form" data-target="<?php echo esc_attr( $instance_id ); ?>">
						Add a <?php echo esc_html( $label ); ?>
					</a> | 	





<?php
// REPLACE your current reorder link + box + first <form> with this:

$reorder_box_id  = 'newsletter-reorder-box-'  . $instance_id;
$reorder_list_id = 'newsletter-reorder-list-' . $instance_id;
$reorder_btn_id  = 'toggle-newsletter-reorder-' . $instance_id;
?>

<a href="#" class="toggle-newsletter-reorder" id="<?php echo esc_attr($reorder_btn_id); ?>"
   data-target="<?php echo esc_attr($reorder_box_id); ?>">
  Reorder <?php echo esc_html($label); ?>s
</a>

<form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" enctype="multipart/form-data">
    <input type="hidden" name="filter" value="<?php echo esc_attr($show_group); ?>">


  <div id="<?php echo esc_attr($reorder_box_id); ?>" class="newsletter-reorder-box"
       style="display:none; margin-top:20px; padding:10px; border:1px solid #ccc; background:#fdfdfd;">

    <ul id="<?php echo esc_attr($reorder_list_id); ?>" class="newsletter-reorder-list"
        style="list-style:none; padding:0;">
      <?php foreach ( $items as $key => $item ) :
        // show-group filter so each instance only reorders its own set
        if ($show_group !== '' && (empty($item['show']) || strcasecmp($item['show'], $show_group) !== 0)) {
          continue;
        }
      ?>
        <li class="reorder-item" style="cursor:move; margin:6px 0; padding:8px; border:1px dashed #aaa; background:#fff;">
          <span class="drag-handle" style="margin-right:8px;">&#x2630;</span>
          <?php echo esc_html($item['title'] ?? 'Untitled'); ?>
          <input type="hidden" name="order[]" value="<?php echo esc_attr($key); ?>">
        </li>
      <?php endforeach; ?>
    </ul>

    <input type="hidden" name="action" value="save_newsletter_order">
    <input type="hidden" name="page_id" value="<?php echo esc_attr(get_the_ID()); ?>">
    <?php wp_nonce_field('save_newsletter_order'); ?>

    <button type="submit" class="save-newsletter-reorder" style="margin-top:10px;">Save Order</button>
  </div>
</form>

<form method="post" enctype="multipart/form-data"
		      action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">

			<input type="hidden" name="action"      value="add_newsletter">
			<input type="hidden" name="page_id"     value="<?php echo esc_attr( $page_id ); ?>">
			<input type="hidden" name="show_group"  value="<?php echo esc_attr( $show_group ); ?>">
			<?php wp_nonce_field( 'firefly_add_newsletter' ); ?>

<script>
jQuery(function($){
  // 1) Prevent duplicate bindings across multiple shortcode instances
  $(document)
    .off('click.ff-reorder', '.toggle-newsletter-reorder')
    .on('click.ff-reorder', '.toggle-newsletter-reorder', function(e){
      e.preventDefault();
      const $target = $('#'+ $(this).data('target'));
      // stop queued animations so two rapid calls don't reverse each other
      $target.stop(true, true).slideToggle();
    });

  // 2) Initialize sortable ONCE per list
  $('.newsletter-reorder-list').each(function(){
    const $list = $(this);
    if ($list.data('sortable-initialized')) return;

    $list.sortable({
      items: '.reorder-item',
      handle: '.drag-handle',
      placeholder: 'firefly-placeholder',
      tolerance: 'pointer'
    });

    $list.data('sortable-initialized', true);
  });
});
</script>

<style>
.firefly-placeholder{background:#f0f0f0;border:2px dashed #ccc;height:40px;margin:6px 0;}
.reorder-item{cursor:move;margin:6px 0;padding:8px 12px;background:#fff;border:1px dashed #aaa;border-radius:4px;
  font-size:15px;display:flex;align-items:center;gap:8px}
.reorder-item:hover{background:#f0f8ff}
.drag-handle{cursor:move;}
</style>

<style>
	.firefly-placeholder {
		background: #f0f0f0;
		border: 2px dashed #ccc;
		height: 40px;
	}

  #newsletter-reorder-list {
    list-style: none;
    padding: 0;
  }

  .reorder-item {
    cursor: move;
    margin: 6px 0;
    padding: 8px 12px;
    background: #fff;
    border: 1px dashed #aaa;
    border-radius: 4px;
    font-size: 15px;
    display: flex;
    align-items: center;
    gap: 8px;
  }

  .reorder-item:hover {
    background: #f0f8ff;
  }

  .firefly-placeholder {
    height: 40px;
    background: #e0e0e0;
    border: 2px dashed #999;
    margin: 6px 0;
  }
</style>


	
					<?php
					$delete_url = add_query_arg(
						[
							'delete_block' => '1',
							'block_type'   => 'shortcode',
							'shortcode'    => 'newsletters',
							'block_id'     => $instance_id,
						],
						$_SERVER['REQUEST_URI']
					);
				//	echo '<a href="' . esc_url( $delete_url ) . '" onclick="return confirm(\'Are you sure you want to delete this ' . esc_js( $label ) . ' module?\');">Delete this ' . esc_html( $label ) . ' module</a>';


  
					?>

					<div class="firefly-admin-4" id="<?php echo esc_attr( $instance_id ); ?>" style="display:none;">
						<p class="firefly-admin-link">
							<label><?php echo esc_html( $label ); ?> Title (e.g. February 2025):
								<input type="text" name="newsletter_title" required>
							</label>
						</p>

						<p class="firefly-admin-link">
							<label>Upload PDF/doc:
								<input type="file" name="newsletter_pdf"
								       accept=".pdf,.doc,.docx,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document"
								       required>
							</label>
						</p>

						<p class="firefly-admin-link">
							<label>Upload Thumbnail (optional – generic PDF icon used if omitted):
								<input type="file" name="newsletter_thumb" accept="image/*">
							</label>
						</p>

						<p class="firefly-admin-link">
							<button type="submit">Add <?php echo esc_html( $label ); ?></button>
						</p>

						<a href="#" class="cancel-firefly-form">Cancel</a>
					</div><!-- /.firefly-admin-4 -->
				</div>
			</div><!-- /.firefly-admin-1 -->
		</form>

		<script>
		document.addEventListener('DOMContentLoaded', () => {
			// open
			document.querySelectorAll('.show-firefly-form').forEach(link => {
				link.addEventListener('click', e => {
					e.preventDefault();
					const target = document.getElementById(link.dataset.target);
					if (target) target.style.display = 'block';
				});
			});
			// cancel
			document.querySelectorAll('.cancel-firefly-form').forEach(link => {
				link.addEventListener('click', e => {
					e.preventDefault();
					const box = link.closest('.firefly-admin-4');
					if (box) box.style.display = 'none';
				});
			});
		});
		</script>
	<?php
	endif; // admin

	/* ----------  3. FRONT-END DISPLAY  ---------- */
	echo '<div class="newsletter">';

	foreach ( $items as $key => $item ) {

		// -- filter by show group
		if ( $show_group !== '' ) {
			if ( empty( $item['show'] ) || strcasecmp( $item['show'], $show_group ) !== 0 ) {
				continue;
			}
		}

		$title = esc_html( $item['title'] ?? '' );
		$pdf   = esc_url(  $item['pdf']   ?? '' );
		$thumb = ! empty( $item['thumb'] )
		         ? esc_url( $item['thumb'] )
		         : get_stylesheet_directory_uri() . '/assets/PDF.gif';

		echo '<div class="newsletter-panel">';

		/* -- per-item admin controls */
		if ( current_user_can( 'manage_options' ) ) {
			echo '<div class="firefly-admin-1"><div class="firefly-admin-2">Document options</div><div class="firefly-admin-3">';
			echo '<a href="' . esc_url( admin_url( 'admin-post.php?action=delete_newsletter&page_id=' . $page_id . '&key=' . $key . '&_wpnonce=' . wp_create_nonce( 'delete_newsletter' ) ) ) . '" onclick="return confirm(\'Are you sure you want to delete this document?\')">Delete</a> | ';
			echo '<a href="#" onclick="editNewsletterTitle(' . esc_attr( $key ) . ', \'' . esc_js( $title ) . '\')">Edit title</a>';

            echo ' | <a href="#" class="show-thumbnail-form" data-key="' . esc_attr($key) . '">Thumbnail</a>';

            echo '<div class="thumbnail-upload-form" id="thumb-form-' . esc_attr($key) . '" style="display:none; margin-top:10px;">
    <form method="post" action="' . esc_url(admin_url('admin-post.php')) . '" enctype="multipart/form-data">
        <input type="hidden" name="action" value="update_newsletter_thumbnail">
        
        <input type="hidden" name="page_id" value="' . esc_attr($page_id) . '">
        <input type="hidden" name="key" value="' . esc_attr($key) . '">
        ' . wp_nonce_field('update_newsletter_thumbnail', '_wpnonce', true, false). '




        <input type="file" name="new_thumb" accept="image/*" required>
        <button type="submit">Upload</button>
        <button type="button" class="cancel-thumbnail-form">Cancel</button>
    </form>
</div>';

echo '<script>
jQuery(document).ready(function($) {
    $(".show-thumbnail-form").click(function(e) {
        e.preventDefault();
        var key = $(this).data("key");
        $(".thumbnail-upload-form").hide(); // Hide all open forms
        $("#thumb-form-" + key).slideDown();
    });

    $(".cancel-thumbnail-form").click(function(e) {
        e.preventDefault();
        $(this).closest(".thumbnail-upload-form").slideUp();
    });
});
</script>';


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

		$title_pos = get_theme_mod( 'firefly_document_title_position', 'above' );

		if ( $title_pos === 'above' ) {
			echo '<div class="newsletter-name">' . $title . '</div>';
		}



         if (stristr($thumb, 'wp-content/themes/firefly/assets/PDF.gif')) {
              echo '<div class="newsletter-thumbnail-container-no-thumb"';
            echo '><a href="' . $pdf . '" target="_blank" rel="noopener noreferrer">';
            echo '<img src="' . $thumb . '" alt="' . $title . '" class="newsletter-thumbnail" ';
     
            if (stristr($thumb, 'wp-content/themes/firefly/assets/PDF.gif')) {
                echo ' style="width:40px;height:42px;" ';
            }

        echo "/>"; 
		echo '</a></div>';
        }
        else
        {
        
        echo '<div class="newsletter-thumbnail-container"';
        echo '><a href="' . $pdf . '" target="_blank" rel="noopener noreferrer">';
		echo '<img src="' . $thumb . '" alt="' . $title . '" class="newsletter-thumbnail" ';
     
        if (stristr($thumb, 'wp-content/themes/firefly/assets/PDF.gif')) {
            echo ' style="width:40px;height:42px;" ';
        }

        echo "/>"; 
		echo '</a></div>';

    }

		if ( $title_pos === 'below' ) {
			echo '<div class="newsletter-name">' . $title . '</div>';
		}

		echo '</div>'; // .newsletter-panel
	}

	echo '</div></div></div>'; // .newsletter, .newsletter-container, .wp-block-group

	/* ----------  4. INLINE JS – TITLE EDIT  ---------- */ ?>
	<script>
	function editNewsletterTitle(key, currentTitle) {
		const newTitle = prompt("Edit title:", currentTitle);
		if (newTitle && newTitle.trim() !== "" && newTitle !== currentTitle) {
			const form = document.createElement('form');
			form.method = 'POST';
			form.action = '<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>';

			const data = {
				action: 'update_newsletter_title',
				page_id: '<?php echo esc_attr( $page_id ); ?>',
				key: key,
				new_title: newTitle,
				_wpnonce: '<?php echo wp_create_nonce( 'update_newsletter_title' ); ?>'
			};

			for (const name in data) {
				const input = document.createElement('input');
				input.type  = 'hidden';
				input.name  = name;
				input.value = data[name];
				form.appendChild(input);
			}

			document.body.appendChild(form);
			form.submit();
		}
	}
	</script>
	<?php

	return ob_get_clean();
}

/*--------------------------------------------------------------
  Small helper – handles single file upload
--------------------------------------------------------------*/
// Handle uploads – now stores the “show” group
function firefly_handle_newsletter_upload() {
    if ( ! current_user_can( 'manage_options' ) || ! wp_verify_nonce( $_POST['_wpnonce'], 'firefly_add_newsletter' ) ) {
        wp_die( 'Unauthorized request' );
    }

    $page_id    = intval( $_POST['page_id'] );
    $show_group = isset( $_POST['show_group'] ) ? sanitize_text_field( $_POST['show_group'] ) : '';
    $title      = sanitize_text_field( $_POST['newsletter_title'] );
    $pdf_url    = firefly_upload_file( 'newsletter_pdf' );
    $thumb_url  = firefly_upload_file( 'newsletter_thumb' );

    if ( $pdf_url ) {
        $newsletters = get_post_meta( $page_id, 'firefly_newsletters', true ) ?: [];
        array_unshift( $newsletters, [
            'title' => $title,
            'pdf'   => $pdf_url,
            'thumb' => $thumb_url ?: '',
            'show'  => $show_group,           // <-- NEW
        ] );
        update_post_meta( $page_id, 'firefly_newsletters', $newsletters );
    }

    wp_redirect( get_permalink( $page_id ) );
    exit;
}



// 1) Register the hook
add_action( 'wp_head', 'firefly_admin_upload_form_styles' );




/**
 * Simple wrapper around wp_handle_upload() for our shortcode form.
 */
function firefly_upload_file( $field ) {
    if ( empty( $_FILES[ $field ] ) || $_FILES[ $field ]['error'] !== UPLOAD_ERR_OK ) {
        return false;
    }
    $upload = wp_handle_upload( $_FILES[ $field ], [ 'test_form' => false ] );
    return $upload['url'] ?? false;
}



/**
 * Outputs all of the CSS we’ve used for the Firefly admin upload form.
 */
function firefly_admin_upload_form_styles() {
    ?>
    <style type="text/css">
    /* === Firefly admin upload form – “pretty” makeover === */

    /* wrapper */
    .firefly-admin-4 {
        background: #fafbff;
        border: 1px solid #d0d8e4;
        border-radius: 8px;
        padding: 24px 32px;
        max-width: 540px;
        margin: 24px auto;
        box-shadow: 0 4px 12px rgba(0,0,0,.08);
        font-family: system-ui, -apple-system, Segoe UI, Roboto, sans-serif;
        text-align: left;
    }

    /* each row */
    .firefly-admin-link {
        margin: 18px 0;
        font-size: 15px;
        line-height: 1.4;
    }

    /* labels above inputs */
    .firefly-admin-link label {
        display: block;
        font-weight: 600;
        color: #333;
        margin-bottom: 6px;
    }

    /* text / file inputs */
    .firefly-admin-link input[type="text"],
    .firefly-admin-link input[type="file"] {
        width: 100%;
        padding: 10px 12px;
        font-size: 15px;
        border: 1px solid #c4cdd5;
        border-radius: 6px;
        background: #fff;
        transition: border-color .2s;
    }
    .firefly-admin-link input[type="text"]:focus,
    .firefly-admin-link input[type="file"]:focus {
        border-color: #4285f4;
        outline: none;
    }

    /* submit button */
    .firefly-admin-link button {
        display: inline-block;
        padding: 10px 24px;
        font-size: 15px;
        font-weight: 600;
        background: #4285f4;
        color: #fff;
        border: none;
        border-radius: 6px;
        cursor: pointer;
        transition: background .2s;
    }
    .firefly-admin-link button:hover {
        background: #2f6fe0;
    }

    /* cancel link */
    .cancel-firefly-form {
        display: inline-block;
        margin-top: 12px;
        font-size: 14px;
        color: #a00064;
        text-decoration: none;
        /* border below is just to prove it’s working: */
        border: 1px solid red;
        padding: 4px 8px;
        border-radius: 4px;
    }
    .cancel-firefly-form:hover {
        text-decoration: underline;
    }
    </style>
    <?php

    // Get the settings
    $margin_top    = get_theme_mod('firefly_document_margin_top', '10px');
    $margin_bottom = get_theme_mod('firefly_document_margin_bottom', '10px');
    $image_padding = get_theme_mod('firefly_document_image_padding', '0px');
     $panel_margin = get_theme_mod('firefly_document_panel_margin', '10px');
    $title_size    = get_theme_mod('firefly_document_title_size', '16px');

$newsletter_panel_border              = get_theme_mod('firefly_document_border', '0px');

// Get hex values for all colour settings using your helper function
$bg_newsletter_block            = firefly_get_colour_value('firefly_document_background');
$bg_newsletter_panel            = firefly_get_colour_value('firefly_document_panel_background');
$heading_colour  = firefly_get_colour_value('firefly_document_name_colour');
$line_colour         = firefly_get_colour_value('firefly_document_line_colour');

$thumb_height = get_theme_mod('newsletter-thumbnail-height', '350px');
$thumb_width  = get_theme_mod('newsletter-thumbnail-width', '250px');
$newsletter_force_fixed_size  = get_theme_mod('newsletter-force-fixed-size', '');




    $container_margin_top = get_theme_mod('firefly_container_margin_top', '10px');
    $container_margin_bottom = get_theme_mod('firefly_container_margin_bottom', '10px');
    $container_padding_top = get_theme_mod('firefly_container_padding_top', '0px');
    $container_padding_bottom = get_theme_mod('firefly_container_padding_bottom', '0px');
    $container_padding = get_theme_mod('firefly_container_padding', '0px');


    $panel_margin_top = get_theme_mod('firefly_panel_margin_top', '10px');
    $panel_margin_bottom = get_theme_mod('firefly_panel_margin_bottom', '10px');
    $panel_margin = get_theme_mod('firefly_panel_margin', '10px');
    $panel_padding_top = get_theme_mod('firefly_panel_padding_top', '0px');
    $panel_padding_bottom = get_theme_mod('firefly_panel_padding_bottom', '0px');
    $panel_padding = get_theme_mod('firefly_panel_padding', '0px');
    $panel_border_width = get_theme_mod('firefly_panel_border_width', '2px');


    $image_padding_top = get_theme_mod('firefly_image_padding_top', '0px');
    $image_padding_bottom = get_theme_mod('firefly_image_padding_bottom', '0px');
    $image_padding = get_theme_mod('firefly_image_padding', '0px');

    $document_title_size = get_theme_mod('firefly_document_title_size', '0px');


     $name_padding_top = get_theme_mod('firefly_name_padding_top', '0px');
      $name_padding_bottom = get_theme_mod('firefly_name_padding_bottom', '0px');

       $newsletter_panel_height = get_theme_mod('newsletter-panel-height', '350px');
        $newsletter_panel_width = get_theme_mod('newsletter-panel-width', '250px');
 $document_title_leading = get_theme_mod('firefly_document_title_leading', '120px');



    echo "<style type='text/css'>
        .newsletter-container {
          
            margin-top: {$container_margin_top};
            margin-bottom: {$container_margin_bottom};
            background-color: {$bg_newsletter_block};
            padding-top: {$container_padding_top};
            padding-bottom: {$container_padding_bottom};
            padding-left: {$container_padding};
            padding-right: {$container_padding};
        }
        
        
      

        .newsletter-container {
            text-align:center;
        }

        .newsletter-panel {
            display:inline-block;            
            margin-top: {$panel_margin_top} !important;
            margin-bottom: {$panel_margin_bottom} !important;
            margin-left: {$panel_margin} !important;
            margin-right: {$panel_margin} !important;
            padding-top: {$panel_padding_top} !important;
            padding-bottom: {$panel_padding_bottom} !important;
            padding-left: {$panel_padding} !important;
            padding-right: {$panel_padding} !important;
            background-color: {$bg_newsletter_panel} !important;
            border: {$panel_border_width} solid {$line_colour};
            vertical-align:top;
            text-align:center !important;
           /* width:{$newsletter_panel_width};
            height:{$newsletter_panel_height};*/
        }


        .newsletter-thumbnail-container {
            max-height:{$thumb_height};
            max-width: {$thumb_width};
            height:{$thumb_height} !important;
            width: {$thumb_width} !important;
            margin:0 auto;
             margin-bottom: {$image_padding_bottom} !important;
               margin-top: {$image_padding_top};  
            margin-left: {$image_padding};
            margin-right: {$image_padding};
        }            

        .newsletter-name {
            font-size: {$title_size};
            color: {$heading_colour} !important;
             margin-top: {$name_padding_top} !important;
            margin-bottom: {$name_padding_bottom} !important;
            line-height: {$document_title_leading} !important;
        }

        .newsletter-thumbnail {
           /* max-height:{$thumb_height};
            max-width: {$thumb_width}; */
           width:100%;
           height:100%;
            ";

    if ($newsletter_force_fixed_size) {
        echo   "
        
        height:{$thumb_height} !important;
        width: {$thumb_width} !important;
        
        ";

    }

            echo "
                  margin:0 auto;
          
        }


        ";

  $newsletter_div_borders    = get_theme_mod('newsletter-div-borders', '');

        if ($newsletter_div_borders) {
           
            echo  "
            .newsletter-thumbnail {
            border:2px pink solid;
            }   

            .newsletter-name {
               border:2px blue solid;
            }

             .newsletter-container {
                border:2px green solid;
            }

            .newsletter-panel {
             border:2px purple solid;
                }

            .newsletter-thumbnail-container {
                border:5px red solid;
                }

        ";
        }

        echo "
    </style>";
}



add_action('admin_post_delete_newsletter', 'firefly_handle_newsletter_deletion');
function firefly_handle_newsletter_deletion() {
    if (
        ! current_user_can('manage_options') ||
        ! isset($_GET['page_id'], $_GET['key'], $_GET['_wpnonce']) ||
        ! wp_verify_nonce($_GET['_wpnonce'], 'delete_newsletter')
    ) {
        wp_die('Unauthorized request');
    }

    $page_id = intval($_GET['page_id']);
    $key     = intval($_GET['key']);

    $items = get_post_meta($page_id, 'firefly_newsletters', true) ?: [];

    if (isset($items[$key])) {
        unset($items[$key]);
        $items = array_values($items); // reindex keys
        update_post_meta($page_id, 'firefly_newsletters', $items);
    }

    wp_redirect(get_permalink($page_id));
    exit;
}


add_action('wp_enqueue_scripts', function () {
	if ( current_user_can('manage_options') && is_page() ) {
		wp_enqueue_script('jquery-ui-sortable');
	}
});

add_action('admin_post_save_newsletter_order', 'firefly_handle_reorder_submit');
function firefly_handle_reorder_submit() {
    if (
        ! current_user_can('manage_options') ||
        ! isset($_POST['page_id']) ||
        ! wp_verify_nonce($_POST['_wpnonce'], 'save_newsletter_order')
    ) {
        wp_die('Unauthorized');
    }

    $page_id      = intval($_POST['page_id']);
    $filter       = isset($_POST['filter']) ? sanitize_text_field($_POST['filter']) : '';
    $ordered_keys = array_map('intval', $_POST['order'] ?? []);

    $existing = get_post_meta($page_id, 'firefly_newsletters', true) ?: [];

    // Queue the selected items in the new order (by original keys)
    $queue = [];
    foreach ($ordered_keys as $k) {
        if (isset($existing[$k])) {
            $queue[] = $existing[$k];
        }
    }

    // Rebuild list: keep non-filter items where they are; for filter items,
    // pull the next item from $queue to preserve positions but change relative order
    $new = [];
    foreach ($existing as $k => $item) {
        $belongs = ($filter === '')
            ? true
            : (!empty($item['show']) && strcasecmp($item['show'], $filter) === 0);

        if ($belongs) {
            $new[] = count($queue) ? array_shift($queue) : $item; // fallback if mismatch
        } else {
            $new[] = $item;
        }
    }

    // Edge case: if anything remains (shouldn’t normally), append to end
    foreach ($queue as $leftover) {
        $new[] = $leftover;
    }

    update_post_meta($page_id, 'firefly_newsletters', $new);

    wp_redirect(get_permalink($page_id));
    exit;
}



add_action('admin_post_update_newsletter_thumbnail', 'firefly_update_newsletter_thumbnail');

function firefly_update_newsletter_thumbnail() {
	if (
		! current_user_can('manage_options') ||
		! isset($_POST['page_id'], $_POST['key']) ||
		! wp_verify_nonce($_POST['_wpnonce'], 'update_newsletter_thumbnail')
	) {
		wp_die('Unauthorized');
	}

	$page_id = intval($_POST['page_id']);
	$key = intval($_POST['key']);
	$items = get_post_meta($page_id, 'firefly_newsletters', true) ?: [];

	if (!isset($items[$key])) {
		wp_die('Newsletter not found');
	}

	$new_thumb_url = firefly_upload_newsletter_thumbnail('new_thumb');

	if ($new_thumb_url) {
		$items[$key]['thumb'] = $new_thumb_url;
		update_post_meta($page_id, 'firefly_newsletters', $items);
	}

	wp_redirect(get_permalink($page_id));
	exit;
}

function firefly_upload_newsletter_thumbnail( $file_field_name ) {
	if (
		! isset( $_FILES[ $file_field_name ] ) ||
		! is_uploaded_file( $_FILES[ $file_field_name ]['tmp_name'] )
	) {
		return false;
	}

	$uploaded_file = $_FILES[ $file_field_name ];
	$file_type = wp_check_filetype( $uploaded_file['name'] );
	$allowed_types = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
	if ( ! in_array( strtolower( $file_type['ext'] ), $allowed_types, true ) ) {
		return false;
	}

	require_once ABSPATH . 'wp-admin/includes/file.php';
	$upload_overrides = [ 'test_form' => false ];
	$movefile = wp_handle_upload( $uploaded_file, $upload_overrides );

	if ( $movefile && ! isset( $movefile['error'] ) ) {
		return esc_url_raw( $movefile['url'] );
	}

	return false;
}


add_action('admin_post_update_newsletter_title', 'firefly_update_newsletter_title');

function firefly_update_newsletter_title() {
	if (
		! current_user_can('manage_options') ||
		! isset($_POST['page_id'], $_POST['key'], $_POST['new_title']) ||
		! wp_verify_nonce($_POST['_wpnonce'], 'update_newsletter_title')
	) {
		wp_die('Unauthorized');
	}

	$page_id = intval($_POST['page_id']);
	$key = intval($_POST['key']);
	$new_title = sanitize_text_field($_POST['new_title']);

	$items = get_post_meta($page_id, 'firefly_newsletters', true) ?: [];

	if (!isset($items[$key])) {
		wp_die('Newsletter not found');
	}

	$items[$key]['title'] = $new_title;
	update_post_meta($page_id, 'firefly_newsletters', $items);

	wp_redirect(get_permalink($page_id));
	exit;
}
