<?php

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

class AIEO_Newsletter_Adapter_Klaviyo extends AIEO_Newsletter_Adapter_Base {

    const API_REVISION = '2024-10-15';

    public function get_id(): string    { return 'klaviyo'; }
    public function get_label(): string { return 'Klaviyo'; }

    public function get_settings_fields(): array {
        return array(
            array(
                'key'         => 'api_key',
                'label'       => __('Private API key', 'ai-eshop-optimizer'),
                'type'        => 'password',
                'required'    => true,
                'description' => __('Generate at Account → Settings → API keys. Starts with pk_.', 'ai-eshop-optimizer'),
            ),
            array(
                'key'         => 'list_id',
                'label'       => __('List ID', 'ai-eshop-optimizer'),
                'type'        => 'text',
                'required'    => true,
                'description' => __('From Lists & Segments → Settings → List ID. 6-character alphanumeric.', 'ai-eshop-optimizer'),
            ),
        );
    }

    public function test_connection(): array {
        $resp = wp_remote_get('https://a.klaviyo.com/api/accounts/', 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 && $code < 300 && is_array($body)) {
            $name = '';
            if (isset($body['data'][0]['attributes']['contact_information']['organization_name'])) {
                $name = (string) $body['data'][0]['attributes']['contact_information']['organization_name'];
            }
            return array('ok' => true, 'error' => '', 'details' => array('account_name' => $name));
        }
        $err = '';
        if (is_array($body) && isset($body['errors'][0]['detail'])) {
            $err = (string) $body['errors'][0]['detail'];
        }
        return array(
            'ok'      => false,
            'error'   => 'HTTP ' . $code . ' — ' . ($err ?: wp_remote_retrieve_response_message($resp)),
            'details' => is_array($body) ? $body : array(),
        );
    }

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

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

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

            $body = array(
                'data' => array(
                    'type' => 'profile',
                    'attributes' => array(
                        'email'      => $email,
                        'properties' => array(
                            'aieo_ltv'                => round((float) ($c['ltv'] ?? 0), 2),
                            'aieo_orders'             => (int) ($c['orders_count'] ?? 0),
                            'aieo_recency_days'       => (int) ($c['recency_days'] ?? 0),
                            'aieo_top_brand'          => (string) ($c['top_brand'] ?? ''),
                            'aieo_reactivation_score' => (int) ($c['reactivation_score'] ?? 0),
                            'aieo_cohort'             => $cohort,
                            'aieo_tags'               => array($tag_cohort, $tag_generic),
                        ),
                    ),
                ),
            );

            $resp = wp_remote_post('https://a.klaviyo.com/api/profile-import/', array(
                'timeout' => 10,
                'headers' => array_merge($this->auth_headers(), array(
                    'Content-Type' => 'application/json',
                    'Accept'       => '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);
            $rb   = json_decode((string) wp_remote_retrieve_body($resp), true);
            if ($code < 200 || $code >= 300) {
                $failed++;
                if ($first_error === '' && is_array($rb) && isset($rb['errors'][0]['detail'])) {
                    $first_error = 'HTTP ' . $code . ' ' . (string) $rb['errors'][0]['detail'];
                }
                continue;
            }
            $synced++;
            $pid = is_array($rb) ? (string) ($rb['data']['id'] ?? '') : '';
            if ($pid !== '') { $profile_ids[] = $pid; }
        }

        
        if (!empty($profile_ids) && $list_id !== '') {
            $relations = array_map(static function ($id) {
                return array('type' => 'profile', 'id' => $id);
            }, $profile_ids);
            wp_remote_post(
                'https://a.klaviyo.com/api/lists/' . rawurlencode($list_id) . '/relationships/profiles/',
                array(
                    'timeout' => 10,
                    'headers' => array_merge($this->auth_headers(), array(
                        'Content-Type' => 'application/json',
                        'Accept'       => 'application/json',
                    )),
                    'body' => wp_json_encode(array('data' => $relations)),
                )
            );
        }

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

    private function auth_headers(): array {
        return array(
            'Authorization' => 'Klaviyo-API-Key ' . (string) ($this->settings['api_key'] ?? ''),
            'revision'      => self::API_REVISION,
        );
    }
}
