<?php
/**
 * Single Client Success Story 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_story_slug', true ) ?: get_post_field( 'post_name', get_the_ID() );
$_sdata = freshm_get_story_by_slug( $_slug );

if ( $_sdata ) {
    $client_name  = $_sdata['name'] ?? '';
    $industry     = $_sdata['industry'] ?? '';
    $duration     = $_sdata['duration'] ?? '';
    $excerpt      = $_sdata['excerpt'] ?? '';
    $quote        = $_sdata['quote_text'] ?? '';
    $quote_author = $_sdata['quote_author'] ?? '';
    if ( ! empty( $_sdata['quote_role'] ) ) $quote_author .= ', ' . $_sdata['quote_role'];
    $client_logo  = $_sdata['logo'] ?? '';
    $hero_image   = $_sdata['hero_image'] ?? $_sdata['image'] ?? '';
    $video_url    = $_sdata['video_url'] ?? '';
    $_gallery     = ! empty( $_sdata['gallery'] ) ? array_filter( array_values( $_sdata['gallery'] ) ) : array();

    // Metrics from structured array
    $_metrics = ! empty( $_sdata['metrics'] ) ? array_values( $_sdata['metrics'] ) : array();
    $main_result  = ! empty( $_metrics[0] ) ? $_metrics[0]['number'] . ' ' . $_metrics[0]['label'] : '';
    $leads        = isset( $_metrics[1] ) ? $_metrics[1]['number'] : '';
    $roi          = isset( $_metrics[2] ) ? $_metrics[2]['number'] : '';
    $engagement   = isset( $_metrics[3] ) ? $_metrics[3]['number'] : '';

    // Extra metrics beyond the 4 standard ones
    $_extra_metrics = array();
    foreach ( $_metrics as $i => $m ) {
        if ( $i >= 4 && ! empty( $m['number'] ) ) $_extra_metrics[] = $m;
    }

    $_use_plugin = true;
} else {
    $client_name  = get_post_meta( get_the_ID(), 'client_name', true );
    $industry     = get_post_meta( get_the_ID(), 'industry', true );
    $duration     = get_post_meta( get_the_ID(), 'duration', true );
    $excerpt      = get_the_excerpt();
    $main_result  = get_post_meta( get_the_ID(), 'main_result', true );
    $leads        = get_post_meta( get_the_ID(), 'result_leads', true );
    $roi          = get_post_meta( get_the_ID(), 'result_roi', true );
    $engagement   = get_post_meta( get_the_ID(), 'result_engagement', true );
    $quote        = get_post_meta( get_the_ID(), 'client_quote', true );
    $quote_author = get_post_meta( get_the_ID(), 'client_quote_author', true );
    $client_logo  = '';
    $hero_image   = '';
    $video_url    = get_post_meta( get_the_ID(), 'video_url', true );
    $_gallery     = array();
    $_extra_metrics = array();
    $_use_plugin = false;
}
?>

<section class="page-hero">
  <div class="container">
    <?php fresh_breadcrumb(); ?>
    <?php if ( $client_logo ) : ?>
      <img src="<?php echo esc_url( $client_logo ); ?>" alt="<?php echo esc_attr( $client_name ); ?>" class="story-hero-logo">
    <?php endif; ?>
    <h1><?php the_title(); ?></h1>
    <?php if ( $excerpt ) : ?>
      <p class="subtitle"><?php echo esc_html( $excerpt ); ?></p>
    <?php elseif ( $main_result ) : ?>
      <p class="subtitle"><?php echo esc_html( $main_result ); ?></p>
    <?php endif; ?>
  </div>
</section>

<section class="case-study-detail">
  <div class="container">
    <div class="case-study-main">

      <!-- Meta Bar -->
      <?php if ( $client_name || $industry || $duration || $main_result ) : ?>
      <div class="case-study-meta-bar">
        <?php if ( $client_name ) : ?>
        <div class="meta-item">
          <span class="meta-label">לקוח</span>
          <span class="meta-value"><?php echo esc_html( $client_name ); ?></span>
        </div>
        <?php endif; ?>
        <?php if ( $industry ) : ?>
        <div class="meta-item">
          <span class="meta-label">תעשייה</span>
          <span class="meta-value"><?php echo esc_html( $industry ); ?></span>
        </div>
        <?php endif; ?>
        <?php if ( $duration ) : ?>
        <div class="meta-item">
          <span class="meta-label">משך</span>
          <span class="meta-value"><?php echo esc_html( $duration ); ?></span>
        </div>
        <?php endif; ?>
        <?php if ( $main_result ) : ?>
        <div class="meta-item">
          <span class="meta-label">תוצאה</span>
          <span class="meta-value"><?php echo esc_html( $main_result ); ?></span>
        </div>
        <?php endif; ?>
      </div>
      <?php endif; ?>

      <?php if ( $hero_image ) : ?>
        <div class="post-featured-image">
          <img src="<?php echo esc_url( $hero_image ); ?>" alt="<?php echo esc_attr( $client_name ); ?>">
        </div>
      <?php elseif ( has_post_thumbnail() ) : ?>
        <div class="post-featured-image">
          <?php the_post_thumbnail( 'large' ); ?>
        </div>
      <?php endif; ?>

      <div class="post-body">
        <?php the_content(); ?>
      </div>

      <!-- Video -->
      <?php if ( $video_url ) :
        $embed_url = fresh_embed_url( $video_url );
        if ( $embed_url ) :
          $embed_url = str_replace( '?autoplay=1&', '?', $embed_url );
          $embed_url = str_replace( '?autoplay=1', '', $embed_url );
      ?>
      <div class="story-video reveal">
        <h2>סרטון</h2>
        <div class="video-wrapper">
          <iframe src="<?php echo esc_url( $embed_url ); ?>" frameborder="0" allow="accelerometer; encrypted-media; gyroscope; picture-in-picture" allowfullscreen loading="lazy"></iframe>
        </div>
      </div>
      <?php endif; endif; ?>

      <!-- Gallery -->
      <?php if ( ! empty( $_gallery ) ) : ?>
      <div class="story-gallery reveal">
        <h2>גלריה</h2>
        <div class="story-gallery-grid">
          <?php foreach ( $_gallery as $gimg ) : ?>
          <div class="story-gallery-item">
            <img src="<?php echo esc_url( $gimg ); ?>" alt="" loading="lazy">
          </div>
          <?php endforeach; ?>
        </div>
      </div>
      <?php endif; ?>

      <!-- Client Quote -->
      <?php if ( $quote ) : ?>
      <div class="client-quote">
        <div class="quote-mark">"</div>
        <p><?php echo esc_html( $quote ); ?></p>
        <?php if ( $quote_author ) : ?>
          <div class="quote-author">- <?php echo esc_html( $quote_author ); ?></div>
        <?php endif; ?>
      </div>
      <?php endif; ?>

      <!-- Related Client Success Stories -->
      <?php
      // Try plugin data first for related stories
      $all_stories = freshm_get_stories();
      $related_items = array();
      if ( ! empty( $all_stories ) ) {
          foreach ( $all_stories as $rs ) {
              if ( ( $rs['slug'] ?? '' ) !== $_slug && count( $related_items ) < 3 ) {
                  $related_items[] = $rs;
              }
          }
      }

      if ( ! empty( $related_items ) ) :
      ?>
      <div class="related-stories">
        <h2>הצלחת לקוחות נוספות</h2>
        <div class="related-stories-grid">
          <?php foreach ( $related_items as $ri ) :
            $ri_result = ! empty( $ri['metrics'][0] ) ? $ri['metrics'][0]['number'] . ' ' . $ri['metrics'][0]['label'] : '';
          ?>
          <a href="<?php echo esc_url( home_url( '/client-success/' . $ri['slug'] . '/' ) ); ?>" class="related-story-card">
            <div class="related-story-image">
              <?php if ( ! empty( $ri['image'] ) ) : ?>
                <img src="<?php echo esc_url( $ri['image'] ); ?>" alt="<?php echo esc_attr( $ri['name'] ); ?>" loading="lazy">
              <?php else : ?>
                <div class="placeholder-img">📸</div>
              <?php endif; ?>
              <?php if ( ! empty( $ri['logo'] ) ) : ?>
                <span class="card-logo-badge"><img src="<?php echo esc_url( $ri['logo'] ); ?>" alt=""></span>
              <?php endif; ?>
            </div>
            <div class="related-story-content">
              <span class="related-story-industry"><?php echo esc_html( $ri['industry'] ?: 'הצלחת לקוח' ); ?></span>
              <h3><?php echo esc_html( $ri['name'] ); ?></h3>
              <?php if ( $ri_result ) : ?><p class="related-story-stat"><?php echo esc_html( $ri_result ); ?></p><?php endif; ?>
            </div>
          </a>
          <?php endforeach; ?>
        </div>
      </div>
      <?php else :
        // CPT fallback
        $related = new WP_Query( array(
            'post_type'      => 'fresh_case_study',
            'posts_per_page' => 3,
            'post__not_in'   => array( get_the_ID() ),
            'orderby'        => 'rand',
        ) );
        if ( $related->have_posts() ) :
      ?>
      <div class="related-stories">
        <h2>הצלחת לקוחות נוספות</h2>
        <div class="related-stories-grid">
          <?php while ( $related->have_posts() ) : $related->the_post(); ?>
          <a href="<?php the_permalink(); ?>" class="related-story-card">
            <div class="related-story-image">
              <?php if ( has_post_thumbnail() ) the_post_thumbnail( 'fresh-portfolio' ); else echo '<div class="placeholder-img">📸</div>'; ?>
            </div>
            <div class="related-story-content">
              <span class="related-story-industry"><?php echo esc_html( get_post_meta( get_the_ID(), 'industry', true ) ?: 'הצלחת לקוח' ); ?></span>
              <h3><?php the_title(); ?></h3>
              <?php $r_result = get_post_meta( get_the_ID(), 'main_result', true ); ?>
              <?php if ( $r_result ) : ?><p class="related-story-stat"><?php echo esc_html( $r_result ); ?></p><?php endif; ?>
            </div>
          </a>
          <?php endwhile; wp_reset_postdata(); ?>
        </div>
      </div>
      <?php endif; endif; ?>
    </div>

    <!-- Results Sidebar -->
    <aside class="results-sidebar">
      <?php if ( $leads || $roi || $engagement || ! empty( $_extra_metrics ) ) : ?>
      <div class="sidebar-card">
        <h3>תוצאות</h3>
        <?php if ( $leads ) : ?>
        <div class="result-row">
          <span class="label"><?php echo esc_html( isset( $_metrics[1]['label'] ) ? $_metrics[1]['label'] : 'לידים' ); ?></span>
          <span class="value"><?php echo esc_html( $leads ); ?></span>
        </div>
        <?php endif; ?>
        <?php if ( $roi ) : ?>
        <div class="result-row">
          <span class="label"><?php echo esc_html( isset( $_metrics[2]['label'] ) ? $_metrics[2]['label'] : 'ROI' ); ?></span>
          <span class="value"><?php echo esc_html( $roi ); ?></span>
        </div>
        <?php endif; ?>
        <?php if ( $engagement ) : ?>
        <div class="result-row">
          <span class="label"><?php echo esc_html( isset( $_metrics[3]['label'] ) ? $_metrics[3]['label'] : 'אנגייג\'מנט' ); ?></span>
          <span class="value"><?php echo esc_html( $engagement ); ?></span>
        </div>
        <?php endif; ?>
        <?php foreach ( $_extra_metrics as $em ) : ?>
        <div class="result-row">
          <span class="label"><?php echo esc_html( $em['label'] ); ?></span>
          <span class="value"><?php echo esc_html( $em['number'] ); ?></span>
        </div>
        <?php endforeach; ?>
      </div>
      <?php endif; ?>

      <div class="sidebar-card sidebar-cta">
        <h3><?php echo esc_html( fm( 'portfolio_settings', 'sidebar_cta_title', 'רוצים תוצאות כאלה?' ) ); ?></h3>
        <p><?php echo esc_html( fm( 'portfolio_settings', 'sidebar_cta_text', 'ספרו לנו על המסעדה שלכם ונתאים חבילה.' ) ); ?></p>
        <a href="#" class="btn-primary" data-popup="contact" style="width:100%;justify-content:center;"><?php echo esc_html( fm( 'portfolio_settings', 'sidebar_cta_btn', 'דברו איתנו ←' ) ); ?></a>
      </div>
    </aside>
  </div>
</section>

<?php get_footer(); ?>
