<?php
/**
 * DBA_EEurope_Shortcodes
 *
 * Provides [damalion_geo_blog country="poland"] shortcode support
 * for Eastern Europe countries.
 *
 * @since 3.0.0
 */

if ( ! defined( 'ABSPATH' ) ) exit;

class DBA_EEurope_Shortcodes {

    public static function init() {
        add_shortcode( 'damalion_eeurope_blog', array( __CLASS__, 'render' ) );
    }

    /**
     * Render EEurope blog shortcode.
     *
     * Usage: [damalion_eeurope_blog country="poland" count="5"]
     *
     * @param array $atts Shortcode attributes.
     * @return string HTML output.
     */
    public static function render( $atts ) {
        $atts = shortcode_atts( array(
            'country' => '',
            'count'   => 5,
        ), $atts, 'damalion_eeurope_blog' );

        $country_key = sanitize_key( $atts['country'] );
        $count       = max( 1, min( 20, intval( $atts['count'] ) ) );

        if ( empty( $country_key ) ) {
            return '<p>⚠️ Missing country parameter.</p>';
        }

        $config = DBA_EEurope_Registry::get_country( $country_key );
        if ( ! $config ) {
            return '<p>⚠️ Unknown EEurope country: ' . esc_html( $country_key ) . '</p>';
        }

        $args = array(
            'post_type'      => 'post',
            'post_status'    => 'publish',
            'posts_per_page' => $count,
            'meta_query'     => array(
                array( 'key' => '_dba_eeurope_country', 'value' => $country_key ),
                array( 'key' => '_dba_eeurope_auto_created', 'compare' => 'EXISTS' ),
            ),
            'orderby' => 'date',
            'order'   => 'DESC',
        );

        $query = new WP_Query( $args );

        if ( ! $query->have_posts() ) {
            return '<p>No articles yet for ' . esc_html( $config['label'] ) . '.</p>';
        }

        $html = '<div class="dba-eeurope-blog dba-eeurope-' . esc_attr( $country_key ) . '">';
        while ( $query->have_posts() ) {
            $query->the_post();
            $html .= '<article class="dba-eeurope-post">';
            if ( has_post_thumbnail() ) {
                $html .= '<a href="' . esc_url( get_permalink() ) . '">' . get_the_post_thumbnail( null, 'medium' ) . '</a>';
            }
            $html .= '<h3><a href="' . esc_url( get_permalink() ) . '">' . esc_html( get_the_title() ) . '</a></h3>';
            $html .= '<p class="dba-eeurope-meta">';
            $city = get_post_meta( get_the_ID(), '_dba_eeurope_city', true );
            if ( $city ) $html .= '<span class="dba-eeurope-city">📍 ' . esc_html( $city ) . '</span> ';
            $html .= '<span class="dba-eeurope-date">' . get_the_date() . '</span>';
            $html .= '</p>';
            $html .= '<p>' . esc_html( wp_trim_words( get_the_excerpt(), 25 ) ) . '</p>';
            $html .= '</article>';
        }
        $html .= '</div>';

        wp_reset_postdata();
        return $html;
    }
}
