<?php
if ( ! defined( 'ABSPATH' ) ) exit;

/**
 * IPP Shortcodes — Embeddable property widgets for pages and posts.
 *
 * Available shortcodes:
 *   [palace_properties]       — Property grid
 *   [palace_property]         — Single property card
 *   [palace_search]           — Search/filter bar
 *   [palace_property_count]   — Property count
 *   [palace_property_field]   — Single field value
 *   [palace_agent]            — Agent card
 *
 * @package Integrate_Palace_Properties
 * @since   2.0.0
 */
class IPP_Shortcodes {

    /**
     * Register all shortcodes.
     */
    public static function init() {
        add_shortcode( 'palace_properties',     [ __CLASS__, 'properties_grid' ] );
        add_shortcode( 'palace_property',       [ __CLASS__, 'single_property' ] );
        add_shortcode( 'palace_search',         [ __CLASS__, 'search_bar' ] );
        add_shortcode( 'palace_property_count', [ __CLASS__, 'property_count' ] );
        add_shortcode( 'palace_property_field', [ __CLASS__, 'property_field' ] );
        add_shortcode( 'palace_agent',          [ __CLASS__, 'agent_card' ] );
    }

    /* ═══════════════════════════════════════════════════════════════
     *  [palace_properties] — Renders a property grid
     *
     *  Attributes:
     *    limit           — Number of properties (default 9)
     *    columns         — Grid columns: 2, 3, or 4 (default 3)
     *    template        — Template slug override
     *    status          — Filter by status taxonomy slug
     *    type            — Filter by type taxonomy slug
     *    region          — Filter by region taxonomy slug
     *    sort            — Sort: date, price_asc, price_desc, bedrooms, title
     *    show_search     — Show search bar: yes/no (default no)
     *    show_pagination — Show pagination: yes/no (default yes)
     *    class           — Additional CSS class
     * ═══════════════════════════════════════════════════════════════ */
    public static function properties_grid( $atts = [] ) {
        $atts = shortcode_atts( [
            'limit'           => 9,
            'columns'         => 3,
            'template'        => '',
            'status'          => '',
            'type'            => '',
            'region'          => '',
            'sort'            => 'date',
            'show_search'     => 'no',
            'show_pagination' => 'yes',
            'class'           => '',
        ], $atts, 'palace_properties' );

        $template_slug = ! empty( $atts['template'] )
            ? sanitize_text_field( $atts['template'] )
            : sanitize_text_field( get_option( 'ipp_select_template', 'palace-property' ) );

        $columns = max( 2, min( 4, absint( $atts['columns'] ) ) );

        $query_args = IPP_Developer_API::build_query_args( [
            'limit'   => absint( $atts['limit'] ),
            'status'  => $atts['status'],
            'type'    => $atts['type'],
            'region'  => $atts['region'],
            'sort_by' => $atts['sort'],
        ] );

        $query = new WP_Query( $query_args );

        ob_start();

        $css_class = 'ipp-shortcode-grid ipp-grid ipp-grid--cols-' . $columns;
        if ( ! empty( $atts['class'] ) ) {
            $css_class .= ' ' . sanitize_html_class( $atts['class'] );
        }

        do_action( 'ipp_before_archive', $template_slug );

        // Optional search bar
        if ( strtolower( $atts['show_search'] ) === 'yes' ) {
            do_action( 'ipp_before_search_bar' );
            $search_path = INTEGRATE_PALACE_P_PLUGIN_DIR . 'public/templates/' . sanitize_file_name( $template_slug ) . '/search.php';
            $search_path = apply_filters( 'ipp_search_template', $search_path, $template_slug );
            if ( file_exists( $search_path ) ) {
                include $search_path;
            } else {
                include INTEGRATE_PALACE_P_PLUGIN_DIR . 'public/templates/search-default.php';
            }
            do_action( 'ipp_after_search_bar' );
        }

        echo '<div class="' . esc_attr( $css_class ) . '">';

        if ( $query->have_posts() ) {
            while ( $query->have_posts() ) {
                $query->the_post();
                $post_id = get_the_ID();
                $prop    = new IPP_Property_Helper( $post_id );

                do_action( 'ipp_before_card', $post_id, $prop );

                $card_path = INTEGRATE_PALACE_P_PLUGIN_DIR . 'public/templates/' . sanitize_file_name( $template_slug ) . '/card.php';
                // Theme override
                $theme_card = get_stylesheet_directory() . '/palace-properties/card.php';
                if ( file_exists( $theme_card ) ) {
                    $card_path = $theme_card;
                }
                $card_path = apply_filters( 'ipp_card_template', $card_path, $template_slug );

                if ( file_exists( $card_path ) ) {
                    include $card_path;
                }

                do_action( 'ipp_after_card', $post_id, $prop );
            }
        } else {
            echo '<div class="ipp-no-results">';
            echo '<p>' . esc_html__( 'No properties found.', 'integrate-palace-properties' ) . '</p>';
            echo '</div>';
        }

        echo '</div>';

        // Pagination
        if ( strtolower( $atts['show_pagination'] ) === 'yes' && $query->max_num_pages > 1 ) {
            echo '<div class="ipp-pagination ipp-shortcode-pagination">';
            echo paginate_links( [
                'total'   => $query->max_num_pages,
                'current' => max( 1, get_query_var( 'paged' ) ),
            ] );
            echo '</div>';
        }

        do_action( 'ipp_after_archive', $template_slug );

        wp_reset_postdata();

        return ob_get_clean();
    }

