<?php
namespace WooNooW\Compat;

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

class SettingsProvider {
    public static function init() {
        // later: cache if needed
    }

    public static function get_tabs(): array {
        $pages = apply_filters('woocommerce_get_settings_pages', []);
        $out = [];
        foreach ($pages as $page) {
            if (!is_object($page) || !isset($page->id)) continue;
            $label = method_exists($page, 'get_label') ? $page->get_label() : ($page->label ?? ucfirst($page->id));
            $sections = method_exists($page, 'get_sections') ? $page->get_sections() : ['' => $label];
            $out[] = ['id' => $page->id, 'label' => $label, 'sections' => $sections];
        }
        return $out;
    }

    public static function get_tab_schema(string $tab, string $section = ''): array {
        $pages = apply_filters('woocommerce_get_settings_pages', []);
        foreach ($pages as $page) {
            if (!is_object($page) || !isset($page->id)) continue;
            if ($page->id !== $tab) continue;
            $settings = $page->get_settings($section);
            return [
                'tab'      => $tab,
                'section'  => $section,
                'fields'   => self::normalize_fields($settings),
            ];
        }
        return ['tab' => $tab, 'section' => $section, 'fields' => []];
    }

    private static function normalize_fields(array $settings): array {
        $out = [];
        foreach ($settings as $field) {
            $type = $field['type'] ?? 'text';
            $id   = $field['id']   ?? '';
            $title= $field['title']?? '';
            if (in_array($type, ['title','sectionend'], true)) {
                $out[] = ['type' => $type, 'id' => $id, 'label' => $title];
                continue;
            }
            $value = \WC_Admin_Settings::get_option($id, $field['default'] ?? '');
            $out[] = [
                'type'    => $type,
                'id'      => $id,
                'label'   => $title,
                'desc'    => $field['desc'] ?? ($field['description'] ?? ''),
                'options' => $field['options'] ?? null,
                'default' => $field['default'] ?? null,
                'value'   => $value,
                'attrs'   => $field['custom_attributes'] ?? null,
            ];
        }
        return $out;
    }

    public static function save_tab(string $tab, string $section = '', array $payload = []): array {
        $pages = apply_filters('woocommerce_get_settings_pages', []);
        foreach ($pages as $page) {
            if (!is_object($page) || !isset($page->id)) continue;
            if ($page->id !== $tab) continue;

            $settings = $page->get_settings($section);
            // Rebuild $_POST for Woo's saver
            foreach ($settings as $field) {
                if (empty($field['id']) || empty($field['type'])) continue;
                $id = $field['id'];
                if ($field['type'] === 'checkbox') {
                    $_POST[$id] = !empty($payload[$id]) ? 'yes' : 'no';
                } else {
                    $_POST[$id] = isset($payload[$id]) ? $payload[$id] : null;
                }
            }
            \WC_Admin_Settings::save_fields($settings);
            return ['ok' => true];
        }
        return ['ok' => false, 'error' => 'Tab not found'];
    }
}