<?php

function carnet_display_rooms_shortcode() {
    ob_start();

    // Query all pages with page_category = rooms
    $args = array(
        'post_type'      => 'page',
        'posts_per_page' => 6, 
        'page_category'  => 'rooms',
        'order'          => 'asc',
    );

    $query = new WP_Query($args);

    if ($query->have_posts()) {
        echo '<div class="row">';

        while ($query->have_posts()) {
            $query->the_post();
            $image = get_the_post_thumbnail_url(get_the_ID(), 'full');
            $title = get_the_title();
            $excerpt = get_the_excerpt();
            $content = wp_trim_words(get_the_content(), 25, '...');
            $link = get_permalink();
            $content_full = apply_filters('the_content', get_the_content());
            $paragraphs = preg_split('/<\/p>\s*/', $content_full); // split by closing </p>
            $filtered_paragraphs = array_slice($paragraphs, 2); // remove first 2

            // Rebuild content from remaining paragraphs
            $content_full = get_the_content();
            $plain_text = wp_strip_all_tags($content_full); // Remove all HTML
            $lines = preg_split("/\r\n|\n|\r/", $plain_text); // Split into lines

// Remove first 2 lines if they exist
$filtered_lines = array_slice($lines, 25,100);

// Rebuild the remaining lines into a trimmed summary
$trimmed_content = wp_trim_words(implode(' ', $filtered_lines), 30, '...');

            echo '<div class="col-md-12 mb-3">
                    <div class="card border-0 rounded-0" data-aos="fade-up">
                        <div class="row g-0 align-items-center shadow-sm">
                            <div class="col-md-6">
                                <img src="' . esc_url($image) . '" class="img-fluid" alt="' . esc_attr($title) . '">
                            </div>
                            <div class="col-md-6">
                                <div class="card-body">
                                    <h2 class="card-title">' . esc_html($title) . '</h2>
                                    <span class="excerpt">' . $excerpt . '</span>
                                    <p class="card-text">'. esc_html($trimmed_content) .'</p>
                                    <div class="btn-group">
                                        <a href="' . esc_url($link) . '" class="btn btn-outline-primary me-2">View More</a>
                                        <a href="' . esc_url(site_url('/hotel-room-booking')) . '" class="btn btn-outline-success">Book Now</a>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>';
        }

        echo '</div>';
        wp_reset_postdata();
    } else {
        echo '<p>No rooms found.</p>';
    }

    return ob_get_clean();
}

add_shortcode('display_rooms', 'carnet_display_rooms_shortcode');
