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

/**
 * Adds the product metabox to posts (Classic + Gutenberg).
 * Supports multiple products, shortcode generator, and manual/API entry.
 */
class SAA_Metabox {

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

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

    /**
     * Register hooks
     */
    public function init(): void {
        add_action('add_meta_boxes', [$this, 'add_metabox']);
        add_action('save_post',       [$this, 'save_metabox']);
        add_action('admin_enqueue_scripts', [$this, 'enqueue_assets']);
    }

    /**
     * Add metabox under post editor
     */
    public function add_metabox(): void {
        add_meta_box(
            'saa_products',
            __('Amazon Products', 'slurpywp-saa-lang'),
            [$this, 'render_metabox'],
            ['post', 'page'],
            'normal',
            'default'
        );
    }

    /**
     * Render metabox
     */
    public function render_metabox($post): void {
        if (!current_user_can('manage_options')) {
            echo '<p>' . esc_html__('You do not have permission to edit these products.', 'slurpywp-saa-lang') . '</p>';
            return;
        }

        wp_nonce_field('saa_metabox_save', 'saa_metabox_nonce');

        $products = get_post_meta($post->ID, '_saa_products', true);
        if (!is_array($products)) {
            $products = [];
        }
        ?>
        <div id="saa-metabox-container">
            <p class="saa-instruction">
                <?php esc_html_e('You must create a post first (by saving or publishing) before you can add a product.', 'slurpywp-saa-lang'); ?>
            </p>
        
            <button type="button" class="button saa-add-product">
                <?php esc_html_e('Add Product', 'slurpywp-saa-lang'); ?>
            </button>

            <div class="saa-products">
                <?php foreach ($products as $index => $prod): ?>
                    <?php $this->render_product_fields($index, $prod, false); ?>
                <?php endforeach; ?>

                <!-- Hidden template row (no name attributes) -->
                <?php $this->render_product_fields(0, [], true); ?>
            </div>
        </div>
        <?php
    }

    /**
     * Render a single product row
     */
    private function render_product_fields(int $index, array $prod = [], bool $is_template = false): void {
        $defaults = [
            'title'  => '',
            'price'  => '',
            'desc'   => '',
            'img'    => '',
            'url'    => '',
            'asin'   => '',
            'manual' => 0,
        ];
        $prod = wp_parse_args($prod, $defaults);

        $row_classes = 'saa-product-row';
        if ($is_template) {
            $row_classes .= ' saa-template';
        }

        // Prefix for input names (empty if template)
        $name_prefix = $is_template ? '' : 'saa_products[' . $index . ']';
        ?>
        <div class="<?php echo esc_attr($row_classes); ?>" <?php if ($is_template) echo 'style="display:none"'; ?>>
            <h4><?php printf(__('Product %d', 'slurpywp-saa-lang'), $index + 1); ?></h4>

            <div class="saa-fields">
                <div class="saa-field-row">
                    <label class="saa-label"><?php esc_html_e('Original Amazon Product URL:', 'slurpywp-saa-lang'); ?></label>
                    <div class="saa-field">
                        <input type="text" data-field="asin"
                            <?php if ($name_prefix) echo 'name="' . esc_attr($name_prefix . '[asin]') . '"'; ?>
                            value="<?php echo esc_attr($prod['asin']); ?>"
                            class="regular-text">
                        <p class="description">
                            <?php esc_html_e('Paste the full Amazon product URL (not your affiliate link). The ASIN will be extracted automatically.', 'slurpywp-saa-lang'); ?>
                        </p>
                    </div>
                </div>

                <div class="saa-field-row">
                    <label class="saa-label"></label>
                    <div class="saa-field">
                        <label>
                            <input type="checkbox" data-field="manual"
                                <?php if ($name_prefix) echo 'name="' . esc_attr($name_prefix . '[manual]') . '"'; ?>
                                value="1" <?php checked($prod['manual'], 1); ?>>
                            <?php esc_html_e('Enter product manually', 'slurpywp-saa-lang'); ?>
                        </label>
                    </div>
                </div>

                <div class="saa-manual-fields" <?php if (!$prod['manual']) echo 'style="display:none"'; ?>>
                    <div class="saa-field-row">
                        <label class="saa-label"><?php esc_html_e('Title:', 'slurpywp-saa-lang'); ?></label>
                        <div class="saa-field">
                            <input type="text" data-field="title"
                                <?php if ($name_prefix) echo 'name="' . esc_attr($name_prefix . '[title]') . '"'; ?>
                                value="<?php echo esc_attr($prod['title']); ?>"
                                class="regular-text">
                        </div>
                    </div>

                    <div class="saa-field-row">
                        <label class="saa-label"><?php esc_html_e('Description:', 'slurpywp-saa-lang'); ?></label>
                        <div class="saa-field">
                            <textarea rows="4" class="large-text" data-field="desc"
                                <?php if ($name_prefix) echo 'name="' . esc_attr($name_prefix . '[desc]') . '"'; ?>><?php echo esc_textarea($prod['desc']); ?></textarea>
                        </div>
                    </div>

                    <!-- Price under description -->
                    <div class="saa-field-row">
                        <label class="saa-label"><?php esc_html_e('Price:', 'slurpywp-saa-lang'); ?></label>
                        <div class="saa-field price-field">
                            <input type="text" class="small-text half-width" data-field="price"
                                <?php if ($name_prefix) echo 'name="' . esc_attr($name_prefix . '[price]') . '"'; ?>
                                value="<?php echo esc_attr($prod['price']); ?>">
                            <span class="tooltip"><?php esc_html_e('Include currency symbol.', 'slurpywp-saa-lang'); ?></span>
                        </div>
                    </div>

                    <div class="saa-field-row">
                        <label class="saa-label"><?php esc_html_e('Image URL:', 'slurpywp-saa-lang'); ?></label>
                        <div class="saa-field">
                            <input type="text" class="regular-text image-url" data-field="img"
                                <?php if ($name_prefix) echo 'name="' . esc_attr($name_prefix . '[img]') . '"'; ?>
                                value="<?php echo esc_url($prod['img']); ?>">
                            <button type="button" class="button saa-upload-image"><?php esc_html_e('Upload', 'slurpywp-saa-lang'); ?></button>
                        </div>
                    </div>

                    <div class="saa-field-row">
                        <label class="saa-label"><?php esc_html_e('Your Affiliate URL:', 'slurpywp-saa-lang'); ?></label>
                        <div class="saa-field">
                            <input type="text" class="regular-text" data-field="url"
                                <?php if ($name_prefix) echo 'name="' . esc_attr($name_prefix . '[url]') . '"'; ?>
                                value="<?php echo esc_url($prod['url']); ?>" placeholder="https://">
                        </div>
                    </div>
                </div>
            </div>

            <!-- Shortcode box row (aligned with fields) -->
            <div class="saa-field-row">
                <label class="saa-label"></label>
                <div class="saa-field">
                    <div class="saa-shortcode-box">
                        <p><?php esc_html_e('Copy this shortcode and paste it anywhere in your content to display this product.', 'slurpywp-saa-lang'); ?></p>
                        <div class="saa-shortcode-line">
                            <code>[amazon_product asin="<?php echo esc_attr($prod['asin']); ?>"]</code>
                            <button type="button" class="button saa-copy-shortcode"><?php esc_html_e('Copy', 'slurpywp-saa-lang'); ?></button>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Remove button row (aligned with fields) -->
            <div class="saa-field-row">
                <label class="saa-label"></label>
                <div class="saa-field">
                    <button type="button" class="button link-delete saa-remove-product">
                        <?php esc_html_e('Remove Product', 'slurpywp-saa-lang'); ?>
                    </button>
                </div>
            </div>
        </div>
        <?php
    }