    /* ═══════════════════════════════════════════════════════════════
     *  [palace_property id="123"] — Single property card
     *
     *  Attributes:
     *    id       — Post ID (required)
     *    template — Template slug override
     *    class    — Additional CSS class
     * ═══════════════════════════════════════════════════════════════ */
    public static function single_property( $atts = [] ) {
        $atts = shortcode_atts( [
            'id'       => 0,
            'template' => '',
            'class'    => '',
        ], $atts, 'palace_property' );

        $post_id = absint( $atts['id'] );
        if ( ! $post_id ) {
            $post_id = get_the_ID();
        }

        if ( ! $post_id || get_post_type( $post_id ) !== 'palace-properties' ) {
            return '<!-- Palace Properties: Invalid property ID -->';
        }

        $template_slug = ! empty( $atts['template'] )
            ? sanitize_text_field( $atts['template'] )
            : sanitize_text_field( get_option( 'ipp_select_template', 'palace-property' ) );

        ob_start();

        $css_class = 'ipp-shortcode-single';
        if ( ! empty( $atts['class'] ) ) {
            $css_class .= ' ' . sanitize_html_class( $atts['class'] );
        }

        echo '<div class="' . esc_attr( $css_class ) . '">';

        // Use the developer API to render the card
        global $post;
        $original_post = $post;
        $post = get_post( $post_id );
        setup_postdata( $post );

        $prop = new IPP_Property_Helper( $post_id );

        do_action( 'ipp_before_card', $post_id, $prop );

        $card_path = INTEGRATE_PALACE_P_PLUGIN_DIR . 'public/templates/' . sanitize_file_name( $template_slug ) . '/card.php';
        $theme_card = get_stylesheet_directory() . '/palace-properties/card.php';
        if ( file_exists( $theme_card ) ) {
            $card_path = $theme_card;
        }
        $card_path = apply_filters( 'ipp_card_template', $card_path, $template_slug );

        if ( file_exists( $card_path ) ) {
            include $card_path;
        }

        do_action( 'ipp_after_card', $post_id, $prop );

        echo '</div>';

        // Restore
        $post = $original_post;
        if ( $original_post ) {
            setup_postdata( $original_post );
        } else {
            wp_reset_postdata();
        }

        return ob_get_clean();
    }

    /* ═══════════════════════════════════════════════════════════════
     *  [palace_search] — Search/filter bar
     *
     *  Attributes:
     *    class — Additional CSS class
     * ═══════════════════════════════════════════════════════════════ */
    public static function search_bar( $atts = [] ) {
        $atts = shortcode_atts( [
            'class' => '',
        ], $atts, 'palace_search' );

        $template_slug = sanitize_text_field( get_option( 'ipp_select_template', 'palace-property' ) );

        ob_start();

        $css_class = 'ipp-shortcode-search';
        if ( ! empty( $atts['class'] ) ) {
            $css_class .= ' ' . sanitize_html_class( $atts['class'] );
        }

        echo '<div class="' . esc_attr( $css_class ) . '">';

        do_action( 'ipp_before_search_bar' );

        $search_path = INTEGRATE_PALACE_P_PLUGIN_DIR . 'public/templates/' . sanitize_file_name( $template_slug ) . '/search.php';
        $search_path = apply_filters( 'ipp_search_template', $search_path, $template_slug );
        if ( file_exists( $search_path ) ) {
            include $search_path;
        } else {
            include INTEGRATE_PALACE_P_PLUGIN_DIR . 'public/templates/search-default.php';
        }

        do_action( 'ipp_after_search_bar' );

        echo '</div>';

        return ob_get_clean();
    }

    /* ═══════════════════════════════════════════════════════════════
     *  [palace_property_count] — Outputs property count
     *
     *  Attributes:
     *    status — Filter by status taxonomy slug
     *    type   — Filter by type taxonomy slug
     *    region — Filter by region taxonomy slug
     * ═══════════════════════════════════════════════════════════════ */
    public static function property_count( $atts = [] ) {
        $atts = shortcode_atts( [
            'status' => '',
            'type'   => '',
            'region' => '',
        ], $atts, 'palace_property_count' );

        $query_args = [
            'post_type'      => 'palace-properties',
            'post_status'    => 'publish',
            'posts_per_page' => 1,
            'fields'         => 'ids',
        ];

        $tax_query = [];
        if ( ! empty( $atts['status'] ) ) {
            $tax_query[] = [
                'taxonomy' => 'palace-property-status',
                'field'    => 'slug',
                'terms'    => sanitize_text_field( $atts['status'] ),
            ];
        }
        if ( ! empty( $atts['type'] ) ) {
            $tax_query[] = [
                'taxonomy' => 'palace-property-type',
                'field'    => 'slug',
                'terms'    => sanitize_text_field( $atts['type'] ),
            ];
        }
        if ( ! empty( $atts['region'] ) ) {
            $tax_query[] = [
                'taxonomy' => 'palace-property-region',
                'field'    => 'slug',
                'terms'    => sanitize_text_field( $atts['region'] ),
            ];
        }
        if ( ! empty( $tax_query ) ) {
            $tax_query['relation'] = 'AND';
            $query_args['tax_query'] = $tax_query;
        }

        $query = new WP_Query( $query_args );
        wp_reset_postdata();

        return '<span class="ipp-property-count">' . esc_html( number_format_i18n( $query->found_posts ) ) . '</span>';
    }

