<?php
/**
 * Single Service — Enhanced Template
 * Reads from plugin data first, falls back to CPT post meta
 */
get_header();

// Try plugin data first via slug
$_slug    = get_post_meta( get_the_ID(), '_freshm_service_slug', true ) ?: get_post_field( 'post_name', get_the_ID() );
$_pdata   = freshm_get_service_by_slug( $_slug );

if ( $_pdata ) {
    // Plugin data available — structured arrays
    $icon         = $_pdata['icon'] ?? '🎯';
    $accent       = $_pdata['color'] ?? '#c9a84c';
    $hero_img     = $_pdata['hero_image'] ?? '';
    $video_url    = $_pdata['video_url'] ?? '';
    $cta_title    = $_pdata['cta_title'] ?? 'מתעניינים בשירות?';
    $cta_text     = $_pdata['cta_text'] ?? 'נשמח לשמוע על המסעדה שלכם ולהתאים חבילה.';
    $cta_btn      = $_pdata['cta_btn_text'] ?? 'דברו איתנו ←';
    // Structured arrays for benefits, process, metrics, gallery
    $_benefits_arr = ! empty( $_pdata['benefits'] ) ? array_values( $_pdata['benefits'] ) : array();
    $_process_arr  = ! empty( $_pdata['process'] ) ? array_values( $_pdata['process'] ) : array();
    $_gallery_arr  = ! empty( $_pdata['gallery'] ) ? array_values( $_pdata['gallery'] ) : array();
    $_use_plugin   = true;
} else {
    // Fallback to CPT post meta
    $icon         = get_post_meta( get_the_ID(), 'service_icon', true ) ?: '🎯';
    $accent       = get_post_meta( get_the_ID(), 'service_accent_color', true ) ?: '#c9a84c';
    $hero_img     = get_post_meta( get_the_ID(), 'service_hero_image', true );
    $video_url    = get_post_meta( get_the_ID(), 'service_video_url', true );
    $cta_title    = get_post_meta( get_the_ID(), 'service_cta_title', true ) ?: 'מתעניינים בשירות?';
    $cta_text     = get_post_meta( get_the_ID(), 'service_cta_text', true ) ?: 'נשמח לשמוע על המסעדה שלכם ולהתאים חבילה.';
    $cta_btn      = get_post_meta( get_the_ID(), 'service_cta_btn', true ) ?: 'דברו איתנו ←';
    $_use_plugin   = false;
}

$categories = get_the_terms( get_the_ID(), 'service_category' );
$cat_name   = ( $categories && ! is_wp_error( $categories ) ) ? $categories[0]->name : '';
?>

<!-- Service Hero -->
<section class="service-hero" <?php if ( $hero_img ) echo 'style="background-image:url(' . esc_url( $hero_img ) . ')"'; ?>>
  <div class="service-hero-overlay"></div>
  <div class="container">
    <?php fresh_breadcrumb(); ?>
    <div class="service-hero-icon"><?php echo function_exists('freshm_render_service_icon') ? freshm_render_service_icon( $icon ) : fresh_svg_icon( $icon, 40 ); ?></div>
    <?php if ( $cat_name ) : ?>
      <div class="service-hero-cat"><?php echo esc_html( $cat_name ); ?></div>
    <?php endif; ?>
    <h1><?php the_title(); ?></h1>
    <?php if ( has_excerpt() ) : ?>
      <p class="subtitle"><?php echo esc_html( get_the_excerpt() ); ?></p>
    <?php endif; ?>
    <div class="service-hero-actions">
      <a href="#" class="btn-primary" data-popup="contact">קבעו שיחה ←</a>
      <?php if ( $video_url ) : ?>
        <a href="<?php echo esc_url( $video_url ); ?>" class="btn-outline service-video-btn" target="_blank" rel="noopener">▶ צפו בסרטון</a>
      <?php endif; ?>
    </div>
  </div>
</section>

