<?php

namespace App\Services;

use App\Models\VoiceGateway;
use Illuminate\Support\Facades\Http;

class VoiceService
{
    /**
     * Send voice call to a single contact
     */
    public function send_voice($contact, $voice_file_path, $caller_id = null, $retry_count = 0, $message = null)
    {
        // Prefix contact with 88 if it contains exactly 11 digits and has no country code
        $cleanContact = preg_replace('/\D/', '', $contact);
        if (strlen($cleanContact) === 11 && strpos($cleanContact, '88') !== 0) {
            $contact = '88' . $cleanContact;
        }

        $result = cache()->remember('voiceapiForSendVoice', 60 * 1, function () {
            return VoiceGateway::where('status', 'enable')->first();
        });

        if ($result) {
            // Get caller ID and retry from gateway if not provided
            $caller_id = $caller_id ?? $result->caller_id;
            $retry_count = $retry_count ?? $result->retry_count;

            try {
                // Prepare request with credentials
                $http = Http::timeout(60);

                // Add authentication headers if user/pass are provided
                if ($result->username && $result->password) {
                    $http = $http->withHeaders([
                        'user' => $result->username,
                        'pass' => $result->password,
                    ]);
                }

                // Prepare destinations array
                $destinations = [$contact];

                $response = $http->attach('voice', file_get_contents($voice_file_path), basename($voice_file_path))
                    ->post($result->api_url, [
                        'callerid' => $caller_id,
                        'retry' => $retry_count,
                        'arr_dst' => json_encode($destinations),
                    ]);

                $data = $response->json();

                if ($data['success'] ?? false) {
                    return [
                        'success' => true,
                        'blast_id' => $data['blast_id'] ?? null,
                        'message' => $data['msg'] ?? 'Voice call sent successfully',
                        'call_status' => 'Success'
                    ];
                }

                return [
                    'success' => false,
                    'message' => $data['msg'] ?? 'Failed to send voice call',
                    'call_status' => 'Failed'
                ];
            } catch (\Exception $e) {
                return [
                    'success' => false,
                    'message' => 'Error: ' . $e->getMessage(),
                    'call_status' => 'Error'
                ];
            }
        } else {
            return [
                'success' => false,
                'message' => 'No active voice gateway configured',
                'call_status' => 'No Gateway'
            ];
        }
    }
}

