<?php
if (!defined('ABSPATH')) {
    exit;
}

class BMTQB_Settings_Repository {
    public static function defaults(BMTQB_Industry_Interface $industry) {
        $defaults = $industry->settings_defaults();
        return is_array($defaults) ? $defaults : [];
    }

    public static function all(BMTQB_Industry_Interface $industry) {
        $options = get_option($industry->option_name(), []);
        if (!is_array($options)) {
            $options = [];
        }

        return array_merge(self::defaults($industry), $options);
    }

    public static function get(BMTQB_Industry_Interface $industry, $key, $default = null) {
        $settings = self::all($industry);
        return array_key_exists($key, $settings) ? $settings[$key] : $default;
    }

    public static function email_settings(BMTQB_Industry_Interface $industry) {
        $settings = self::all($industry);

        return [
            'company_email' => sanitize_email($settings['company_email'] ?? ''),
            'from_name' => sanitize_text_field($settings['from_name'] ?? ''),
            'from_email' => sanitize_email($settings['from_email'] ?? ''),
        ];
    }

    public static function pdf_settings(BMTQB_Industry_Interface $industry) {
        $settings = self::all($industry);

        return [
            'logo_url' => esc_url_raw($settings['logo_url'] ?? ''),
            'header_title' => (string) ($settings['pdf_header_title'] ?? ''),
            'header_subtitle' => (string) ($settings['pdf_header_subtitle'] ?? ''),
            'footer_note' => (string) ($settings['pdf_footer_note'] ?? ''),
        ];
    }

    public static function integration_settings(BMTQB_Industry_Interface $industry, $integration_key) {
        $settings = self::all($industry);
        $prefix = sanitize_key($integration_key) . '_';

        $values = [];
        foreach ($settings as $key => $value) {
            if (strpos($key, $prefix) === 0) {
                $values[substr($key, strlen($prefix))] = $value;
            }
        }

        return $values;
    }
}
