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

require_once VMO_AI_BUILDER_DIR . 'includes/modules/core/class-vmo-service.php';

class VMO_Twilio_Service extends VMO_Service {
    private $sid;
    private $token;

    public function __construct() {
        parent::__construct('twilio');
        // Only load credentials in master mode
        if (!defined('VMO_CLIENT_MODE') || VMO_CLIENT_MODE !== true) {
            $this->sid = get_option('vmo_twilio_account_sid');
            $this->token = get_option('vmo_twilio_auth_token');
        }
    }

    public function make_call($to, $from, $twiml_url) {
        if (!$this->is_available()) {
            return false;
        }

        // Use centralized API request helper if available
        if (function_exists('vmo_api_request')) {
            // In client mode, route through proxy
            $body = http_build_query([
                'To' => $to,
                'From' => $from,
                'Url' => $twiml_url,
            ]);
            
            $args = [
                'headers' => ['Content-Type' => 'application/x-www-form-urlencoded'],
                'body' => $body,
                'timeout' => 30,
            ];
            
            // The endpoint needs the account SID - in client mode, master will handle this
            $endpoint = defined('VMO_CLIENT_MODE') && VMO_CLIENT_MODE 
                ? 'Calls.json'  // Master will construct full path
                : "2010-04-01/Accounts/{$this->sid}/Calls.json";
            
            $response = vmo_api_request('twilio', $endpoint, $args, 'POST');
            
            if (is_wp_error($response)) {
                $this->record_failure($response->get_error_message());
                return false;
            }
            
            $code = wp_remote_retrieve_response_code($response);
            if ($code >= 400) {
                $this->record_failure("Twilio Error: $code");
                return false;
            }
            
            $this->reset_circuit();
            return true;
        }

        // Fallback: Direct API call (master mode only)
        if (empty($this->sid) || empty($this->token)) {
            return false;
        }

        $url = "https://api.twilio.com/2010-04-01/Accounts/{$this->sid}/Calls.json";
        $args = [
            'headers' => [
                'Authorization' => 'Basic ' . base64_encode("{$this->sid}:{$this->token}"), // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode -- HTTP Basic auth header
            ],
            'body' => [
                'To' => $to,
                'From' => $from,
                'Url' => $twiml_url,
            ],
        ];

        $response = wp_remote_post($url, $args);

        if (is_wp_error($response)) {
            $this->record_failure($response->get_error_message());
            return false;
        }

        $code = wp_remote_retrieve_response_code($response);
        if ($code >= 400) {
            $this->record_failure("Twilio Error: $code");
            return false;
        }

        $this->reset_circuit();
        return true;
    }

    protected function get_fallback() {
        // For voice, fallback might be logging or sending an email instead
        error_log("Twilio Service Unavailable. Fallback action triggered.");
        return false;
    }
}
