<?php
defined( 'ABSPATH' ) || exit;

class PIPEBU_Publisher {

    public static function publish( array $data ) {
        if ( ! class_exists( 'WooCommerce' ) ) {
            return new WP_Error( 'pb_wc', __( 'WooCommerce is not active.', 'pipeline-buster' ) );
        }

        // Guide Mode: skip product creation — only create How To post.
        if ( ! empty( $data['guide_mode'] ) ) {
            return self::publish_guide_mode( $data );
        }

        $has_colors = ! empty( $data['has_colors'] ) && ! empty( $data['colors'] );
        $product_id = $has_colors
            ? self::create_variable_product( $data )
            : self::create_product( $data );
        if ( is_wp_error( $product_id ) ) {
            return $product_id;
        }

        $howto_id = null;
        if ( ! empty( $data['howto_title'] ) && ! empty( $data['howto_content'] ) ) {
            $howto_id = self::create_howto_post( $data, $product_id );
            if ( is_wp_error( $howto_id ) ) {
                $howto_id = null;
            }
        }

        if ( $howto_id && PIPEBU_Settings::howto_link_enabled() ) {
            self::inject_howto_link( $product_id, $howto_id );
        }

        return [
            'product_id' => $product_id,
            'howto_id'   => $howto_id,
        ];
    }

    // -------------------------------------------------------------------------
    // Guide Mode publish — How To only, optionally linked to existing product
    // -------------------------------------------------------------------------

    private static function publish_guide_mode( array $data ): array|WP_Error {
        $existing_product_id = absint( $data['existing_product_id'] ?? 0 );

        // Pass product context to How To post creator.
        $howto_id = self::create_howto_post( $data, $existing_product_id );
        if ( is_wp_error( $howto_id ) ) {
            return $howto_id;
        }

        // Inject How To link into the existing product's short description.
        if ( $existing_product_id && PIPEBU_Settings::howto_link_enabled() ) {
            self::inject_howto_link( $existing_product_id, $howto_id );
        }

        return [
            'product_id' => $existing_product_id ?: null,
            'howto_id'   => $howto_id,
            'guide_mode' => true,
        ];
    }

    // -------------------------------------------------------------------------
    // WooCommerce product
    // -------------------------------------------------------------------------

    private static function create_product( array $data ): int|WP_Error {
        global $wpdb;

        $status  = PIPEBU_Settings::publish_status();
        $is_free = ! (bool) apply_filters( 'pipebu_has_paid_license', false );
        $product = new WC_Product_Simple();

        $description = $data['description'] ?? '';
        if ( $is_free ) {
            $description .= "\n" . self::attribution_html();
        }

        $product->set_name( $data['product_name'] ?? '' );
        $product->set_status( $status );
        $product->set_description( $description );
        $product->set_short_description( $data['short_description'] ?? '' );

        if ( isset( $data['regular_price'] ) && $data['regular_price'] !== '' ) {
            $product->set_regular_price( wc_format_decimal( $data['regular_price'] ) );
        }
        if ( isset( $data['sale_price'] ) && $data['sale_price'] !== '' ) {
            $product->set_sale_price( wc_format_decimal( $data['sale_price'] ) );
        }
        if ( isset( $data['stock_quantity'] ) && $data['stock_quantity'] !== '' ) {
            $product->set_manage_stock( true );
            $product->set_stock_quantity( (int) $data['stock_quantity'] );
            $product->set_stock_status( 'instock' );
        }

        if ( ! empty( $data['category_ids'] ) ) {
            $product->set_category_ids( array_map( 'absint', (array) $data['category_ids'] ) );
        }

        if ( ! empty( $data['attachment_ids'] ) ) {
            $ids      = array_map( 'absint', (array) $data['attachment_ids'] );
            $hero_idx = max( 0, min( (int) ( $data['hero_index'] ?? 0 ), count( $ids ) - 1 ) );
            $hero_id  = $ids[ $hero_idx ];
            $gallery  = array_values( array_filter( $ids, fn( $id ) => $id !== $hero_id ) );

            $product->set_image_id( $hero_id );
            $product->set_gallery_image_ids( $gallery );
        }

        $product_id = $product->save();
        if ( ! $product_id ) {
            return new WP_Error( 'pb_save', __( 'Failed to save WooCommerce product.', 'pipeline-buster' ) );
        }

        update_post_meta( $product_id, 'pipebu_generated', 1 );

        // HTML comment — all tiers. Appended via direct DB write to survive kses.
        $raw = get_post_field( 'post_content', $product_id, 'raw' );
        $wpdb->update( $wpdb->posts, [ 'post_content' => $raw . "\n" . self::attribution_comment() ], [ 'ID' => $product_id ] );
        clean_post_cache( $product_id );

        if ( ! empty( $data['yoast_focus_keyword'] ) ) {
            update_post_meta( $product_id, '_yoast_wpseo_focuskw', sanitize_text_field( $data['yoast_focus_keyword'] ) );
        }
        if ( ! empty( $data['yoast_meta_description'] ) ) {
            update_post_meta( $product_id, '_yoast_wpseo_metadesc', sanitize_text_field( $data['yoast_meta_description'] ) );
        }

        return $product_id;
    }