<div class="service-page-content">
  <div class="container">
    <div class="service-layout">

      <!-- Main Content -->
      <div class="service-main">

        <!-- Overview -->
        <?php if ( get_the_content() ) : ?>
        <div class="service-block service-overview reveal">
          <div class="post-body">
            <?php the_content(); ?>
          </div>
        </div>
        <?php endif; ?>

        <!-- Benefits -->
        <?php
        if ( $_use_plugin ) {
            $benefits_items = array();
            foreach ( $_benefits_arr as $b ) {
                if ( ! empty( $b['title'] ) ) $benefits_items[] = array( $b['icon'] ?? '✅', $b['title'], $b['desc'] ?? '' );
            }
        } else {
            $benefits = get_post_meta( get_the_ID(), 'service_benefits', true );
            $benefits_items = freshm_parse_pipe_meta( $benefits );
        }
        if ( ! empty( $benefits_items ) ) :
        ?>
        <div class="service-block service-benefits reveal">
          <h2 class="includes-heading"><?php echo fresh_svg_icon( '✨', 22 ); ?> מה כולל השירות</h2>
          <div class="service-includes-grid">
            <?php foreach ( $benefits_items as $b ) :
              $b_icon  = $b[0] ?? '✅';
              $b_title = $b[1] ?? '';
              $b_desc  = $b[2] ?? '';
            ?>
            <div class="service-includes-card">
              <div class="card-icon"><?php echo fresh_svg_icon( $b_icon, 22 ); ?></div>
              <?php if ( $b_title ) : ?><div class="card-title"><?php echo esc_html( $b_title ); ?></div><?php endif; ?>
              <?php if ( $b_desc ) : ?><div class="card-desc"><?php echo esc_html( $b_desc ); ?></div><?php endif; ?>
            </div>
            <?php endforeach; ?>
          </div>
        </div>
        <?php endif; ?>

        <!-- Video Embed -->
        <?php if ( $video_url ) :
          $embed_url = fresh_embed_url( $video_url );
          if ( $embed_url ) :
          // Strip autoplay from service page embeds
          $embed_url = str_replace( '?autoplay=1&', '?', $embed_url );
        ?>
        <div class="service-block service-video reveal">
          <div class="video-wrapper">
            <iframe src="<?php echo esc_url( $embed_url ); ?>" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen loading="lazy"></iframe>
          </div>
        </div>
        <?php endif; endif; ?>

        <!-- Process Steps -->
        <?php
        if ( $_use_plugin ) {
            $process_items = array();
            foreach ( $_process_arr as $p ) {
                if ( ! empty( $p['title'] ) ) $process_items[] = array( $p['number'] ?? '', $p['title'], $p['desc'] ?? '' );
            }
        } else {
            $process = get_post_meta( get_the_ID(), 'service_process', true );
            $process_items = freshm_parse_pipe_meta( $process );
        }
        if ( ! empty( $process_items ) ) :
        ?>
        <div class="service-block service-process reveal">
          <h2><?php echo fresh_svg_icon( '⚙️', 22 ); ?> תהליך העבודה</h2>
          <div class="process-timeline">
            <?php foreach ( $process_items as $p ) :
              $p_num   = $p[0] ?? '';
              $p_title = $p[1] ?? '';
              $p_desc  = $p[2] ?? '';
            ?>
            <div class="process-step">
              <div class="process-number"><?php echo esc_html( $p_num ); ?></div>
              <div class="process-content">
                <?php if ( $p_title ) : ?><h3><?php echo esc_html( $p_title ); ?></h3><?php endif; ?>
                <?php if ( $p_desc ) : ?><p><?php echo esc_html( $p_desc ); ?></p><?php endif; ?>
              </div>
            </div>
            <?php endforeach; ?>
          </div>
        </div>
        <?php endif; ?>

        <!-- Closing Paragraph -->
        <?php
        $closing_text = '';
        if ( $_use_plugin && ! empty( $_pdata['closing_text'] ) ) {
            $closing_text = $_pdata['closing_text'];
        }
        if ( ! $closing_text ) {
            $closing_text = 'אנחנו לא מאמינים בהבטחות ריקות. אנחנו מאמינים בתוצאות שאפשר למדוד, בשקיפות מלאה, ובשותפות ארוכת טווח שגורמת למסעדה שלכם לצמוח - חודש אחרי חודש. מוכנים להתחיל? אנחנו כאן.';
        }
        ?>
        <div class="service-block service-closing reveal">
          <p class="service-closing-text"><?php echo esc_html( $closing_text ); ?></p>
          <a href="#" class="btn-primary" data-popup="contact">קבעו שיחת ייעוץ ←</a>
        </div>

        <!-- FAQ Accordion -->
        <?php
        $_faqs_arr = array();
        if ( $_use_plugin && ! empty( $_pdata['faqs'] ) ) {
            $_faqs_arr = array_values( $_pdata['faqs'] );
        }
        if ( ! empty( $_faqs_arr ) ) :
        ?>
        <div class="service-block service-faq reveal">
          <h2><?php echo fresh_svg_icon( '❓', 22 ); ?> שאלות נפוצות</h2>
          <div class="faq-list">
            <?php foreach ( $_faqs_arr as $faq_item ) : ?>
            <div class="faq-item">
              <button class="faq-question" aria-expanded="false" onclick="this.parentElement.classList.toggle('open');this.setAttribute('aria-expanded',this.parentElement.classList.contains('open'))">
                <span><?php echo esc_html( $faq_item['q'] ); ?></span>
                <span class="faq-toggle">+</span>
              </button>
              <div class="faq-answer">
                <p><?php echo esc_html( $faq_item['a'] ); ?></p>
              </div>
            </div>
            <?php endforeach; ?>
          </div>
        </div>

        <!-- FAQ JSON-LD Schema -->
        <script type="application/ld+json">
        <?php
        $faq_schema = array(
            '@context'   => 'https://schema.org',
            '@type'      => 'FAQPage',
            'mainEntity' => array(),
        );
        foreach ( $_faqs_arr as $faq_item ) {
            $faq_schema['mainEntity'][] = array(
                '@type' => 'Question',
                'name'  => $faq_item['q'],
                'acceptedAnswer' => array(
                    '@type' => 'Answer',
                    'text'  => wp_strip_all_tags( $faq_item['a'] ),
                ),
            );
        }
        echo wp_json_encode( $faq_schema, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT );
        ?>
        </script>
        <?php endif; ?>

        <!-- Gallery -->
        <?php
        if ( $_use_plugin ) {
            $gallery_items = array_filter( $_gallery_arr );
        } else {
            $gallery_raw   = get_post_meta( get_the_ID(), 'service_gallery', true );
            $gallery_items = freshm_parse_gallery( $gallery_raw );
        }
        if ( ! empty( $gallery_items ) ) :
        ?>
        <div class="service-block service-gallery reveal">
          <h2><?php echo fresh_svg_icon( '🖼️', 22 ); ?> דוגמאות</h2>
          <div class="service-gallery-grid">
            <?php foreach ( $gallery_items as $img_url ) : ?>
            <div class="gallery-item">
              <img src="<?php echo esc_url( $img_url ); ?>" alt="" loading="lazy">
            </div>
            <?php endforeach; ?>
          </div>
        </div>
        <?php endif; ?>

      </div>

      <!-- Sidebar -->
      <aside class="service-sidebar">
        <div class="sidebar-card">
          <h3>כל השירותים</h3>
          <ul class="sidebar-nav">
            <?php
            // Plugin data first for sidebar
            $sb_cats = freshm_get_service_cats();
            $sb_svcs = freshm_get_services();
            if ( ! empty( $sb_cats ) && ! empty( $sb_svcs ) ) :
              usort( $sb_cats, function( $a, $b ) { return ( $a['order'] ?? 0 ) - ( $b['order'] ?? 0 ); } );
              foreach ( $sb_cats as $sc ) :
                $cat_items = array_filter( $sb_svcs, function( $s ) use ( $sc ) { return ( $s['category'] ?? '' ) === $sc['slug']; } );
                usort( $cat_items, function( $a, $b ) { return ( $a['order'] ?? 0 ) - ( $b['order'] ?? 0 ); } );
                if ( empty( $cat_items ) ) continue;
            ?>
            <li class="sidebar-nav-group">
              <span class="sidebar-nav-cat"><?php echo esc_html( $sc['name'] ); ?></span>
              <ul>
                <?php foreach ( $cat_items as $si ) :
                  $is_current = ( $_slug === $si['slug'] ) ? ' class="current"' : '';
                ?>
                <li<?php echo $is_current; ?>>
                  <a href="<?php echo esc_url( home_url( '/service/' . $si['slug'] . '/' ) ); ?>">
                    <span class="nav-icon"><?php echo function_exists('freshm_render_service_icon') ? freshm_render_service_icon( $si['icon'] ?? '◆', 'mini' ) : fresh_svg_icon( $si['icon'] ?? '◆', 18 ); ?></span>
                    <?php echo esc_html( $si['name'] ); ?>
                  </a>
                </li>
                <?php endforeach; ?>
              </ul>
            </li>
            <?php endforeach;
            else :
              // Fallback to WP taxonomy
              $all_cats = get_terms( array( 'taxonomy' => 'service_category', 'hide_empty' => true ) );
              if ( ! is_wp_error( $all_cats ) && ! empty( $all_cats ) ) :
                foreach ( $all_cats as $cat ) :
                  $cat_services = get_posts( array(
                      'post_type'      => 'fresh_service',
                      'posts_per_page' => -1,
                      'tax_query'      => array( array( 'taxonomy' => 'service_category', 'field' => 'term_id', 'terms' => $cat->term_id ) ),
                      'orderby'        => 'menu_order',
                      'order'          => 'ASC',
                  ) );
            ?>
            <li class="sidebar-nav-group">
              <span class="sidebar-nav-cat"><?php echo esc_html( $cat->name ); ?></span>
              <ul>
                <?php foreach ( $cat_services as $s ) :
                  $s_icon = get_post_meta( $s->ID, 'service_icon', true ) ?: '◆';
                  $is_current = ( $s->ID === get_queried_object_id() ) ? ' class="current"' : '';
                ?>
                <li<?php echo $is_current; ?>>
                  <a href="<?php echo get_permalink( $s->ID ); ?>">
                    <span class="nav-icon"><?php echo function_exists('freshm_render_service_icon') ? freshm_render_service_icon( $s_icon, 'mini' ) : fresh_svg_icon( $s_icon, 18 ); ?></span>
                    <?php echo esc_html( $s->post_title ); ?>
                  </a>
                </li>
                <?php endforeach; ?>
              </ul>
            </li>
            <?php endforeach; endif; endif; ?>
          </ul>
        </div>

        <div class="sidebar-card sidebar-cta">
          <h3><?php echo esc_html( $cta_title ); ?></h3>
          <p><?php echo esc_html( $cta_text ); ?></p>
          <a href="#" class="btn-primary" data-popup="contact" style="width:100%;justify-content:center;"><?php echo esc_html( $cta_btn ); ?></a>
          <a href="<?php echo esc_url( freshm_whatsapp_url() ); ?>" class="btn-outline" style="width:100%;justify-content:center;margin-top:0.5rem;">WhatsApp</a>
        </div>
      </aside>

    </div>
  </div>
