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

class SAA_Frontend {

    /** @var SAA_Plugin */
    private $plugin;

    public function __construct(SAA_Plugin $plugin) {
        $this->plugin = $plugin;
    }

    public function init(): void {
        add_shortcode('amazon_product', [$this, 'render_shortcode']);
        add_action('wp_enqueue_scripts', [$this, 'enqueue_assets']);
    }

    public function enqueue_assets(): void {
        wp_enqueue_style(
            'saa-frontend',
            SAA_PLUGIN_URL . 'frontend/css/style.css',
            [],
            SAA_PLUGIN_VERSION
        );
    }

    /**
     * Render [amazon_product asin="..."]
     */
    public function render_shortcode($atts): string {
        global $post;

        $atts = shortcode_atts([
            'asin' => '',
        ], $atts, 'amazon_product');

        if (empty($atts['asin']) || !$post) {
            return '';
        }

        $products = get_post_meta($post->ID, '_saa_products', true);
        if (!is_array($products)) {
            return '';
        }

        foreach ($products as $prod) {
            if (!empty($prod['asin']) && $prod['asin'] === $atts['asin']) {
                return $this->render_product_box($prod);
            }
        }

        return ''; // no match
    }

    /**
     * Render product HTML (aligned with CSS classes)
     */
    private function render_product_box(array $prod): string {
        $title = esc_html($prod['title']);
        $price = esc_html($prod['price']);
        $desc  = esc_html($prod['desc']);
        $img   = esc_url($prod['img']);
        $url   = esc_url($prod['url']);
        $asin  = esc_attr($prod['asin']);

        ob_start();
        ?>
        <div class="saa-product-box">
            <a href="<?php echo $url; ?>" target="_blank" rel="nofollow sponsored" class="saa-product-link">
                <div class="saa-product-image">
                    <?php if ($img): ?>
                        <img src="<?php echo $img; ?>" alt="<?php echo $title ?: $asin; ?>">
                    <?php endif; ?>
                </div>
                <div class="saa-product-details">
                    <?php if ($title): ?>
                        <h3 class="saa-product-title"><?php echo $title; ?></h3>
                    <?php endif; ?>
                    <?php if ($price): ?>
                        <div class="saa-product-price"><?php echo $price; ?></div>
                    <?php endif; ?>
                    <?php if ($desc): ?>
                        <p class="saa-product-desc"><?php echo $desc; ?></p>
                    <?php endif; ?>
                    <button class="saa-buy-btn"><?php esc_html_e('Buy Now', 'slurpywp-saa-lang'); ?></button>
                </div>
            </a>
        </div>
        <p class="saa-disclaimer">
            <?php esc_html_e('We may earn a commission if you buy through these links.', 'slurpywp-saa-lang'); ?>
        </p>
        <?php
        return ob_get_clean();
    }
}