    // -------------------------------------------------------------------------
    // WooCommerce variable product (color variations path)
    // -------------------------------------------------------------------------

    private static function create_variable_product( array $data ): int|WP_Error {
        global $wpdb;

        $status  = PIPEBU_Settings::publish_status();
        $is_free = ! (bool) apply_filters( 'pipebu_has_paid_license', false );
        $product = new WC_Product_Variable();

        $description = $data['description'] ?? '';
        if ( $is_free ) {
            $description .= "\n" . self::attribution_html();
        }

        $product->set_name( $data['product_name'] ?? '' );
        $product->set_status( $status );
        $product->set_description( $description );
        $product->set_short_description( $data['short_description'] ?? '' );

        if ( ! empty( $data['category_ids'] ) ) {
            $product->set_category_ids( array_map( 'absint', (array) $data['category_ids'] ) );
        }

        if ( ! empty( $data['attachment_ids'] ) ) {
            $ids      = array_map( 'absint', (array) $data['attachment_ids'] );
            $hero_idx = max( 0, min( (int) ( $data['hero_index'] ?? 0 ), count( $ids ) - 1 ) );
            $hero_id  = $ids[ $hero_idx ];
            $gallery  = array_values( array_filter( $ids, fn( $id ) => $id !== $hero_id ) );

            $product->set_image_id( $hero_id );
            $product->set_gallery_image_ids( $gallery );
        }

        $product_id = $product->save();
        if ( ! $product_id ) {
            return new WP_Error( 'pb_save', __( 'Failed to save WooCommerce variable product.', 'pipeline-buster' ) );
        }

        update_post_meta( $product_id, 'pipebu_generated', 1 );

        $raw = get_post_field( 'post_content', $product_id, 'raw' );
        $wpdb->update( $wpdb->posts, [ 'post_content' => $raw . "\n" . self::attribution_comment() ], [ 'ID' => $product_id ] );
        clean_post_cache( $product_id );

        if ( ! empty( $data['yoast_focus_keyword'] ) ) {
            update_post_meta( $product_id, '_yoast_wpseo_focuskw', sanitize_text_field( $data['yoast_focus_keyword'] ) );
        }
        if ( ! empty( $data['yoast_meta_description'] ) ) {
            update_post_meta( $product_id, '_yoast_wpseo_metadesc', sanitize_text_field( $data['yoast_meta_description'] ) );
        }

        PIPEBU_Color::create_variations( $product_id, $data['colors'] );

        return $product_id;
    }

    // -------------------------------------------------------------------------
    // How To post
    // -------------------------------------------------------------------------

