<?php

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

class AIEO_Newsletter_Adapter_Mailchimp extends AIEO_Newsletter_Adapter_Base {

    public function get_id(): string    { return 'mailchimp'; }
    public function get_label(): string { return 'Mailchimp'; }

    public function get_settings_fields(): array {
        return array(
            array(
                'key'         => 'api_key',
                'label'       => __('API key', 'ai-eshop-optimizer'),
                'type'        => 'password',
                'required'    => true,
                'description' => __('Generate one at Account → Extras → API keys. Format includes a datacenter suffix like -us21.', 'ai-eshop-optimizer'),
            ),
            array(
                'key'         => 'list_id',
                'label'       => __('Audience (list) ID', 'ai-eshop-optimizer'),
                'type'        => 'text',
                'required'    => true,
                'description' => __('Find it in Audience → Settings → Audience name and defaults. 10-character alphanumeric.', 'ai-eshop-optimizer'),
            ),
        );
    }

    public function test_connection(): array {
        $base = $this->base_url();
        if ($base === '') {
            return array('ok' => false, 'error' => 'Invalid API key (missing -dc suffix).', 'details' => array());
        }
        $resp = wp_remote_get($base . '/3.0/', array(
            'timeout' => 10,
            'headers' => $this->auth_headers(),
        ));
        if (is_wp_error($resp)) {
            return array('ok' => false, 'error' => $resp->get_error_message(), 'details' => array());
        }
        $code = (int) wp_remote_retrieve_response_code($resp);
        $body = json_decode((string) wp_remote_retrieve_body($resp), true);
        if ($code === 200 && is_array($body)) {
            return array('ok' => true, 'error' => '', 'details' => array(
                'account_name' => (string) ($body['account_name'] ?? ''),
                'datacenter'   => $this->datacenter(),
            ));
        }
        return array(
            'ok'      => false,
            'error'   => 'HTTP ' . $code . ' — ' . (string) ($body['detail'] ?? wp_remote_retrieve_response_message($resp)),
            'details' => is_array($body) ? $body : array(),
        );
    }

    public function sync_contacts(array $contacts, string $cohort): array {
        $base = $this->base_url();
        $list_id = (string) ($this->settings['list_id'] ?? '');
        if ($base === '' || $list_id === '') {
            return array('ok' => false, 'synced' => 0, 'failed' => count($contacts), 'error' => 'missing-config', 'provider_segment_id' => '');
        }

        $tag_cohort  = self::cohort_tag($cohort);
        $tag_generic = self::generic_tag();
        $synced = 0;
        $failed = 0;
        $first_error = '';

        foreach ($contacts as $c) {
            $email = (string) ($c['email'] ?? '');
            if ($email === '') { $failed++; continue; }

            $hash = self::md5_email($email);

            
            
            
            $url = $base . '/3.0/lists/' . rawurlencode($list_id) . '/members/' . $hash;
            $body = array(
                'email_address' => $email,
                'status_if_new' => 'transactional',
                'merge_fields'  => array(
                    'AIEOLTV'   => round((float) ($c['ltv'] ?? 0), 2),
                    'AIEOORD'   => (int) ($c['orders_count'] ?? 0),
                    'AIEORCY'   => (int) ($c['recency_days'] ?? 0),
                    'AIEOBRAND' => (string) ($c['top_brand'] ?? ''),
                    'AIEOSCORE' => (int) ($c['reactivation_score'] ?? 0),
                ),
            );
            $resp = wp_remote_request($url, array(
                'method'  => 'PUT',
                'timeout' => 10,
                'headers' => array_merge($this->auth_headers(), array('Content-Type' => 'application/json')),
                'body'    => wp_json_encode($body),
            ));
            if (is_wp_error($resp)) {
                $failed++;
                if ($first_error === '') { $first_error = $resp->get_error_message(); }
                continue;
            }
            $code = (int) wp_remote_retrieve_response_code($resp);
            if ($code < 200 || $code >= 300) {
                $failed++;
                if ($first_error === '') {
                    $rb = json_decode((string) wp_remote_retrieve_body($resp), true);
                    $first_error = 'HTTP ' . $code . ' ' . (string) ($rb['detail'] ?? '');
                }
                continue;
            }

            
            $tag_url = $base . '/3.0/lists/' . rawurlencode($list_id) . '/members/' . $hash . '/tags';
            wp_remote_post($tag_url, array(
                'timeout' => 10,
                'headers' => array_merge($this->auth_headers(), array('Content-Type' => 'application/json')),
                'body'    => wp_json_encode(array(
                    'tags' => array(
                        array('name' => $tag_cohort,  'status' => 'active'),
                        array('name' => $tag_generic, 'status' => 'active'),
                    ),
                )),
            ));

            $synced++;
        }

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

    
    private function datacenter(): string {
        $key = (string) ($this->settings['api_key'] ?? '');
        $pos = strrpos($key, '-');
        return $pos === false ? '' : substr($key, $pos + 1);
    }

    private function base_url(): string {
        $dc = $this->datacenter();
        if ($dc === '') { return ''; }
        return 'https://' . $dc . '.api.mailchimp.com';
    }

    private function auth_headers(): array {
        return array(
            
            'Authorization' => 'Basic ' . base64_encode('aieo:' . (string) $this->settings['api_key']),
        );
    }
}
