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

/**
 * VMO Twilio Manager (REST API - No SDK Required)
 * 
 * Handles autonomous provisioning of Twilio phone numbers
 * Uses WordPress HTTP API - works on ANY WordPress host
 * NO COMPOSER DEPENDENCIES
 * 
 * @package VMO_AI_Website_Builder
 * @since 1.0.0
 */

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

// VMO Twilio REST API Client (Embedded for robustness against path issues)
if (!class_exists('VMO_Twilio_REST')) {
    class VMO_Twilio_REST {
        private $sid;
        private $token;
        private $base;

        public function __construct( $sid = '', $token = '' ) {
            $this->sid   = $sid ?: get_option('vmo_twilio_sid');
            $this->token = $token ?: get_option('vmo_twilio_token');
            $this->base  = 'https://api.twilio.com/2010-04-01';
        }

        /**
         * Generate Authorization header for Twilio API
         */
        private function auth_header() {
            return 'Authorization: Basic ' . base64_encode($this->sid . ':' . $this->token); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode -- HTTP Basic auth header
        }

        /**
         * POST request to Twilio API
         */
        private function post($path, $body) {
            $url = trailingslashit($this->base) . ltrim($path, '/');
            $res = wp_remote_post($url, [
                'headers' => [
                    $this->auth_header(),
                    'Content-Type' => 'application/x-www-form-urlencoded'
                ],
                'body'    => $body,
                'timeout' => 30,
            ]);
            
            if ( is_wp_error($res) ) return $res;
            
            $code = wp_remote_retrieve_response_code($res);
            $json = json_decode(wp_remote_retrieve_body($res), true);
            
            return $code >= 200 && $code < 300 
                ? $json 
                : new WP_Error('twilio_rest_error', 'Twilio REST error', ['code'=>$code,'body'=>$json]);
        }

        /**
         * GET request to Twilio API
         */
        private function get($path, $query = []) {
            $url = trailingslashit($this->base) . ltrim($path, '/');
            if ($query) $url = add_query_arg($query, $url);
            
            $res = wp_remote_get($url, [
                'headers' => [ $this->auth_header() ],
                'timeout' => 30,
            ]);
            
            if ( is_wp_error($res) ) return $res;
            
            $code = wp_remote_retrieve_response_code($res);
            $json = json_decode(wp_remote_retrieve_body($res), true);
            
            return $code >= 200 && $code < 300 
                ? $json 
                : new WP_Error('twilio_rest_error', 'Twilio REST error', ['code'=>$code,'body'=>$json]);
        }

        /**
         * DELETE request to Twilio API
         */
        private function delete($path) {
            $url = trailingslashit($this->base) . ltrim($path, '/');
            
            $res = wp_remote_request($url, [
                'method'  => 'DELETE',
                'headers' => [ $this->auth_header() ],
                'timeout' => 30,
            ]);
            
            if ( is_wp_error($res) ) return $res;
            
            $code = wp_remote_retrieve_response_code($res);
            // 204 No Content is success for DELETE
            return $code >= 200 && $code < 300 
                ? true 
                : new WP_Error('twilio_rest_error', 'Twilio REST error', ['code'=>$code]);
        }

        /**
         * Create a subaccount for a user
         * 
         * @param string $friendlyName Descriptive name for the subaccount
         * @return array|WP_Error Subaccount data or error
         */
        public function create_subaccount($friendlyName) {
            return $this->post("Accounts.json", [
                'FriendlyName' => sanitize_text_field($friendlyName),
            ]);
        }

        /**
         * Provision a phone number
         * 
         * @param string $accountSid The account SID to provision for
         * @param string $areaCodeOrPattern Area code or pattern to search for
         * @param string $isoCountry ISO country code (default: US)
         * @param bool $smsEnabled Enable SMS (default: true)
         * @param bool $voiceEnabled Enable voice (default: true)
         * @return array|WP_Error Phone number data or error
         */
        public function provision_number($accountSid, $areaCodeOrPattern = '', $isoCountry = 'US', $smsEnabled=true, $voiceEnabled=true) {
            // Search available numbers
            $search = $this->get("Accounts/{$accountSid}/AvailablePhoneNumbers/{$isoCountry}/Local.json", [
                'Contains' => sanitize_text_field($areaCodeOrPattern),
                'SmsEnabled' => $smsEnabled ? 'true':'false',
                'VoiceEnabled' => $voiceEnabled ? 'true':'false',
            ]);
            
            if ( is_wp_error($search) ) return $search;
            
            if ( empty($search['available_phone_numbers'][0]['phone_number']) )
                return new WP_Error('no_numbers', 'No available numbers found');

            $phone = $search['available_phone_numbers'][0]['phone_number'];

            // Purchase number
            return $this->post("Accounts/{$accountSid}/IncomingPhoneNumbers.json", [
                'PhoneNumber' => $phone
            ]);
        }

        /**
         * Send SMS message
         * 
         * @param string $to Recipient phone number
         * @param string $from Sender phone number
         * @param string $body Message body
         * @return array|WP_Error Message data or error
         */
        public function send_sms($to, $from, $body) {
            return $this->post("Accounts/{$this->sid}/Messages.json", [
                'To' => sanitize_text_field($to),
                'From' => sanitize_text_field($from),
                'Body' => sanitize_textarea_field($body),
            ]);
        }

        /**
         * Make phone call
         * 
         * @param string $to Recipient phone number
         * @param string $from Caller phone number
         * @param string $url TwiML URL for call instructions
         * @return array|WP_Error Call data or error
         */
        public function make_call($to, $from, $url) {
            return $this->post("Accounts/{$this->sid}/Calls.json", [
                'To' => sanitize_text_field($to),
                'From' => sanitize_text_field($from),
                'Url' => esc_url_raw($url),
            ]);
        }

        /**
         * List phone numbers on account
         * 
         * @return array|WP_Error Phone numbers or error
         */
        public function list_numbers() {
            return $this->get("Accounts/{$this->sid}/IncomingPhoneNumbers.json");
        }

        /**
         * Release (Delete) a phone number
         * 
         * @param string $incomingPhoneNumberSid The SID of the phone number to release
         * @return bool|WP_Error True on success, error on failure
         */
        public function release_number($incomingPhoneNumberSid) {
            return $this->delete("Accounts/{$this->sid}/IncomingPhoneNumbers/{$incomingPhoneNumberSid}.json");
        }

        /**
         * Test connection to Twilio
         * 
         * @return array|WP_Error Account data or error
         */
        public function test_connection() {
            return $this->get("Accounts/{$this->sid}.json");
        }
    }
}

