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

/**
 * Vibe.co CTV / Streaming TV Advertising Connector
 *
 * Vibe.co is a self-serve Connected TV (CTV) advertising DSP that provides
 * programmatic access to streaming apps, TV channels, live sports, and live
 * shows. Minimum spend $50/day, CPM $15–$35, credit-card payment.
 *
 * This connector manages ad campaigns on Vibe.co through their API. It is NOT
 * a social-media publisher — it specialises in video ad placement across CTV
 * and streaming inventory.
 *
 * Integration scope:
 *  - connect_account   → OAuth / API key exchange with Vibe.co
 *  - list_ad_accounts  → Retrieve advertiser accounts
 *  - create_ad_draft   → Build campaign draft (targeting, budget, creative)
 *  - launch_ad_campaign→ Submit campaign for delivery
 *  - fetch_ad_metrics  → Pull delivery, impression, and conversion data
 *  - fetch_metrics     → Alias for fetch_ad_metrics (unified reporting)
 */
class VMO_Promotion_Vibe_Connector extends VMO_Promotion_Base_Connector {

    const API_BASE = 'https://api.vibe.co/v1';

    public function __construct() {
        parent::__construct('vibe_co', 'Vibe.co', array(
            'connect_supported'            => true,
            'publish_text'                 => false,
            'publish_image'                => false,
            'publish_video'                => true,
            'publish_carousel'             => false,
            'reply_read'                   => false,
            'reply_write'                  => false,
            'metrics_read'                 => true,
            'webhooks'                     => false,
            'ad_management'                => true,
            'app_review_required'          => false,
            'domain_verification_required' => false,
        ));
    }

    /* ------------------------------------------------------------------ */
    /*  Account Connection                                                 */
    /* ------------------------------------------------------------------ */

    public function connect_account(array $input) {
        $api_key = isset($input['api_key']) ? sanitize_text_field($input['api_key']) : '';
        if ($api_key === '') {
            return new WP_Error('vibe_missing_key', 'A Vibe.co API key is required to connect.');
        }

        $response = $this->api_get('/me', $api_key);
        if (is_wp_error($response)) {
            return $response;
        }

        return array(
            'connected'    => true,
            'platform_key' => $this->platform_key,
            'account_id'   => isset($response['id']) ? $response['id'] : '',
            'account_name' => isset($response['name']) ? $response['name'] : '',
            'email'        => isset($response['email']) ? $response['email'] : '',
        );
    }

    public function handle_callback(array $request) {
        return $this->unsupported('handle_callback');
    }

    public function refresh_auth(array $input) {
        return $this->connect_account($input);
    }

    public function validate_scopes(array $input) {
        return array(
            'valid'          => true,
            'platform_key'   => $this->platform_key,
            'missing_scopes' => array(),
            'granted_scopes' => array('campaigns:read', 'campaigns:write', 'reports:read'),
        );
    }

    public function list_accounts(array $input) {
        $api_key = $this->extract_api_key($input);
        if (is_wp_error($api_key)) {
            return $api_key;
        }

        $response = $this->api_get('/advertisers', $api_key);
        if (is_wp_error($response)) {
            return $response;
        }

        $accounts = array();
        $items = isset($response['data']) ? $response['data'] : (is_array($response) ? $response : array());
        foreach ($items as $item) {
            $accounts[] = array(
                'id'   => isset($item['id']) ? $item['id'] : '',
                'name' => isset($item['name']) ? $item['name'] : '',
            );
        }

        return array(
            'accounts'     => $accounts,
            'platform_key' => $this->platform_key,
        );
    }

    /* ------------------------------------------------------------------ */
    /*  Ad Campaign Management                                             */
    /* ------------------------------------------------------------------ */

    public function list_ad_accounts(array $input) {
        return $this->list_accounts($input);
    }

    public function create_ad_draft(array $input) {
        $api_key = $this->extract_api_key($input);
        if (is_wp_error($api_key)) {
            return $api_key;
        }

        $payload = array(
            'name'       => isset($input['campaign_name']) ? sanitize_text_field($input['campaign_name']) : 'VMO Campaign',
            'budget'     => isset($input['budget']) ? (float) $input['budget'] : 50.0,
            'start_date' => isset($input['start_date']) ? sanitize_text_field($input['start_date']) : '',
            'end_date'   => isset($input['end_date']) ? sanitize_text_field($input['end_date']) : '',
            'targeting'  => isset($input['targeting']) ? $input['targeting'] : array(),
            'creative'   => isset($input['creative']) ? $input['creative'] : array(),
            'status'     => 'draft',
        );

        $response = $this->api_post('/campaigns', $payload, $api_key);
        if (is_wp_error($response)) {
            return $response;
        }

        return array(
            'success'       => true,
            'platform_key'  => $this->platform_key,
            'campaign_id'   => isset($response['id']) ? $response['id'] : '',
            'campaign_name' => $payload['name'],
            'status'        => 'draft',
        );
    }

