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

class BMTQB_Integration_Manager {
    private $adapters = [];

    public function register(BMTQB_Integration_Adapter_Interface $adapter) {
        $this->adapters[$adapter->key()] = $adapter;
    }

    public function adapters(BMTQB_Industry_Interface $industry = null) {
        $adapters = $this->adapters;
        $adapters = apply_filters('bmtqb_integration_adapters', $adapters, $industry);

        if ($industry === null) {
            return $adapters;
        }

        return array_filter($adapters, function ($adapter) use ($industry) {
            return $adapter instanceof BMTQB_Integration_Adapter_Interface && $adapter->supports($industry);
        });
    }

    public function dispatch(BMTQB_Integration_Context $context) {
        $summary = [];

        foreach ($this->adapters($context->industry) as $adapter) {
            $key = $adapter->key();
            $label = $adapter->label();

            if (!$adapter->is_configured($context->industry)) {
                $summary[$key] = [
                    'label' => $label,
                    'status' => 'skipped',
                    'message' => 'Integration is not configured.',
                ];
                continue;
            }

            $result = $adapter->send($context);
            if (is_wp_error($result)) {
                $summary[$key] = [
                    'label' => $label,
                    'status' => 'error',
                    'message' => $result->get_error_message(),
                ];
                continue;
            }

            $summary[$key] = array_merge([
                'label' => $label,
                'status' => 'sent',
            ], is_array($result) ? $result : ['message' => 'Sent.']);
        }

        update_post_meta($context->post_id, '_' . $context->industry->meta_prefix() . '_integrations_summary', $summary);

        return $summary;
    }

    public function admin_sections(BMTQB_Industry_Interface $industry, $post_id) {
        $sections = [];

        foreach ($this->adapters($industry) as $adapter) {
            $rows = $adapter->admin_rows($industry, $post_id);
            if (empty($rows) || !is_array($rows)) {
                continue;
            }

            $sections[] = [
                'label' => $adapter->label(),
                'rows' => $rows,
            ];
        }

        return $sections;
    }
}