</div>

<!-- Bottom CTA -->
<section class="cta">
  <div class="container">
    <div class="section-label reveal"><?php echo esc_html( fm( 'homepage', 'cta_label', 'מתעניינים?' ) ); ?></div>
    <h2 class="reveal reveal-delay-1"><?php echo esc_html( fm( 'homepage', 'cta_title', 'בואו נבנה' ) ); ?><br><span class="gold"><?php echo esc_html( fm( 'homepage', 'cta_title_gold', 'חבילה מותאמת אישית' ) ); ?></span></h2>
    <p class="section-subtitle reveal reveal-delay-2"><?php echo esc_html( fm( 'homepage', 'cta_subtitle', 'כל מסעדה שונה. ספרו לנו על העסק שלכם ונבנה תוכנית שמתאימה בדיוק לכם.' ) ); ?></p>
    <div class="cta-buttons reveal reveal-delay-3">
      <a href="#" class="btn-primary" data-popup="contact"><?php echo esc_html( fm( 'homepage', 'cta_btn_text', 'קבעו שיחה ←' ) ); ?></a>
      <a href="<?php echo esc_url( freshm_whatsapp_url() ); ?>" class="btn-outline"><?php echo esc_html( fm( 'homepage', 'cta_btn2_text', 'WhatsApp' ) ); ?></a>
    </div>
  </div>
</section>

<?php get_footer(); ?>
