<?php
/*
Template Name: News Page
*/
get_header();
?>

<section class="howcan-breaking-news container">
  <div class="breaking-label">
    <?php echo esc_html( get_theme_mod( 'howcan_breaking_news_label', __( 'Breaking News', 'howcan' ) ) ); ?>
  </div>
  <div class="breaking-marquee">
    <?php
    $latest_post = new WP_Query(array(
        'posts_per_page' => 1,
        'post_status'    => 'publish',
        'orderby'        => 'date',
        'order'          => 'DESC',
    ));

    if ($latest_post->have_posts()) :
        while ($latest_post->have_posts()) : $latest_post->the_post();
            ?>
            <marquee behavior="scroll" direction="left" scrollamount="5" onmouseover="this.stop();" onmouseout="this.start();">
              <a href="<?php the_permalink(); ?>">
      
      
       <?php the_title(); ?>
       
       
                </a>
            </marquee>
            <?php
        endwhile;
        wp_reset_postdata();
    endif;
    ?>
  </div>
</section>

<?php
$slides = [];
for ( $i = 1; $i <= 3; $i++ ) {
    $img = get_theme_mod( "howcan_slider_image_$i" );
    if ( $img ) {
        $slides[] = array(
            'image' => $img,
            'title' => get_theme_mod( "howcan_slider_title_$i" ),
            'subtitle' => get_theme_mod( "howcan_slider_subtitle_$i" ),
            'btn_text' => get_theme_mod( "howcan_slider_btn_text_$i" ),
            'btn_link' => get_theme_mod( "howcan_slider_btn_link_$i" ),
        );
    }
}
if ( empty( $slides ) ) return;
?>

<section class="howcan-slider my-2">
  <div class="swiper mySwiper">
    <div class="swiper-wrapper">
      <?php foreach ( $slides as $slide ) : ?>
        <div class="swiper-slide" style="height:300px; background-image:url('<?php echo esc_url( $slide['image'] ); ?>');">
          <div class="howcan-slider-content">
            <?php if ( $slide['title'] ) : ?><h2><?php echo esc_html( $slide['title'] ); ?></h2><?php endif; ?>
            <?php if ( $slide['subtitle'] ) : ?><p><?php echo esc_html( $slide['subtitle'] ); ?></p><?php endif; ?>
            <?php if ( $slide['btn_text'] ) : ?>
              <a href="<?php echo esc_url( $slide['btn_link'] ); ?>" class="btn btn-primary">
                <?php echo esc_html( $slide['btn_text'] ); ?>
              </a>
            <?php endif; ?>
          </div>
        </div>
      <?php endforeach; ?>
    </div>
  </div>
</section>

<script>
document.addEventListener('DOMContentLoaded', function () {
  new Swiper('.mySwiper', {
    loop: true,
    autoplay: { delay: 4000 },
    effect: 'fade',
    speed: 800,
  });
});
</script>

<div class="container my-4">
 
 
 
 
  <?php
  $categories = get_categories([
    'orderby' => 'name',
    'order'   => 'ASC',
    'hide_empty' => false
  ]);

  if (!empty($categories)) :
    foreach ($categories as $category) :
  ?>
      <section class="category-section mb-5">
        <div class="d-flex justify-content-between align-items-center mb-3">
          <h3 class="fw-bold border-bottom border-2 border-dark pb-1">
            <i class="bi bi-folder2-open"></i> <?php echo esc_html($category->name); ?>
          </h3>
      
        </div>

        <div class="category-posts" data-cat="<?php echo esc_attr($category->term_id); ?>">
          <?php
          $args = [
            'post_type' => 'post',
            'posts_per_page' => 6,
            'cat' => $category->term_id,
            'paged' => 1,
          ];
          $cat_query = new WP_Query($args);

          if ($cat_query->have_posts()) :
            $count = 0;
            while ($cat_query->have_posts()) : $cat_query->the_post();
              $count++;

              // 🔹 Latest post - show full width
              if ($count == 1) :
          ?>
                <div class="row mb-4">
                  <div class="col-md-12">
                    <div class="card flex-md-row shadow-sm h-100">
                      <?php if (has_post_thumbnail()) : ?>
                        <a href="<?php the_permalink(); ?>" class="col-md-5">
                          <?php the_post_thumbnail('large', ['class' => 'img-fluid rounded-start']); ?>
                        </a>
                      <?php endif; ?>
                      <div class="card-body col-md-7">
                        <h4 class="card-title fw-semibold"><a href="<?php the_permalink(); ?>" class="text-decoration-none text-dark"><?php the_title(); ?></a></h4>
                        <p class="card-text"><?php echo wp_trim_words(get_the_excerpt(), 35, '...'); ?></p>
                        <a href="<?php the_permalink(); ?>" class="btn btn-outline-dark btn-sm mt-2">Read More</a>
                      </div>
                    </div>
                  </div>
                </div>
          <?php
              else :
                // 🔹 Remaining posts (grid)
                if ($count == 2) echo '<div class="row">'; // start grid

                echo '<div class="col-sm-4 mb-4">';
                echo '<div class="card h-100 shadow-sm">';
                if (has_post_thumbnail()) {
                  echo '<a href="' . get_permalink() . '">';
                  the_post_thumbnail('medium', ['class' => 'card-img-top rounded-top']);
                  echo '</a>';
                }
                echo '<div class="card-body">';
                echo '<h6 class="card-title"><a href="' . get_permalink() . '" class="text-decoration-none text-dark">' . get_the_title() . '</a></h6>';
            
                echo '<p class="card-text small">' . wp_trim_words(get_the_excerpt(), 15, '...') . '</p>';
                echo '</div></div></div>';

                // 🔹 Insert Smartlink / 

              endif;
            endwhile;

            if ($count > 1) echo '</div>'; // close grid
          else 
            echo '<div class="alert alert-warning text-center">😕 No posts found in this category.</div>';
          endif;
          wp_reset_postdata();
          ?>
        </div>

        <div class="text-center mt-3">
          <button class="btn btn-outline-secondary btn-sm load-more" data-cat="<?php echo esc_attr($category->term_id); ?>">Load More</button>
        </div>
      </section>
  <?php
    endforeach;
  else :
    echo '<p class="text-center">No categories found.</p>';
  endif;
  ?>
</div>

<!-- ⚡ AJAX Pagination Script -->
<script>
document.addEventListener('DOMContentLoaded', function() {
  document.querySelectorAll('.load-more').forEach(button => {
    let page = 2;
    button.addEventListener('click', function() {
      const catID = this.dataset.cat;
      const container = this.closest('.category-section').querySelector('.category-posts');
      const btn = this;
      btn.disabled = true;
      btn.textContent = 'Loading...';

      fetch('<?php echo admin_url("admin-ajax.php"); ?>?action=load_more_news&page=' + page + '&cat=' + catID)
        .then(res => res.text())
        .then(data => {
          if (data.trim() !== '') {
            container.insertAdjacentHTML('beforeend', data);
            page++;
            btn.disabled = false;
            btn.textContent = 'Load More';
          } else {
            btn.textContent = 'No More Posts';
          }
        })
        .catch(() => {
          btn.textContent = 'Error Loading Posts';
        });
    });
  });
});
</script>

<?php get_footer(); ?>