<?php

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

class AIEO_Newsletter_Adapter_Webhook extends AIEO_Newsletter_Adapter_Base {

    public function get_id(): string    { return 'webhook'; }
    public function get_label(): string { return 'Webhook (MailPoet / Brevo / custom / iPaaS)'; }

    public function get_settings_fields(): array {
        return array(
            array(
                'key'         => 'webhook_url',
                'label'       => __('Endpoint URL', 'ai-eshop-optimizer'),
                'type'        => 'text',
                'required'    => true,
                'description' => __('Full https:// URL we POST the cohort payload to (e.g. /wp-json/your-newsletter/v1/contacts).', 'ai-eshop-optimizer'),
            ),
            array(
                'key'         => 'auth_type',
                'label'       => __('Auth method', 'ai-eshop-optimizer'),
                'type'        => 'text',
                'required'    => false,
                'description' => __('One of: none | basic | bearer | hmac. Default: none. "basic" uses Client key + Client secret (most plugin REST APIs); "bearer" uses Client secret as a Bearer token; "hmac" sends X-AIEO-Signature header.', 'ai-eshop-optimizer'),
            ),
            array(
                'key'         => 'client_key',
                'label'       => __('Client key / API username', 'ai-eshop-optimizer'),
                'type'        => 'text',
                'required'    => false,
                'description' => __('For "basic" auth: the username half. Plugin REST APIs typically issue this as a 40-character hex Client key.', 'ai-eshop-optimizer'),
            ),
            array(
                'key'         => 'client_secret',
                'label'       => __('Client secret / token', 'ai-eshop-optimizer'),
                'type'        => 'password',
                'required'    => false,
                'description' => __('For "basic": password half. For "bearer" / "hmac": the token / shared secret.', 'ai-eshop-optimizer'),
            ),
            array(
                'key'         => 'batch_size',
                'label'       => __('Batch size', 'ai-eshop-optimizer'),
                'type'        => 'text',
                'required'    => false,
                'description' => __('Contacts per POST. Lower this if your endpoint has size limits. Default 500.', 'ai-eshop-optimizer'),
            ),
        );
    }

    public function test_connection(): array {
        $url = (string) ($this->settings['webhook_url'] ?? '');
        if ($url === '' || !preg_match('#^https?://#i', $url)) {
            return array('ok' => false, 'error' => 'Invalid webhook URL.', 'details' => array());
        }
        $payload = array(
            'cohort'    => 'test',
            'tags'      => array('aieo:test'),
            'synced_at' => gmdate('c'),
            'contacts'  => array(),
            'test'      => true,
        );
        $resp = $this->post_payload($payload);
        if (is_wp_error($resp)) {
            return array('ok' => false, 'error' => $resp->get_error_message(), 'details' => array());
        }
        $code = (int) wp_remote_retrieve_response_code($resp);
        if ($code >= 200 && $code < 300) {
            return array('ok' => true, 'error' => '', 'details' => array('http_status' => $code));
        }
        return array(
            'ok'      => false,
            'error'   => 'HTTP ' . $code . ' — ' . wp_remote_retrieve_response_message($resp),
            'details' => array('http_status' => $code, 'body' => substr((string) wp_remote_retrieve_body($resp), 0, 500)),
        );
    }

    public function sync_contacts(array $contacts, string $cohort): array {
        $url = (string) ($this->settings['webhook_url'] ?? '');
        if ($url === '') {
            return array('ok' => false, 'synced' => 0, 'failed' => count($contacts), 'error' => 'missing-url', 'provider_segment_id' => '');
        }
        $batch_size = max(1, min(5000, (int) ($this->settings['batch_size'] ?? 500)));
        $tag_cohort  = self::cohort_tag($cohort);
        $tag_generic = self::generic_tag();

        $synced = 0;
        $failed = 0;
        $first_error = '';

        foreach (array_chunk($contacts, $batch_size) as $batch) {
            $payload = array(
                'cohort'    => $cohort,
                'tags'      => array($tag_cohort, $tag_generic),
                'synced_at' => gmdate('c'),
                'contacts'  => $batch,
            );
            $resp = $this->post_payload($payload);
            if (is_wp_error($resp)) {
                $failed += count($batch);
                if ($first_error === '') { $first_error = $resp->get_error_message(); }
                continue;
            }
            $code = (int) wp_remote_retrieve_response_code($resp);
            if ($code < 200 || $code >= 300) {
                $failed += count($batch);
                if ($first_error === '') { $first_error = 'HTTP ' . $code; }
                continue;
            }
            $synced += count($batch);
        }

        return array(
            'ok'                  => $synced > 0,
            'synced'              => $synced,
            'failed'              => $failed,
            'error'               => $first_error,
            'provider_segment_id' => $tag_cohort,
        );
    }

    private function post_payload(array $payload) {
        $url    = (string) $this->settings['webhook_url'];
        $secret = (string) ($this->settings['shared_secret'] ?? '');
        $body   = (string) wp_json_encode($payload);
        $headers = array(
            'Content-Type' => 'application/json',
            'User-Agent'   => 'AIEO-WebPush/' . (defined('AIEO_VERSION') ? AIEO_VERSION : '1.0'),
        );
        if ($secret !== '') {
            $headers['X-AIEO-Signature'] = 'sha256=' . hash_hmac('sha256', $body, $secret);
        }
        return wp_remote_post($url, array(
            'timeout' => 15,
            'headers' => $headers,
            'body'    => $body,
        ));
    }
}