    /* ═══════════════════════════════════════════════════════════════
     *  [palace_property_field field="rent" id="123"] — Single field
     *
     *  Attributes:
     *    field  — Field name (required)
     *    id     — Post ID (defaults to current post)
     *    format — raw or formatted (default formatted)
     * ═══════════════════════════════════════════════════════════════ */
    public static function property_field( $atts = [] ) {
        $atts = shortcode_atts( [
            'field'  => '',
            'id'     => 0,
            'format' => 'formatted',
        ], $atts, 'palace_property_field' );

        if ( empty( $atts['field'] ) ) {
            return '<!-- Palace Properties: field attribute required -->';
        }

        $post_id = absint( $atts['id'] ) ?: get_the_ID();
        if ( ! $post_id ) return '';

        $prop  = new IPP_Property_Helper( $post_id );
        $field = sanitize_key( $atts['field'] );

        // Map formatted variants
        $formatted_map = [
            'rent'           => 'formatted_rent',
            'date_available' => 'formatted_date_available',
            'address'        => 'full_address',
        ];

        if ( $atts['format'] === 'formatted' && isset( $formatted_map[ $field ] ) ) {
            $method = $formatted_map[ $field ];
        } else {
            $method = $field;
        }

        // Try calling the method
        if ( method_exists( $prop, $method ) ) {
            $value = $prop->$method();
        } else {
            // Fall back to meta
            $value = $prop->meta( $field );
        }

        if ( is_bool( $value ) ) {
            $value = $value ? __( 'Yes', 'integrate-palace-properties' ) : __( 'No', 'integrate-palace-properties' );
        }

        return '<span class="ipp-field ipp-field--' . esc_attr( $field ) . '">' . esc_html( $value ) . '</span>';
    }

    /* ═══════════════════════════════════════════════════════════════
     *  [palace_agent id="123"] — Agent card
     *
     *  Attributes:
     *    id    — Property post ID (required)
     *    class — Additional CSS class
     * ═══════════════════════════════════════════════════════════════ */
    public static function agent_card( $atts = [] ) {
        $atts = shortcode_atts( [
            'id'    => 0,
            'class' => '',
        ], $atts, 'palace_agent' );

        $post_id = absint( $atts['id'] ) ?: get_the_ID();
        if ( ! $post_id || get_post_type( $post_id ) !== 'palace-properties' ) {
            return '<!-- Palace Properties: Invalid property ID for agent -->';
        }

        $prop = new IPP_Property_Helper( $post_id );

        if ( ! $prop->agent_name() ) {
            return '';
        }

        $css_class = 'ipp-agent-card ipp-shortcode-agent';
        if ( ! empty( $atts['class'] ) ) {
            $css_class .= ' ' . sanitize_html_class( $atts['class'] );
        }

        ob_start();

        do_action( 'ipp_before_agent_card', $post_id, $prop );
        ?>
        <div class="<?php echo esc_attr( $css_class ); ?>">
            <div class="ipp-agent-card__body">
                <h4 class="ipp-agent-card__name"><?php echo esc_html( $prop->agent_name() ); ?></h4>
                <?php if ( $prop->agent_title() ) : ?>
                    <p class="ipp-agent-card__title"><?php echo esc_html( $prop->agent_title() ); ?></p>
                <?php endif; ?>
                <div class="ipp-agent-card__contact">
                    <?php if ( $prop->agent_email() ) : ?>
                        <a href="mailto:<?php echo esc_attr( $prop->agent_email() ); ?>" class="ipp-agent-card__email">
                            <?php echo esc_html( $prop->agent_email() ); ?>
                        </a>
                    <?php endif; ?>
                    <?php if ( $prop->agent_phone_mobile() ) : ?>
                        <a href="tel:<?php echo esc_attr( $prop->agent_phone_mobile() ); ?>" class="ipp-agent-card__phone">
                            <?php echo esc_html( $prop->agent_phone_mobile() ); ?>
                        </a>
                    <?php endif; ?>
                    <?php if ( $prop->agent_phone_work() ) : ?>
                        <a href="tel:<?php echo esc_attr( $prop->agent_phone_work() ); ?>" class="ipp-agent-card__phone-work">
                            <?php echo esc_html( $prop->agent_phone_work() ); ?>
                        </a>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        <?php
        do_action( 'ipp_after_agent_card', $post_id, $prop );

        return ob_get_clean();
    }
}

// Self-initialize
IPP_Shortcodes::init();
