<?php
get_header();

$thing_id = get_query_var('firefly_thing_id');

$slug = get_query_var('firefly_thing_slug'); // ✅ THIS IS MISSING

$print_icon = get_theme_mod("firefly_thing_print_page_icon_$slug", '');


if ($thing_id && is_numeric($thing_id)) {
    $post = get_post((int) $thing_id);




         echo '<div class="no-print" style="text-align:center;margin-bottom:20px;margin-top:20px;">';
        echo '<a href="' . esc_url(site_url("/$slug")) . '" style="display:inline-block;background:#0071c2;color:white;padding:8px 16px;border-radius:4px;text-decoration:none !important;font-weight:bold;">← Back</a>';
        echo '</div>';

    if ($post) {
        setup_postdata($post);




        echo '<div class="thing-detail" style="max-width:800px;margin:40px auto;padding:20px;border:1px solid #ccc;border-radius:10px;">';

        if ($print_icon) {
            echo '<button onclick="window.print()" class="no-print" style="margin-bottom:10px;">🖨 Print this page</button>';

            echo "
            
            <style>
            
            
            @media print {
            .no-print, .firefly-footer, 
            nav.main-menu,
            nav,
            nav.mobile-menu,
            .mobile-menu-toggle,
              .firefly-banner,
            .firefly-banner-only,
              .firefly-text-only,
          .banner-with-phone,
            .firefly-logo-wrap  { display: none; }

            p, ul, li , .checkboxlistitem {
                font-size:12px !important;
                line-height:140% !important;
                margin-top:5px !important;
                margin-bottom:5px !important;
                padding-top:0px !important;
                padding-bottom:0px !important;
            }


       

             h1 {
                font-size:28px !important;
            }

               h3 {
                font-size:18px !important;
            }

            .page-break { break-after: page; } /* or page-break-after for older browsers */
            }


            
            @page { @top-left { content: none } }

            </style>";
    }
        // 🖼 Featured image
    //    if (has_post_thumbnail($post)) {
        //    echo '<div style="text-align:center;margin-bottom:20px;">';
         //   echo get_the_post_thumbnail($post, 'large', [$value = get_post_meta($post->ID, $key, true);

   // 'style' => 'max-width:100%; height:auto; border-radius:6px;'
//]);
           // echo '</div>';
//}



// 🎞 Image gallery with interactive thumbnail navigation

// 🎞 Image gallery with intelligent display
$attachments = get_attached_media('image', $post->ID);
if ($attachments) {
    // Get featured image or first attachment
    $featured_id = get_post_thumbnail_id($post->ID);
    $first_image_id = $featured_id ?: reset($attachments)->ID;
    $first_image_url = wp_get_attachment_image_url($first_image_id, 'large');
    
    echo '<div class="firefly-gallery-container" style="max-width:800px;margin:0 auto 20px;">';
    
    // Main large image display
    echo '<div class="firefly-main-image" style="margin-bottom:15px;text-align:center;">';
    echo '<img src="' . esc_url($first_image_url) . '" 
          style="max-width:100%; height:auto; border-radius:6px; cursor:zoom-in;" 
          id="firefly-main-image"
          loading="eager">';
    echo '</div>';
    
    // Only show thumbnails if we have multiple images
    if (count($attachments) > 1) {
        echo '<div class="firefly-thumbnails" style="display:flex;gap:8px;flex-wrap:wrap;justify-content:center;">';
        foreach ($attachments as $attachment) {
            $thumb_url = wp_get_attachment_image_url($attachment->ID, 'thumbnail');
            $full_url = wp_get_attachment_image_url($attachment->ID, 'large');
            
            echo '<img src="' . esc_url($thumb_url) . '" 
                 data-full="' . esc_url($full_url) . '" 
                 style="width:60px;height:60px;object-fit:cover;border-radius:4px;cursor:pointer;border:2px solid ' . ($attachment->ID == $first_image_id ? '#0071c2' : 'transparent') . '"
                 class="firefly-thumb" 
                 onclick="updateMainImage(\'' . esc_js($full_url) . '\', this)">';
        }
        echo '</div>';
        
        // Only include the JavaScript if we have thumbnails
        echo '
        <script>

        /* this script comes from firefly-thing-display.php */

        function updateMainImage(newSrc, clickedThumb) {
            const mainImg = document.getElementById("firefly-main-image");
            document.querySelectorAll(".firefly-thumb").forEach(thumb => {
                thumb.style.borderColor = "transparent";
            });
            clickedThumb.style.borderColor = "#0071c2";
            mainImg.style.opacity = 0;
            setTimeout(() => {
                mainImg.src = newSrc;
                mainImg.style.opacity = 1;
            }, 200);
        }
        </script>
        ';
    }
    echo '</div>'; // Close gallery-container
    
    // Admin upload link
    if (current_user_can('edit_post', $post->ID)) {
        echo '<div class="firefly-admin-1" style="text-align:center;margin:20px 0 30px;">';
        echo '<a href="' . esc_url(admin_url("media-new.php?post_id=" . $post->ID)) . '" target="_blank" style="display:inline-block;background:#f0f0f0;color:#333;padding:8px 16px;border-radius:4px;text-decoration:none !important;font-weight:bold;">➕ Add More Images</a>';
        echo '</div>';
    }
}


        // 🏷 Title
        echo '<h1 style="font-size:1.8rem;margin-bottom:10px;">' . esc_html(get_the_title($post)) . '</h1>';

        // 📝 Content
        echo '<div style="margin-bottom:20px;font-size:1rem;line-height:1.6;">' . apply_filters('the_content', $post->post_content) . '</div>';





        


        
        // 🧩 Custom fields from "Custom fields 2"
        //$custom_fields_detail = get_theme_mod('firefly_thing_fields_detail', '');
        $custom_fields_detail = get_theme_mod("firefly_thing_fields_list_$slug", '');
        $fields = array_filter(array_map('trim', explode("\n", $custom_fields_detail)));


        if (!empty($fields)) { 

        //    echo '<h2>Details</h2>';
            echo '<ul style="list-style:none;padding:0;font-size:1rem;">';

            foreach ($fields as $field_raw) {
                $is_checkbox = str_starts_with($field_raw, '*');
                $field_label = ltrim($field_raw, '*');
                $key = thing_meta_key( $field_label );
                $value = get_post_meta($post->ID, $key, true);

                if ($value !== '') {
                    echo '<li style="margin-bottom:8px;"><strong>' . esc_html($field_label) . ':</strong> ';
                    echo $is_checkbox ? ($value ? '✅' : '❌') : esc_html($value);
                    echo '</li>';
                }
            }

            echo '</ul>';
        }






        // 🧩 Custom fields from "Custom fields 2"
        //$custom_fields_detail = get_theme_mod('firefly_thing_fields_detail', '');
        $custom_fields_detail = get_theme_mod("firefly_thing_fields_detail_$slug", '');
        $fields = array_filter(array_map('trim', explode("\n", $custom_fields_detail)));


        if (!empty($fields)) { 

          //  echo '<h2>Details</h2>';
            echo '<ul style="list-style:none;padding:0;font-size:1rem;">';

            foreach ($fields as $field_raw) {
              //  $is_checkbox = str_starts_with($field_raw, '*');
                $field_label = ltrim($field_raw, '*');
              // $key = sanitize_key($field_label);

              //  $key = str_replace(' ', '', strtolower($field_label));
//$key = str_replace("(", "", $key);
              //  $key = str_replace(")", "", $key);
              //  $key = strtolower(preg_replace('/[^a-z0-9]/', '', $field_label)); // r 
  //  $key = green$field);
             $key = $field_label;


         //   $key = str_replace(" ", "", $field_label);
         //   $key = str_replace("/", "", $key);
         //   $key = str_replace('"', "", $key);
         //   $key = str_replace("'", "", $key);
         //   $key = strtolower($key);
                  
$key = thing_meta_key( $field_label );

               //  echo "<p style='color:blue;'>-$field_label-$key-</p>";
              $value = get_post_meta($post->ID, $key, true);


                if ($value !== '') {
                    echo '<li style="margin-bottom:8px;"><strong>' . esc_html($field_label) . ':</strong> ';
                    echo $is_checkbox ? ($value ? '✅' : '❌') : esc_html($value);
                    echo '</li>';
                }
            }

            echo '</ul>';
        }


$custom_fields_checkboxes = get_theme_mod("firefly_thing_fields_checkboxes_$slug", '');
$checkboxfields = array_filter(array_map('trim', explode("\n", $custom_fields_checkboxes)));

if (!empty($checkboxfields)) {
  //  echo '<h2>Features</h2>';
    echo '<div>';

$pending_heading = null;   // stores the last heading we saw, if any

foreach ( $checkboxfields as $field_raw ) {

    $is_heading   = str_starts_with( $field_raw, '*' );
    $field_label  = ltrim( $field_raw, '*' );
    $key          = thing_meta_key( $field_label );
    $value        = get_post_meta( $post->ID, $key, true );

    if ( $is_heading ) {
        // Keep the heading on standby; only show it if we later
        // encounter a non-empty bullet that belongs under it.
        $pending_heading = $field_label;
        continue;
    }

    // Not a heading → treat as bullet point.
    if ( ! empty( $value ) ) {

        // Print the pending heading once, immediately before the
        // first bullet that actually has data.
        if ( $pending_heading !== null ) {
            echo '<h3 style="margin-top:20px;">' . esc_html( $pending_heading ) . '</h3>';
            $pending_heading = null;   // reset so it only prints once
        }

        // Now print the bullet itself.
        echo '<div class="checkboxlistitem">&bull; ' . esc_html( $field_label ) . '</div>';
    }
}

    echo '</div>';


    echo "<style>

    /* these styles from from firefly-thing-display.php */
    
    .checkboxlistitem {
         margin-left:50px;
    }
    </style>
";
}




        
        echo '</div>'; // .thing-detail
        wp_reset_postdata();
    } else {
        echo '<p style="text-align:center;">❌ Thing not found.</p>';
    }
} else {
    echo '<p style="text-align:center;">❌ No item ID provided.</p>';
}

get_footer();