if (!class_exists('VMO_Twilio_Manager')) {
class VMO_Twilio_Manager {
    
    private $rest_client;
    
    public function __construct() {
        if (class_exists('VMO_Twilio_REST')) {
            $this->rest_client = new VMO_Twilio_REST();
        }
        add_action('rest_api_init', [$this, 'register_routes']);
        add_action('wp_ajax_vmo_twilio_test_connection', [$this, 'ajax_test_connection']);
    }

    /**
     * Register REST API routes
     */
    public function register_routes() {
        // Create subaccount
        register_rest_route('vmo/v1', '/twilio/subaccount', [
            'methods'  => 'POST',
            'permission_callback' => [$this, 'check_permissions'],
            'callback' => [$this, 'create_subaccount_route'],
            'args' => [
                'friendlyName' => [
                    'required' => true,
                    'type' => 'string',
                    'sanitize_callback' => 'sanitize_text_field',
                ]
            ]
        ]);

        // Provision phone number
        register_rest_route('vmo/v1', '/twilio/provision', [
            'methods'  => 'POST',
            'permission_callback' => [$this, 'check_permissions'],
            'callback' => [$this, 'provision_number_route'],
            'args' => [
                'accountSid' => ['required' => true, 'type' => 'string'],
                'pattern'    => ['required' => false, 'type' => 'string', 'default' => ''],
                'country'    => ['required' => false, 'type' => 'string', 'default' => 'US'],
            ]
        ]);

        // List phone numbers
        register_rest_route('vmo/v1', '/twilio/numbers', [
            'methods'  => 'GET',
            'permission_callback' => [$this, 'check_permissions'],
            'callback' => [$this, 'list_numbers_route'],
        ]);

        // Send SMS
        register_rest_route('vmo/v1', '/twilio/sms', [
            'methods'  => 'POST',
            'permission_callback' => [$this, 'check_permissions'],
            'callback' => [$this, 'send_sms_route'],
            'args' => [
                'to' => ['required' => true, 'type' => 'string'],
                'from' => ['required' => true, 'type' => 'string'],
                'body' => ['required' => true, 'type' => 'string'],
            ]
        ]);

        // Test connection
        register_rest_route('vmo/v1', '/twilio/test', [
            'methods'  => 'GET',
            'permission_callback' => [$this, 'check_permissions'],
            'callback' => [$this, 'test_connection_route'],
        ]);
    }

    /**
     * Permission check
     */
    public function check_permissions( $request ) {
        return current_user_can('manage_options') || is_user_logged_in();
    }

    /**
     * Create subaccount route
     */
    public function create_subaccount_route( WP_REST_Request $request ) {
        $friendly_name = $request->get_param('friendlyName');
        
        $result = $this->rest_client->create_subaccount($friendly_name);
        
        if ( is_wp_error($result) ) {
            return new WP_Error(
                $result->get_error_code(),
                $result->get_error_message(),
                ['status' => 500]
            );
        }
        
        // Save subaccount to user meta
        if (is_user_logged_in()) {
            update_user_meta(get_current_user_id(), 'vmo_twilio_subaccount_sid', $result['sid']);
        }
        
        return rest_ensure_response([
            'success' => true,
            'data' => $result
        ]);
    }

    /**
     * Provision phone number route
     */
    public function provision_number_route( WP_REST_Request $request ) {
        $user_id = get_current_user_id();
        
        // 1. LIMIT CHECK: Prevent number hoarding (One number per user)
        $existing = get_user_meta($user_id, 'vmo_twilio_phone_number', true);
        if ($existing && !current_user_can('manage_options')) {
            return new WP_Error(
                'limit_reached', 
                'You already have an active phone number (' . $existing . '). Please contact support to add additional lines.', 
                ['status' => 403]
            );
        }

        // 2. TOKEN CHARGE: Activation Fee (1875 Tokens ~= $2.50 cover setup + 1st month)
        if (function_exists('vmo_deduct_tokens') && !current_user_can('manage_options')) {
            $setup_cost = 1875;
            if (!vmo_deduct_tokens($user_id, $setup_cost, 'phone_activation', 'Phone Number Activation ($2.50 value)')) {
                return new WP_Error(
                    'insufficient_tokens', 
                    'Insufficient tokens for Phone Number Activation. Cost: 1875 Tokens ($2.50).', 
                    ['status' => 402]
                );
            }
        }

        $account_sid = sanitize_text_field($request->get_param('accountSid'));
        $pattern = sanitize_text_field($request->get_param('pattern') ?: '');
        $country = sanitize_text_field($request->get_param('country') ?: 'US');
        
        $result = $this->rest_client->provision_number($account_sid, $pattern, $country);
        
        if ( is_wp_error($result) ) {
            // Refund on failure
             if (function_exists('vmo_add_tokens') && !current_user_can('manage_options')) {
                 vmo_add_tokens($user_id, $setup_cost, 'phone_activation_refund', 'Refund for failed activation');
             }

            return new WP_Error(
                $result->get_error_code(),
                $result->get_error_message(),
                ['status' => 500]
            );
        }
        
        // Save phone number to user meta
        if (is_user_logged_in()) {
            // Core System Meta
            update_user_meta(get_current_user_id(), 'vmo_twilio_phone_number', $result['phone_number']);
            update_user_meta(get_current_user_id(), 'vmo_twilio_phone_sid', $result['sid']);
            // Set next rental date to 30 days from now
            update_user_meta(get_current_user_id(), 'vmo_phone_next_rent_due', strtotime('+30 days'));

            // Website & Dashboard Display Sync
            // Syncs to business info used by themes and frontend dashboard
            update_user_meta(get_current_user_id(), 'business_phone', $result['phone_number']);
            update_user_meta(get_current_user_id(), 'vmo_business_phone', $result['phone_number']);
        }
        
        return rest_ensure_response([
            'success' => true,
            'data' => $result
        ]);
        
        if ( is_wp_error($result) ) {
            return new WP_Error(
                $result->get_error_code(),
                $result->get_error_message(),
                ['status' => 500]
            );
        }
        
        // Save phone number to user meta
        if (is_user_logged_in()) {
            update_user_meta(get_current_user_id(), 'vmo_twilio_phone_number', $result['phone_number']);
            update_user_meta(get_current_user_id(), 'vmo_twilio_phone_sid', $result['sid']);
        }
        
        return rest_ensure_response([
            'success' => true,
            'data' => $result
        ]);
    }

    /**
     * List numbers route
     */
    public function list_numbers_route( WP_REST_Request $request ) {
        $result = $this->rest_client->list_numbers();
        
        if ( is_wp_error($result) ) {
            return new WP_Error(
                $result->get_error_code(),
                $result->get_error_message(),
                ['status' => 500]
            );
        }
        
        return rest_ensure_response([
            'success' => true,
            'data' => $result
        ]);
    }

    /**
     * Send SMS route
     */
    public function send_sms_route( WP_REST_Request $request ) {
        $to = sanitize_text_field($request->get_param('to'));
        $from = sanitize_text_field($request->get_param('from'));
        $body = sanitize_textarea_field($request->get_param('body'));
        
        $result = $this->rest_client->send_sms($to, $from, $body);
        
        if ( is_wp_error($result) ) {
            return new WP_Error(
                $result->get_error_code(),
                $result->get_error_message(),
                ['status' => 500]
            );
        }
        
        return rest_ensure_response([
            'success' => true,
            'data' => $result
        ]);
    }

    /**
     * Test connection route
     */
    public function test_connection_route( WP_REST_Request $request ) {
        $result = $this->rest_client->test_connection();
        
        if ( is_wp_error($result) ) {
            return new WP_Error(
                $result->get_error_code(),
                $result->get_error_message(),
                ['status' => 500]
            );
        }
        
        return rest_ensure_response([
            'success' => true,
            'data' => $result,
            'message' => 'Twilio connection successful!'
        ]);
    }

    /**
     * AJAX test connection (for dashboard buttons)
     */
    public function ajax_test_connection() {
        check_ajax_referer('vmo_nonce', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => 'Unauthorized']);
        }
        
        $result = $this->rest_client->test_connection();
        
        if ( is_wp_error($result) ) {
            wp_send_json_error([
                'message' => $result->get_error_message()
            ]);
        }
        
        wp_send_json_success([
            'message' => 'Twilio connection successful!',
            'data' => $result
        ]);
    }
}

// Initialize
if (class_exists('VMO_Twilio_Manager')) {
    new VMO_Twilio_Manager();
}
}