    public function launch_ad_campaign(array $input) {
        $api_key = $this->extract_api_key($input);
        if (is_wp_error($api_key)) {
            return $api_key;
        }

        $campaign_id = isset($input['campaign_id']) ? sanitize_text_field($input['campaign_id']) : '';
        if ($campaign_id === '') {
            return new WP_Error('vibe_missing_campaign', 'Campaign ID is required to launch.');
        }

        $response = $this->api_post('/campaigns/' . $campaign_id . '/launch', array(), $api_key);
        if (is_wp_error($response)) {
            return $response;
        }

        return array(
            'success'      => true,
            'platform_key' => $this->platform_key,
            'campaign_id'  => $campaign_id,
            'status'       => isset($response['status']) ? $response['status'] : 'active',
        );
    }

    public function fetch_ad_metrics(array $input) {
        $api_key = $this->extract_api_key($input);
        if (is_wp_error($api_key)) {
            return $api_key;
        }

        $campaign_id = isset($input['campaign_id']) ? sanitize_text_field($input['campaign_id']) : '';
        $endpoint    = ($campaign_id !== '') ? '/campaigns/' . $campaign_id . '/metrics' : '/metrics';

        $response = $this->api_get($endpoint, $api_key);
        if (is_wp_error($response)) {
            return $response;
        }

        return array(
            'success'      => true,
            'platform_key' => $this->platform_key,
            'campaign_id'  => $campaign_id,
            'impressions'  => isset($response['impressions']) ? (int) $response['impressions'] : 0,
            'views'        => isset($response['views']) ? (int) $response['views'] : 0,
            'clicks'       => isset($response['clicks']) ? (int) $response['clicks'] : 0,
            'spend'        => isset($response['spend']) ? (float) $response['spend'] : 0.0,
            'cpm'          => isset($response['cpm']) ? (float) $response['cpm'] : 0.0,
            'households'   => isset($response['unique_households']) ? (int) $response['unique_households'] : 0,
        );
    }

    public function fetch_metrics(array $input) {
        return $this->fetch_ad_metrics($input);
    }

    /* ------------------------------------------------------------------ */
    /*  Video Creative Upload (publish_video maps to creative upload)      */
    /* ------------------------------------------------------------------ */

    public function publish_media_post(array $input) {
        return $this->publish_video_creative($input);
    }

    private function publish_video_creative(array $input) {
        $api_key = $this->extract_api_key($input);
        if (is_wp_error($api_key)) {
            return $api_key;
        }

        $video_url = isset($input['video_url']) ? esc_url_raw($input['video_url']) : '';
        if ($video_url === '') {
            return new WP_Error('vibe_missing_video', 'A video URL is required for the creative.');
        }

        $payload = array(
            'name'      => isset($input['title']) ? sanitize_text_field($input['title']) : 'VMO Creative',
            'video_url' => $video_url,
            'duration'  => isset($input['duration']) ? (int) $input['duration'] : 30,
        );

        $response = $this->api_post('/creatives', $payload, $api_key);
        if (is_wp_error($response)) {
            return $response;
        }

        return array(
            'success'      => true,
            'platform_key' => $this->platform_key,
            'creative_id'  => isset($response['id']) ? $response['id'] : '',
            'status'       => isset($response['status']) ? $response['status'] : 'processing',
        );
    }

    /* ------------------------------------------------------------------ */
    /*  Internal HTTP helpers                                              */
    /* ------------------------------------------------------------------ */

    private function extract_api_key(array $input) {
        $api_key = isset($input['api_key']) ? sanitize_text_field($input['api_key']) : '';
        if ($api_key === '') {
            $api_key = isset($input['credentials']['api_key']) ? sanitize_text_field($input['credentials']['api_key']) : '';
        }
        if ($api_key === '') {
            return new WP_Error('vibe_missing_key', 'Vibe.co API key is required.');
        }
        return $api_key;
    }

    private function api_get($endpoint, $api_key) {
        $url = self::API_BASE . $endpoint;
        $response = wp_remote_get($url, array(
            'timeout' => 30,
            'headers' => array(
                'Authorization' => 'Bearer ' . $api_key,
                'Accept'        => 'application/json',
            ),
        ));

        return $this->parse_response($response);
    }

    private function api_post($endpoint, array $body, $api_key) {
        $url = self::API_BASE . $endpoint;
        $response = wp_remote_post($url, array(
            'timeout' => 30,
            'headers' => array(
                'Authorization' => 'Bearer ' . $api_key,
                'Content-Type'  => 'application/json',
                'Accept'        => 'application/json',
            ),
            'body' => wp_json_encode($body),
        ));

        return $this->parse_response($response);
    }

    private function parse_response($response) {
        if (is_wp_error($response)) {
            return new WP_Error('vibe_http_error', 'Vibe.co API request failed: ' . $response->get_error_message());
        }

        $code = wp_remote_retrieve_response_code($response);
        $body = wp_remote_retrieve_body($response);
        $data = json_decode($body, true);

        if ($code >= 400) {
            $message = (is_array($data) && isset($data['message'])) ? $data['message'] : 'HTTP ' . $code;
            return new WP_Error('vibe_api_error', 'Vibe.co API error: ' . $message, array('status' => $code));
        }

        return is_array($data) ? $data : array();
    }
}
