<?php
declare(strict_types=1);
// ==================================================
// Nuclear Fancy Pants Edition™ -- NUCLEAR+++
// File: /modules/store-woocommerce.php
// Description: WooCommerce store provider module -- pulls products from the local WC install - NUCLEAR+++
// Last Edited: 2026-05-15
// ==================================================

namespace AutoMarketerAI\Modules;

use AutoMarketerAI\ModuleInterface;

defined('ABSPATH') || exit;

final class StoreWoocommerce implements ModuleInterface
{
    public function get_id(): string          { return 'store-woocommerce'; }
    public function get_name(): string        { return 'WooCommerce'; }
    public function get_category(): string    { return 'Store'; }
    public function get_logo_url(): string    { return ''; }
    public function get_model_count(): int    { return 0; }
    public function get_available_models(): array     { return []; }
    public function get_single_model_notice(): string { return ''; }
    public function get_api_key_prefix(): string      { return ''; }
    public function validate_api_key(string $key): bool { return true; }
    public function generate_raw(string $prompt, string $api_key, string $model): string { return ''; }
    public function is_free_allowed(): bool   { return false; }
    public function register(): void          {}
    public function activate(): void          {}

    public function get_description(): string
    {
        return 'Already running WooCommerce? AutoMarketer AI reads your product catalog directly -- no API keys needed. Products, prices, and sale events sync nightly.';
    }

    public function get_icon_svg(): string
    {
        return '<svg viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg"><rect width="32" height="32" rx="8" fill="#7F54B3"/><path d="M5 9.5C5 8.4 5.9 7.5 7 7.5h18c1.1 0 2 .9 2 2v9c0 1.1-.9 2-2 2h-7l-4 4v-4H7c-1.1 0-2-.9-2-2v-9z" fill="white"/><path d="M8 13h2.5l1 4.5 2-4.5h1.5l2 4.5 1-4.5H20" stroke="#7F54B3" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round"/></svg>';
    }

    public function deactivate(): void
    {
        // No credentials to clean up -- WooCommerce is local
    }

    public function is_connected(): bool
    {
        return class_exists('WooCommerce');
    }

    public function validate_credentials(array $credentials): bool|string
    {
        if (!class_exists('WooCommerce')) {
            return 'WooCommerce is not installed or not active on this site.';
        }

        return true;
    }

    public function save_credentials(array $credentials): void
    {
        // No credentials needed for WooCommerce -- it is local
    }

    public function delete_credentials(): void
    {
        // Nothing to delete
    }

    public function fetch_products(): array
    {
        if (!class_exists('WooCommerce') || !function_exists('wc_get_products')) {
            return [];
        }

        $all    = [];
        $page   = 1;
        $limit  = 100;

        while (true) {
            $wc_products = wc_get_products([
                'status'  => 'publish',
                'limit'   => $limit,
                'page'    => $page,
                'orderby' => 'date',
                'order'   => 'DESC',
            ]);

            if (empty($wc_products)) {
                break;
            }

            foreach ($wc_products as $product) {
                if (!($product instanceof \WC_Product)) {
                    continue;
                }

                $price      = $product->get_regular_price() !== '' ? (float) $product->get_regular_price() : null;
                $sale_price = $product->get_sale_price()    !== '' ? (float) $product->get_sale_price()    : null;
                $on_sale    = $product->is_on_sale();
                $currency   = strtoupper(get_woocommerce_currency());

                $image_id  = $product->get_image_id();
                $image_url = $image_id ? (string) wp_get_attachment_url((int) $image_id) : '';

                $stock = null;
                if ($product->managing_stock()) {
                    $stock = (int) $product->get_stock_quantity();
                }

                $all[] = [
                    'id'          => (string) $product->get_id(),
                    'name'        => $product->get_name(),
                    'description' => wp_strip_all_tags($product->get_description() ?: $product->get_short_description()),
                    'price'       => $price,
                    'currency'    => $currency,
                    'image_url'   => $image_url,
                    'url'         => (string) $product->get_permalink(),
                    'on_sale'     => $on_sale,
                    'sale_price'  => $on_sale ? $sale_price : null,
                    'stock'       => $stock,
                    'is_new'      => false,
                    'created_at'  => $product->get_date_created() ? $product->get_date_created()->format('c') : gmdate('c'),
                ];
            }

            if (count($wc_products) < $limit) {
                break;
            }

            $page++;
        }

        return $all;
    }
}