<?php

namespace SoftminalB2B\Import;

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

use SoftminalB2B\Models\PriceRule;

/**
 * Imports from Wholesale Suite — "WooCommerce Wholesale Prices" (H8).
 *
 * Its model is small: wholesale roles live in one option, a user is wholesale by
 * WP role, and each product carries an absolute wholesale price in postmeta
 * keyed by role slug. Because that price is an absolute amount, it maps to a
 * fixed-price rule (type `fixed` = set the price to this value), one per product
 * per role.
 *
 * All reads are of core tables / options, so this works whether or not the
 * source plugin is active, and never writes to its keys.
 */
class WholesaleSuiteImporter extends SourceImporter
{
    private const ROLES_OPTION = 'wwp_options_registered_custom_roles';

    public function slug(): string
    {
        return 'wholesale_suite';
    }

    public function label(): string
    {
        return __('Wholesale Suite (WooCommerce Wholesale Prices)', 'softminal-b2b-wholesale-for-woocommerce');
    }

    public function isPresent(): bool
    {
        return !empty($this->roles());
    }

    /**
     * @return array<string, string> role slug => label
     */
    private function roles(): array
    {
        $raw   = maybe_unserialize(get_option(self::ROLES_OPTION, []));
        $out   = [];

        if (is_array($raw)) {
            foreach ($raw as $slug => $info) {
                $out[(string) $slug] = is_array($info) && !empty($info['roleName'])
                    ? (string) $info['roleName']
                    : (string) $slug;
            }
        }

        return $out;
    }

    /**
     * @return array<string, mixed>
     */
    public function collect(): array
    {
        global $wpdb;

        $roles             = $this->roles();
        $groups            = [];
        $users             = [];
        $rules             = [];
        $tax_exempt_groups = [];
        $warnings          = [];

        // A store-wide %-off per role (managed even in the free plugin). Easy to
        // miss and high-impact — maps to one global percentage rule per role.
        $blanket = get_option('wwpp_option_wholesale_role_general_discount_mapping', []);
        $blanket = is_array($blanket) ? $blanket : [];

        // "Do not apply tax to all wholesale roles" — a single global toggle.
        $taxExemptAll = $this->truthy(get_option('wwp_settings_tax_exempt_wholesale_users', ''));

        foreach ($roles as $slug => $label) {
            $groups[] = ['source_id' => $slug, 'name' => $label];

            // Users holding this wholesale role.
            foreach (get_users(['role' => $slug, 'fields' => 'ID']) as $userId) {
                $users[] = [
                    'user_id'         => (int) $userId,
                    'source_group_id' => $slug,
                    'status'          => 'approved', // free Wholesale Suite has no approval flow
                ];
            }

            // Every product/variation carrying this role's wholesale price.
            $metaKey = $slug . '_wholesale_price';

            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
            $rows = $wpdb->get_results($wpdb->prepare(
                "SELECT post_id, meta_value FROM {$wpdb->postmeta} WHERE meta_key = %s AND meta_value <> ''",
                $metaKey
            ));

            foreach ($rows as $row) {
                $productId = (int) $row->post_id;
                $price     = (float) $row->meta_value;

                if ($productId <= 0 || $price <= 0) {
                    continue;
                }

                $rules[] = [
                    'source_key'      => 'wsp:' . $slug . ':' . $productId,
                    'source_group_id' => $slug,
                    'customer_id'     => null,
                    'scope'           => PriceRule::SCOPE_PRODUCT,
                    'object_id'       => $productId,
                    'type'            => PriceRule::TYPE_FIXED,
                    'value'           => $price,
                    'min_qty'         => 1,
                ];
            }

            // Store-wide blanket discount for this role → one global percent rule.
            $discount = (float) ($blanket[$slug] ?? 0);
            if ($discount > 0) {
                $rules[] = [
                    'source_key'      => 'wsblanket:' . $slug,
                    'source_group_id' => $slug,
                    'customer_id'     => null,
                    'scope'           => PriceRule::SCOPE_GLOBAL,
                    'object_id'       => 0,
                    'type'            => PriceRule::TYPE_PERCENT,
                    'value'           => $discount,
                    'min_qty'         => 1,
                ];
            }

            if ($taxExemptAll) {
                $tax_exempt_groups[] = $slug;
            }
        }

        if (empty($groups)) {
            $warnings[] = __('No wholesale roles were found to import.', 'softminal-b2b-wholesale-for-woocommerce');
        }

        // Hide prices from non-wholesale visitors → our hide-prices-for-guests.
        $visibility = [];
        if ($this->truthy(get_option('wwp_hide_price_add_to_cart', ''))) {
            $visibility['hide_prices_guests'] = true;
        }

        return compact('groups', 'users', 'rules', 'tax_exempt_groups', 'visibility', 'warnings');
    }

    /**
     * WooCommerce checkbox settings store 'yes' / '1' / true when on.
     *
     * @param mixed $value
     */
    private function truthy($value): bool
    {
        return in_array($value, ['yes', '1', 1, true], true);
    }
}