    /**
     * Save metabox data
     */
    public function save_metabox(int $post_id): void {
        if (!isset($_POST['saa_metabox_nonce']) || !wp_verify_nonce($_POST['saa_metabox_nonce'], 'saa_metabox_save')) {
            return;
        }

        if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
            return;
        }

        if (!current_user_can('manage_options')) {
            return;
        }

        if (!isset($_POST['saa_products']) || !is_array($_POST['saa_products'])) {
            delete_post_meta($post_id, '_saa_products');
            return;
        }

        $clean = [];
        foreach ($_POST['saa_products'] as $prod) {
            // Skip empty rows
            if (
                empty($prod['asin']) &&
                empty($prod['title']) &&
                empty($prod['price']) &&
                empty($prod['desc']) &&
                empty($prod['img']) &&
                empty($prod['url'])
            ) {
                continue;
            }

            $asin_input = trim($prod['asin'] ?? '');
            $asin = $this->extract_asin($asin_input);

            $clean[] = [
                'title'  => sanitize_text_field($prod['title'] ?? ''),
                'price'  => sanitize_text_field($prod['price'] ?? ''),
                'desc'   => sanitize_textarea_field($prod['desc'] ?? ''),
                'img'    => esc_url_raw($prod['img'] ?? ''),
                'url'    => esc_url_raw($prod['url'] ?? ''),
                'asin'   => $asin,
                'manual' => !empty($prod['manual']) ? 1 : 0,
            ];
        }

        if (!empty($clean)) {
            update_post_meta($post_id, '_saa_products', $clean);
        } else {
            delete_post_meta($post_id, '_saa_products');
        }
    }

    /**
     * Extract ASIN from either ASIN itself or full Amazon URL
     */
    private function extract_asin(string $input): string {
        // If input looks like a full Amazon URL, parse ASIN
        if (preg_match('/(?:dp|gp\/product)\/([A-Z0-9]{10})/i', $input, $matches)) {
            return strtoupper($matches[1]);
        }
        // Otherwise assume it's already an ASIN
        return sanitize_text_field($input);
    }

    /**
     * Enqueue CSS/JS for metabox
     */
    public function enqueue_assets($hook): void {
        global $post;
        if (!isset($post) || !in_array($hook, ['post.php', 'post-new.php'], true)) {
            return;
        }

        wp_enqueue_style(
            'saa-metabox',
            SAA_PLUGIN_URL . 'metabox/css/metabox.css',
            [],
            SAA_PLUGIN_VERSION
        );

        wp_enqueue_script(
            'saa-metabox',
            SAA_PLUGIN_URL . 'metabox/js/metabox.js',
            ['jquery'],
            SAA_PLUGIN_VERSION,
            true
        );

        wp_localize_script('saa-metabox', 'saaMetabox', [
            'copy_text' => __('Shortcode copied!', 'slurpywp-saa-lang'),
        ]);

        wp_enqueue_media();
    }
}