    private static function create_howto_post( array $data, int $product_id ): int|WP_Error {
        global $wpdb;

        $product_url = get_permalink( $product_id );
        $is_free     = ! (bool) apply_filters( 'pipebu_has_paid_license', false );

        $content = str_replace(
            [ '[PRODUCT_LINK]', '[PARTS_LINK]' ],
            [ esc_url( $product_url ), esc_url( get_home_url() ) ],
            $data['howto_content'] ?? ''
        );

        if ( $is_free ) {
            $content .= "\n" . self::attribution_html();
        }

        $status    = PIPEBU_Settings::publish_status();
        $post_args = [
            'post_title'    => sanitize_text_field( $data['howto_title'] ?? '' ),
            'post_content'  => wp_kses_post( $content ),
            'post_status'   => $status,
            'post_type'     => 'post',
        ];

        $cat_id = PIPEBU_Settings::howto_category();
        if ( $cat_id ) {
            $post_args['post_category'] = [ $cat_id ];
        }

        $post_id = wp_insert_post( $post_args, true );
        if ( is_wp_error( $post_id ) ) {
            return $post_id;
        }

        // HTML comment — all tiers. Appended via direct DB write to survive kses.
        $raw = get_post_field( 'post_content', $post_id, 'raw' );
        $wpdb->update( $wpdb->posts, [ 'post_content' => $raw . "\n" . self::attribution_comment() ], [ 'ID' => $post_id ] );
        clean_post_cache( $post_id );

        // Featured image = last attachment (typically the flyer).
        if ( ! empty( $data['attachment_ids'] ) ) {
            $ids = array_map( 'absint', (array) $data['attachment_ids'] );
            set_post_thumbnail( $post_id, end( $ids ) );
        }

        if ( ! empty( $data['yoast_focus_keyword'] ) ) {
            update_post_meta( $post_id, '_yoast_wpseo_focuskw',
                sanitize_text_field( $data['yoast_focus_keyword'] ) . ' how to use' );
        }
        if ( ! empty( $data['howto_meta_description'] ) ) {
            update_post_meta( $post_id, '_yoast_wpseo_metadesc',
                sanitize_text_field( $data['howto_meta_description'] ) );
        }

        return $post_id;
    }

    // -------------------------------------------------------------------------
    // Inject How To link using the user-defined template
    // -------------------------------------------------------------------------

    private static function inject_howto_link( int $product_id, int $howto_id ): void {
        $product    = wc_get_product( $product_id );
        $short      = $product->get_short_description();
        $howto_url  = get_permalink( $howto_id );
        $template   = PIPEBU_Settings::short_desc_template();
        $link_block = str_replace( '[HOWTO_LINK]', esc_url( $howto_url ), $template );

        $product->set_short_description( $short . "\n" . $link_block );
        $product->save();
    }

    // -------------------------------------------------------------------------
    // Attribution helpers
    // -------------------------------------------------------------------------

    /**
     * Visible fine-print — free tier only.
     * Survives wp_kses_post (style on p is allowed in post context).
     */
    private static function attribution_html(): string {
        return '<p style="font-size:11px;color:#aaa;border-top:1px solid #eee;padding-top:10px;margin-top:2em;">'
             . '<a href="https://pipelinebuster.com" rel="nofollow" style="color:#0d4740;text-decoration:none;font-weight:600;">Pipeline Buster</a>'
             . ' by <a href="https://zoa.captelek.net" rel="nofollow" style="color:#0d4740;text-decoration:none;">ZOA</a>'
             . ' &mdash; AI-generated product content'
             . '</p>';
    }

    /**
     * HTML comment — all tiers. Written via direct DB update to bypass kses.
     */
    private static function attribution_comment(): string {
        return '<!-- Pipeline Buster by ZOA | pipelinebuster.com | AI-generated product content -->';
    }
}
