<?php

if ( !defined( 'ABSPATH' ) ) {
    exit;
}
class Yatoon_SF_Shortcode {
    public function __construct() {
        add_shortcode( 'yatoon_social_feed', array($this, 'render') );
        add_action( 'wp_enqueue_scripts', array($this, 'enqueue') );
    }

    public function enqueue() {
        wp_register_style(
            'yatoon-sf-public',
            YATOON_SF_URL . 'public/css/yatoon-sf-public.css',
            array(),
            YATOON_SF_VERSION
        );
        wp_register_script(
            'yatoon-sf-public',
            YATOON_SF_URL . 'public/js/yatoon-sf-public.js',
            array(),
            YATOON_SF_VERSION,
            true
        );
    }

    public function render( $atts ) {
        // Determine platform first so we can pick the right default grid size
        $raw_platform = ( isset( $atts['platform'] ) ? sanitize_key( $atts['platform'] ) : 'all' );
        if ( ! in_array( $raw_platform, array( 'all', 'facebook', 'instagram' ), true ) ) {
            // Guard against typos like platform="Facebook" or platform="fb" -
            // fall back to "all" rather than silently rendering an empty grid.
            $raw_platform = 'all';
        }
        if ( $raw_platform === 'facebook' ) {
            $default_columns = get_option( 'yatoon_sf_fb_columns', 4 );
            $default_rows = get_option( 'yatoon_sf_fb_rows', 3 );
        } elseif ( $raw_platform === 'instagram' ) {
            $default_columns = get_option( 'yatoon_sf_ig_columns', 4 );
            $default_rows = get_option( 'yatoon_sf_ig_rows', 3 );
        } else {
            $default_columns = get_option( 'yatoon_sf_columns', 4 );
            $default_rows = get_option( 'yatoon_sf_rows', 3 );
        }
        $atts = shortcode_atts( array(
            'platform'     => 'all',
            'columns'      => $default_columns,
            'rows'         => $default_rows,
            'gap'          => get_option( 'yatoon_sf_gap', 8 ),
            'show_caption' => get_option( 'yatoon_sf_show_caption', 0 ),
            'display'      => get_option( 'yatoon_sf_display_mode', get_option( 'yatoon_sf_show_caption', 0 ) ? 'both' : 'image' ),
            'layout'       => get_option( 'yatoon_sf_layout', 'grid' ),
            'lightbox'     => get_option( 'yatoon_sf_lightbox', 1 ),
            'open_link'    => get_option( 'yatoon_sf_open_link', 1 ),
        ), $atts, 'yatoon_social_feed' );
        wp_enqueue_style( 'yatoon-sf-public' );
        wp_enqueue_script( 'yatoon-sf-public' );
        $columns = max( 1, min( 12, (int) $atts['columns'] ) );
        $rows = max( 1, min( 20, (int) $atts['rows'] ) );
        $limit = $columns * $rows;
        $gap = (int) $atts['gap'];
        $display = sanitize_key( $atts['display'] );
        if ( ! in_array( $display, array( 'image', 'text', 'both' ), true ) ) {
            $display = 'image';
        }
        $layout = sanitize_key( $atts['layout'] );
        if ( ! in_array( $layout, array( 'grid', 'masonry' ), true ) ) {
            $layout = 'grid';
        }
        $lightbox = filter_var( $atts['lightbox'], FILTER_VALIDATE_BOOLEAN );
        $show_caption = ( 'both' === $display ) || ( (bool) $atts['show_caption'] && 'image' !== $display );
        $open_link = filter_var( $atts['open_link'], FILTER_VALIDATE_BOOLEAN );
        // Re-validate here too: shortcode_atts() only fills in a default
        // when the attribute is *missing*, it doesn't sanitize a value the
        // author actually typed, so re-run it through the same allow-list
        // used above for $raw_platform.
        $platform = sanitize_key( $atts['platform'] );
        if ( ! in_array( $platform, array( 'all', 'facebook', 'instagram' ), true ) ) {
            $platform = 'all';
        }
        $photos = $this->filter_photos_for_display( $this->get_photos( $platform, $limit * 3 ), $display, $limit );
        if ( empty( $photos ) ) {
            return '<p class="yatoon-sf-empty">' . esc_html__( 'No photos to display yet. Please sync in the WordPress admin.', 'yatoon-social-feed' ) . '</p>';
        }

        // Pro-only: lets site owners fine-tune colors/spacing/fonts beyond
        // what the Display Settings controls expose, without needing a
        // child theme or a separate custom-CSS plugin.
        $custom_css = $this->get_premium_custom_css();

        // Header settings
        $show_header = get_option( 'yatoon_sf_show_header', 1 );
        $show_avatar = get_option( 'yatoon_sf_show_avatar', 1 );
        $show_name = get_option( 'yatoon_sf_show_name', 1 );
        $show_bio = get_option( 'yatoon_sf_show_bio', 1 );
        $show_followers = get_option( 'yatoon_sf_show_followers', 1 );
        $show_follow_btn = get_option( 'yatoon_sf_show_follow_btn', 1 );
        // Per-platform info
        $fb_name = get_option( 'yatoon_sf_fb_page_name', '' );
        $fb_page_id = get_option( 'yatoon_sf_fb_page_id', '' );
        $fb_avatar = get_option( 'yatoon_sf_fb_avatar', '' );
        $fb_followers = get_option( 'yatoon_sf_fb_followers', '' );
        $fb_bio = get_option( 'yatoon_sf_fb_bio', '' );
        $fb_url = ( $fb_page_id ? 'https://www.facebook.com/' . $fb_page_id : '' );
        $ig_username = get_option( 'yatoon_sf_ig_username', '' );
        $ig_name = get_option( 'yatoon_sf_ig_display_name', '' );
        if ( empty( $ig_name ) ) {
            $ig_name = ( $ig_username ? '@' . $ig_username : '' );
        }
        $ig_avatar = get_option( 'yatoon_sf_ig_avatar', '' );
        $ig_followers = get_option( 'yatoon_sf_ig_followers', '' );
        $ig_bio = get_option( 'yatoon_sf_ig_bio', '' );
        $ig_url = ( $ig_username ? 'https://www.instagram.com/' . $ig_username : '' );
        ob_start();
        if ( $custom_css ) {
            // The value is stripped of tags in get_premium_custom_css()
            // before it ever reaches here, so this is CSS-only output.
            echo '<style>' . $custom_css . '</style>'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
        }
        // Show header(s)
        if ( $show_header ) {
            $platforms_to_show = array();
            if ( $platform === 'all' || $platform === 'facebook' ) {
                if ( $fb_name ) {
                    $platforms_to_show[] = 'facebook';
                }
            }
            if ( $platform === 'all' || $platform === 'instagram' ) {
                if ( $ig_name ) {
                    $platforms_to_show[] = 'instagram';
                }
            }
            if ( !empty( $platforms_to_show ) ) {
                echo '<div class="yatoon-sf-headers">';
                foreach ( $platforms_to_show as $p ) {
                    $is_ig = $p === 'instagram';
                    $name = ( $is_ig ? $ig_name : $fb_name );
                    $avatar = ( $is_ig ? $ig_avatar : $fb_avatar );
                    $follows = ( $is_ig ? $ig_followers : $fb_followers );
                    $bio = ( $is_ig ? $ig_bio : $fb_bio );
                    $url = ( $is_ig ? $ig_url : $fb_url );
                    $color = ( $is_ig ? 'yatoon-sf-header-ig' : 'yatoon-sf-header-fb' );
                    $label = ( $is_ig ? 'Follow on Instagram' : 'Follow on Facebook' );
                    $icon = ( $is_ig ? '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"><rect x="2" y="2" width="20" height="20" rx="5"/><circle cx="12" cy="12" r="4"/><circle cx="17.5" cy="6.5" r="1" fill="currentColor" stroke="none"/></svg>' : '<svg viewBox="0 0 24 24" fill="currentColor"><path d="M24 12.073C24 5.404 18.627 0 12 0S0 5.404 0 12.073C0 18.1 4.388 23.094 10.125 24v-8.437H7.078v-3.49h3.047V9.413c0-3.007 1.792-4.669 4.533-4.669 1.312 0 2.686.234 2.686.234v2.953H15.83c-1.491 0-1.956.925-1.956 1.874v2.25h3.328l-.532 3.49h-2.796V24C19.612 23.094 24 18.1 24 12.073z"/></svg>' );
                    echo '<div class="yatoon-sf-header-card ' . esc_attr( $color ) . '">';
                    // Left: avatar + info
                    echo '<div class="yatoon-sf-header-left">';
                    if ( $show_avatar && $avatar ) {
                        echo '<div class="yatoon-sf-header-avatar-wrap">';
                        echo '<img src="' . esc_url( $avatar ) . '" alt="' . esc_attr( $name ) . '" class="yatoon-sf-header-avatar" />';
                        echo '<div class="yatoon-sf-header-platform-icon ' . esc_attr( $color ) . '-icon">' . wp_kses( $icon, self::icon_allowed_html() ) . '</div>';
                        echo '</div>';
                    } elseif ( !$show_avatar || !$avatar ) {
                        // No avatar - show platform icon small instead
                        echo '<div class="yatoon-sf-header-icon-only ' . esc_attr( $color ) . '-icon">' . wp_kses( $icon, self::icon_allowed_html() ) . '</div>';
                    }
                    echo '<div class="yatoon-sf-header-info">';
                    if ( $show_name && $name ) {
                        echo '<strong class="yatoon-sf-header-name">' . esc_html( $name ) . '</strong>';
                    }
                    if ( $show_followers && $follows ) {
                        echo '<span class="yatoon-sf-header-followers">' . esc_html( $follows ) . ' followers</span>';
                    }
                    if ( $show_bio && $bio ) {
                        echo '<p class="yatoon-sf-header-bio">' . esc_html( $bio ) . '</p>';
                    }
                    echo '</div>';
                    // .header-info
                    echo '</div>';
                    // .header-left
                    // Right: follow button
                    if ( $show_follow_btn && $url ) {
                        echo '<a href="' . esc_url( $url ) . '" target="_blank" rel="noopener" class="yatoon-sf-follow-btn ' . esc_attr( $color ) . '-btn">' . esc_html( $label ) . '</a>';
                    }
                    echo '</div>';
                    // .header-card
                }
                echo '</div>';
                // .yatoon-sf-headers
            }
        }
        ?>

        <div class="yatoon-sf-grid yatoon-sf-grid--<?php echo esc_attr( $layout ); ?>" style="--yatoon-cols:<?php 
        echo esc_attr( $columns );
        ?>;--yatoon-gap:<?php 
        echo esc_attr( $gap );
        ?>px;">
            <?php 
        foreach ( $photos as $photo ) {
            $has_image = ! empty( $photo->media_url );
            $is_video = in_array( $photo->media_type, array( 'VIDEO', 'REELS' ), true );
            // For video items, the grid/lightbox trigger shows a poster
            // image (thumbnail) - media_url holds the actual video file,
            // which only gets loaded once the lightbox opens.
            $img_src = $is_video ? ( ! empty( $photo->thumbnail ) ? $photo->thumbnail : '' ) : $photo->media_url;
            $has_poster = ! empty( $img_src );
            $url = esc_url( $photo->media_url );
            $link = esc_url( $photo->permalink );
            $alt = esc_attr( wp_strip_all_tags( $photo->caption ) );
            $title = wp_strip_all_tags( $photo->caption );
            $badge_class = ( $photo->platform === 'instagram' ? 'yatoon-sf-badge--ig' : 'yatoon-sf-badge--fb' );
            $badge_label = ( $photo->platform === 'instagram' ? 'IG' : 'FB' );
            $platform_label = ( $photo->platform === 'instagram' ? 'Instagram' : 'Facebook' );
            $date_label = ! empty( $photo->taken_at ) ? mysql2date( get_option( 'date_format' ), $photo->taken_at ) : '';
            ?>
            <div class="yatoon-sf-item yatoon-sf-item--<?php echo esc_attr( $display ); ?><?php echo $has_image ? '' : ' yatoon-sf-item--no-image'; ?>">
                <?php 
            if ( ( $lightbox && $has_image ) || ( $open_link && $link ) ) {
                ?>
                <a href="<?php 
                echo esc_url( $lightbox && $has_image ? $url : $link );
                ?>" <?php echo $lightbox && $has_image ? '' : 'target="_blank" rel="noopener noreferrer"'; ?> class="yatoon-sf-link" aria-label="<?php 
                echo esc_attr( $alt );
                ?>"<?php if ( $lightbox && $has_image ) { ?>
                    data-yatoon-sf-lightbox="1"
                    data-image="<?php echo esc_url( $has_poster ? $img_src : $url ); ?>"
                    <?php if ( $is_video ) { ?>
                    data-type="video"
                    data-video="<?php echo esc_url( $url ); ?>"
                    <?php } ?>
                    data-caption="<?php echo esc_attr( $title ); ?>"
                    data-platform="<?php echo esc_attr( $platform_label ); ?>"
                    data-date="<?php echo esc_attr( $date_label ); ?>"
                    data-post-url="<?php echo esc_url( $link ); ?>"
                <?php } ?>>
                <?php 
            }
            ?>
                    <?php if ( 'text' !== $display && $has_image ) { ?>
                    <div class="yatoon-sf-img-wrap">
                        <?php if ( $has_poster ) { ?>
                        <img src="<?php 
            echo esc_url( $img_src );
            ?>" alt="<?php 
            echo esc_attr( $alt );
            ?>" loading="lazy" class="yatoon-sf-img" />
                        <?php } elseif ( $is_video ) { ?>
                        <div class="yatoon-sf-img yatoon-sf-img--video-noposter" aria-hidden="true"></div>
                        <?php } ?>
                        <?php if ( $is_video ) { ?>
                        <span class="yatoon-sf-play-icon" aria-hidden="true"></span>
                        <?php } ?>
                        <span class="yatoon-sf-badge <?php 
            echo esc_attr( $badge_class );
            ?>"><?php 
            echo esc_html( $badge_label );
                        ?></span>
                        <div class="yatoon-sf-overlay"></div>
                        <span class="yatoon-sf-view-label"><?php echo $is_video ? esc_html__( 'Play', 'yatoon-social-feed' ) : esc_html__( 'View', 'yatoon-social-feed' ); ?></span>
                    </div>
                    <?php } ?>
                    <?php 
            if ( ( 'text' === $display || $show_caption ) && $title ) {
                ?>
                    <p class="yatoon-sf-caption"><?php 
                echo esc_html( 'text' === $display ? $title : wp_trim_words( $title, 24, '...' ) );
                ?></p>
                    <?php 
            }
            ?>
                <?php 
            if ( ( $lightbox && $has_image ) || ( $open_link && $link ) ) {
                ?>
                </a>
                <?php 
            }
            ?>
            </div>
            <?php 
        }
        ?>
        </div>
        <?php 
        $yatoon_sf_show_credit = true;
        if ( function_exists( 'yatoon_sf_fs' ) && method_exists( yatoon_sf_fs(), 'can_use_premium_code__premium_only' ) && yatoon_sf_fs()->can_use_premium_code__premium_only() ) {
            $yatoon_sf_show_credit = false;
        }
        if ( $yatoon_sf_show_credit ) {
            ?>
        <div class="yatoon-sf-credit">
            <a href="https://yatoon.com/" target="_blank" rel="noopener noreferrer">by Yatoon.com</a>
        </div>
        <?php 
        }
        ?>
        <?php 
        return ob_get_clean();
    }

    /**
     * Allow-list for our small set of hardcoded platform icon SVGs.
     * These SVG strings are fixed in this file (never derived from user
     * input), but we still run them through wp_kses with an explicit
     * allow-list so the output passes static escaping checks and stays
     * safe if the icon set is ever extended.
     */
    private static function icon_allowed_html() {
        return array(
            'svg'    => array(
                'viewbox'      => true,
                'fill'         => true,
                'stroke'       => true,
                'stroke-width' => true,
                'width'        => true,
                'height'       => true,
                'xmlns'        => true,
            ),
            'rect'   => array(
                'x'      => true,
                'y'      => true,
                'width'  => true,
                'height' => true,
                'rx'     => true,
            ),
            'circle' => array(
                'cx'     => true,
                'cy'     => true,
                'r'      => true,
                'fill'   => true,
                'stroke' => true,
            ),
            'path'   => array(
                'd' => true,
            ),
        );
    }

    /**
     * Pro-only custom CSS override. Even if the option somehow has a
     * value saved (e.g. a site was downgraded from Pro to Free after
     * having set it), we only ever output it while premium code is
     * actually unlocked - this keeps the feature a genuine Pro benefit
     * rather than something that leaks through in the free version.
     */
    private function get_premium_custom_css() {
        if ( ! function_exists( 'yatoon_sf_fs' ) || ! method_exists( yatoon_sf_fs(), 'can_use_premium_code__premium_only' ) || ! yatoon_sf_fs()->can_use_premium_code__premium_only() ) {
            return '';
        }
        $css = get_option( 'yatoon_sf_custom_css', '' );
        if ( empty( $css ) ) {
            return '';
        }
        // Strip any HTML tags so a saved value can never break out of the
        // <style> element (e.g. "</style><script>...").
        return wp_strip_all_tags( $css );
    }

    private function get_photos( $platform, $limit ) {
        global $wpdb;
        $table = $wpdb->prefix . 'yatoon_sf_photos';
        // phpcs:disable WordPress.DB.DirectDatabaseQuery
        if ( $platform === 'all' ) {
            return $wpdb->get_results( $wpdb->prepare( "SELECT * FROM " . esc_sql( $table ) . " ORDER BY taken_at DESC LIMIT %d", $limit ) );
            // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
        }
        return $wpdb->get_results( $wpdb->prepare( "SELECT * FROM " . esc_sql( $table ) . " WHERE platform = %s ORDER BY taken_at DESC LIMIT %d", $platform, $limit ) );
        // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
        // phpcs:enable
    }

    private function filter_photos_for_display( $photos, $display, $limit ) {
        $filtered = array();
        foreach ( $photos as $photo ) {
            $has_image = ! empty( $photo->media_url );
            $has_text  = ! empty( $photo->caption );
            if ( 'image' === $display && ! $has_image ) {
                continue;
            }
            if ( 'text' === $display && ! $has_text ) {
                continue;
            }
            if ( 'both' === $display && ! $has_image && ! $has_text ) {
                continue;
            }
            $filtered[] = $photo;
            if ( count( $filtered ) >= $limit ) {
                break;
            }
        }
        return $filtered;
    }

}
