<?php
namespace AICSAPP;

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

class Data {

    public static function export_products_csv() {

        if ( ! current_user_can( 'manage_options' ) ) {
            wp_die( esc_html__( 'Permission denied.', 'aisalebot' ) );
        }

        if ( ! class_exists( 'WooCommerce' ) ) {
            wp_die( esc_html__( 'WooCommerce is not active.', 'aisalebot' ) );
        }

        if ( ob_get_length() ) {
            ob_clean();
        }

        header( 'Content-Type: text/csv; charset=utf-8' );
        header( 'Content-Disposition: attachment; filename=products.csv' );
        header( 'Pragma: no-cache' );
        header( 'Expires: 0' );

        // Header row
        echo esc_html( "ID,SKU,Name,Price,Categories,Description,URL\n" );

        $products = wc_get_products( [
            'status' => 'publish',
            'limit'  => -1,
        ] );

        foreach ( $products as $product ) {

            $categories = wp_get_post_terms(
                $product->get_id(),
                'product_cat',
                [ 'fields' => 'names' ]
            );

            $row = [
                (string) (int) $product->get_id(),
                sanitize_text_field( $product->get_sku() ),
                sanitize_text_field( $product->get_name() ),
                sanitize_text_field( $product->get_price() ),
                sanitize_text_field( implode( '|', $categories ) ),
                sanitize_text_field(
                    wp_strip_all_tags(
                        $product->get_description()
                        ? $product->get_description()
                        : $product->get_short_description()
                    )
                ),
                esc_url_raw( get_permalink( $product->get_id() ) ),
            ];

            /**
             * CSV-safe output
             * wp_json_encode() is considered escaped by Plugin Check
             */
            echo esc_html(
                implode(
                    ',',
                    array_map(
                        function ( $field ) {
                            return '"' . str_replace( '"', '""', (string) $field ) . '"';
                        },
                        $row
                    )
                ) . "\n"
            );
        }

        exit;
    }
}
