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

/**
 * VMO Brevo Direct API Client
 * 
 * Handles direct communication between the User's WP Install and Brevo API.
 * ensures VMO server is bypassed completely (Zero Cost Architecture).
 * 
 * @package VMO_AI_Builder_Manager
 */

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

class VMO_Brevo_Direct {
    
    private $api_key;
    private $api_url = 'https://api.brevo.com/v3';
    
    public function __construct() {
        // User must provide their own key
        $this->api_key = get_option('vmo_brevo_api_key');
    }
    
    /**
     * Check if properly configured
     */
    public function is_configured() {
        return !empty($this->api_key);
    }
    
    /**
     * Send email via Brevo API
     * 
     * @param array $data Email data payload
     * @return array Response from Brevo
     */
    public function send_email($data) {
        if (!$this->is_configured()) {
            return ['success' => false, 'message' => 'Brevo API Key not configured'];
        }

        // Map VMO standard fields to Brevo format
        $payload = [
            'sender' => [
                'name' => isset($data['from_name']) ? $data['from_name'] : get_bloginfo('name'),
                'email' => isset($data['from_email']) ? $data['from_email'] : get_option('admin_email')
            ],
            'to' => [
                [
                    'email' => $data['to_email'],
                    'name' => isset($data['to_name']) ? $data['to_name'] : ''
                ]
            ],
            'subject' => $data['subject'],
            'htmlContent' => $data['html_body']
        ];
        
        // Optional: Plain text fallback
        if (!empty($data['plain_body'])) {
            $payload['textContent'] = $data['plain_body'];
        }
        
        // Optional: Reply-To
        if (!empty($data['reply_to'])) {
            $payload['replyTo'] = ['email' => $data['reply_to']];
        }

        return $this->make_request('smtp/email', 'POST', $payload);
    }
    
    /**
     * Get User Account Info (Credits, Plan)
     * Useful for dashboard display
     */
    public function get_account() {
        return $this->make_request('account', 'GET');
    }

    /**
     * Make the HTTP request directly from User Server -> Brevo
     */
    private function make_request($endpoint, $method = 'GET', $body = null) {
        $url = $this->api_url . '/' . $endpoint;
        
        $args = [
            'method' => $method,
            'timeout' => 30,
            'headers' => [
                'api-key' => $this->api_key,
                'Content-Type' => 'application/json',
                'Accept' => 'application/json'
            ]
        ];
        
        if ($body && $method !== 'GET') {
            $args['body'] = json_encode($body);
        }
        
        $response = wp_remote_request($url, $args);
        
        if (is_wp_error($response)) {
            return ['success' => false, 'message' => $response->get_error_message()];
        }
        
        $code = wp_remote_retrieve_response_code($response);
        $response_body = json_decode(wp_remote_retrieve_body($response), true);
        
        if ($code >= 200 && $code < 300) {
            return ['success' => true, 'data' => $response_body];
        } else {
            return [
                'success' => false, 
                'code' => $code, 
                'message' => isset($response_body['message']) ? $response_body['message'] : 'Unknown error'
            ];
        }
    }
}
