@extends('layouts.admin')

@section('title', 'SMS Settings')

@section('page-title', 'SMS Settings')

@section('breadcrumbs')
    <a href="{{ route('admin.settings.index') }}" class="hover:text-primary">Settings</a>
    <span class="material-symbols-outlined text-xs">chevron_right</span>
    <span class="text-primary font-medium">SMS Settings</span>
@endsection

@section('content')
<div class="max-w-7xl mx-auto">
    <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
        <div class="mb-6">
            <h2 class="text-xl font-bold text-gray-900">SMS Settings</h2>
            <p class="text-sm text-gray-500 mt-1">Configure SMS gateway settings for sending notifications</p>
        </div>

        @if (session('success'))
            <div class="mb-6 p-4 bg-green-50 border border-green-200 rounded-lg flex items-center gap-2">
                <span class="material-symbols-outlined text-green-600">check_circle</span>
                <span class="text-sm text-green-800">{{ session('success') }}</span>
            </div>
        @endif

        @if (session('error'))
            <div class="mb-6 p-4 bg-red-50 border border-red-200 rounded-lg flex items-center gap-2">
                <span class="material-symbols-outlined text-red-600">error</span>
                <span class="text-sm text-red-800">{{ session('error') }}</span>
            </div>
        @endif

        @if ($errors->any())
            <div class="mb-6 p-4 bg-red-50 border border-red-200 rounded-lg">
                <div class="flex items-start">
                    <span class="material-symbols-outlined text-red-600 mr-2">error</span>
                    <div class="flex-1">
                        <h3 class="text-sm font-medium text-red-800 mb-2">Please correct the following errors:</h3>
                        <ul class="list-disc list-inside text-sm text-red-700 space-y-1">
                            @foreach ($errors->all() as $error)
                                <li>{{ $error }}</li>
                            @endforeach
                        </ul>
                    </div>
                </div>
            </div>
        @endif

        <form method="POST" action="{{ route('admin.settings.sms.update') }}" class="space-y-6" id="sms-settings-form">
            @csrf
            
            <!-- SMS Provider Selection -->
            <div>
                <label for="provider" class="block text-sm font-medium text-gray-700 mb-2">
                    SMS Provider <span class="text-red-500">*</span>
                </label>
                <select name="provider" id="provider" required class="w-full rounded-lg border border-gray-300 bg-white text-gray-900 px-4 py-2.5 shadow-sm focus:border-primary focus:ring-2 focus:ring-primary/20 transition-colors sm:text-sm" onchange="toggleProviderFields()">
                    <option value="twilio" {{ ($currentProvider ?? 'twilio') === 'twilio' ? 'selected' : '' }}>Twilio</option>
                    <option value="nexmo" {{ ($currentProvider ?? '') === 'nexmo' ? 'selected' : '' }}>Nexmo (Vonage)</option>
                    <option value="messagebird" {{ ($currentProvider ?? '') === 'messagebird' ? 'selected' : '' }}>MessageBird</option>
                    <option value="custom" {{ ($currentProvider ?? '') === 'custom' ? 'selected' : '' }}>Custom</option>
                </select>
                <p class="mt-1 text-xs text-gray-500">Select the SMS provider you want to use</p>
            </div>

            <!-- Twilio Configuration -->
            <div id="twilio-config" class="provider-config">
                <h3 class="text-lg font-semibold text-gray-900 mb-4">Twilio Configuration</h3>
                <div class="mb-4 p-4 bg-blue-50 border border-blue-200 rounded-lg">
                    <div class="flex items-start gap-3">
                        <span class="material-symbols-outlined text-blue-600 text-lg">info</span>
                        <div class="flex-1">
                            <h4 class="text-sm font-semibold text-blue-900 mb-2">How to Get Your Twilio Credentials</h4>
                            <ol class="text-xs text-blue-800 space-y-1.5 list-decimal list-inside">
                                <li>Sign up at <a href="https://www.twilio.com/try-twilio" target="_blank" class="underline font-medium">Twilio</a> (free trial available)</li>
                                <li>Go to <strong>Console Dashboard</strong> → <strong>Account Info</strong></li>
                                <li><strong>Account SID:</strong> Found in Account Info section (starts with AC...)</li>
                                <li><strong>Auth Token:</strong> Click "View" next to Auth Token in Account Info (keep it secret!)</li>
                                <li><strong>From Number:</strong> Go to <strong>Phone Numbers</strong> → <strong>Manage</strong> → <strong>Buy a Number</strong> → Purchase an SMS-enabled number</li>
                            </ol>
                            <p class="mt-2 text-xs text-blue-700">
                                <strong>Note:</strong> Free trial includes $15.50 credit. Use E.164 format for phone numbers (e.g., +1234567890).
                            </p>
                        </div>
                    </div>
                </div>
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div>
                        <label for="twilio_account_sid" class="block text-sm font-medium text-gray-700 mb-2">
                            Account SID <span class="text-red-500">*</span>
                        </label>
                        <input type="text" name="twilio_account_sid" id="twilio_account_sid" value="{{ old('twilio_account_sid', env('TWILIO_ACCOUNT_SID', $smsConfig->api_key ?? '')) }}" required class="w-full rounded-lg border border-gray-300 bg-white text-gray-900 px-4 py-2.5 shadow-sm placeholder:text-gray-400 focus:border-primary focus:ring-2 focus:ring-primary/20 transition-colors sm:text-sm" placeholder="ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx">
                        <p class="mt-1 text-xs text-gray-500">Your Twilio Account SID</p>
                    </div>
                    <div>
                        <label for="twilio_auth_token" class="block text-sm font-medium text-gray-700 mb-2">
                            Auth Token <span class="text-red-500">*</span>
                        </label>
                        <input type="password" name="twilio_auth_token" id="twilio_auth_token" value="{{ old('twilio_auth_token') }}" required class="w-full rounded-lg border border-gray-300 bg-white text-gray-900 px-4 py-2.5 shadow-sm placeholder:text-gray-400 focus:border-primary focus:ring-2 focus:ring-primary/20 transition-colors sm:text-sm" placeholder="Leave blank to keep current">
                        <p class="mt-1 text-xs text-gray-500">Your Twilio Auth Token</p>
                    </div>
                    <div>
                        <label for="twilio_from_number" class="block text-sm font-medium text-gray-700 mb-2">
                            From Number <span class="text-red-500">*</span>
                        </label>
                        <input type="text" name="twilio_from_number" id="twilio_from_number" value="{{ old('twilio_from_number', env('TWILIO_FROM_NUMBER', $smsConfig->config['from_number'] ?? '')) }}" required class="w-full rounded-lg border border-gray-300 bg-white text-gray-900 px-4 py-2.5 shadow-sm placeholder:text-gray-400 focus:border-primary focus:ring-2 focus:ring-primary/20 transition-colors sm:text-sm" placeholder="+1234567890">
                        <p class="mt-1 text-xs text-gray-500">Your Twilio phone number (E.164 format)</p>
                    </div>
                </div>
            </div>

            <!-- Nexmo Configuration -->
            <div id="nexmo-config" class="provider-config hidden">
                <h3 class="text-lg font-semibold text-gray-900 mb-4">Nexmo (Vonage) Configuration</h3>
                <div class="mb-4 p-4 bg-blue-50 border border-blue-200 rounded-lg">
                    <div class="flex items-start gap-3">
                        <span class="material-symbols-outlined text-blue-600 text-lg">info</span>
                        <div class="flex-1">
                            <h4 class="text-sm font-semibold text-blue-900 mb-2">How to Get Your Nexmo (Vonage) Credentials</h4>
                            <ol class="text-xs text-blue-800 space-y-1.5 list-decimal list-inside">
                                <li>Sign up at <a href="https://www.vonage.com/communications-apis/" target="_blank" class="underline font-medium">Vonage API Platform</a> (free trial available)</li>
                                <li>Go to <strong>Dashboard</strong> → <strong>API Settings</strong></li>
                                <li><strong>API Key:</strong> Found in API Settings section</li>
                                <li><strong>API Secret:</strong> Found in API Settings section (click "Show" to reveal)</li>
                                <li><strong>From Number/Name:</strong> Use your verified sender ID or phone number (can be alphanumeric for some countries)</li>
                            </ol>
                            <p class="mt-2 text-xs text-blue-700">
                                <strong>Note:</strong> Free tier includes €2 credit. Sender ID format varies by country - use phone number or alphanumeric name.
                            </p>
                        </div>
                    </div>
                </div>
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div>
                        <label for="nexmo_api_key" class="block text-sm font-medium text-gray-700 mb-2">
                            API Key <span class="text-red-500">*</span>
                        </label>
                        <input type="text" name="nexmo_api_key" id="nexmo_api_key" value="{{ old('nexmo_api_key', env('NEXMO_API_KEY', $smsConfig->api_key ?? '')) }}" required class="w-full rounded-lg border border-gray-300 bg-white text-gray-900 px-4 py-2.5 shadow-sm placeholder:text-gray-400 focus:border-primary focus:ring-2 focus:ring-primary/20 transition-colors sm:text-sm" placeholder="Your Nexmo API Key">
                    </div>
                    <div>
                        <label for="nexmo_api_secret" class="block text-sm font-medium text-gray-700 mb-2">
                            API Secret <span class="text-red-500">*</span>
                        </label>
                        <input type="password" name="nexmo_api_secret" id="nexmo_api_secret" value="{{ old('nexmo_api_secret') }}" required class="w-full rounded-lg border border-gray-300 bg-white text-gray-900 px-4 py-2.5 shadow-sm placeholder:text-gray-400 focus:border-primary focus:ring-2 focus:ring-primary/20 transition-colors sm:text-sm" placeholder="Leave blank to keep current">
                    </div>
                    <div>
                        <label for="nexmo_from" class="block text-sm font-medium text-gray-700 mb-2">
                            From Number/Name <span class="text-red-500">*</span>
                        </label>
                        <input type="text" name="nexmo_from" id="nexmo_from" value="{{ old('nexmo_from', env('NEXMO_FROM', $smsConfig->config['from'] ?? '')) }}" required class="w-full rounded-lg border border-gray-300 bg-white text-gray-900 px-4 py-2.5 shadow-sm placeholder:text-gray-400 focus:border-primary focus:ring-2 focus:ring-primary/20 transition-colors sm:text-sm" placeholder="ProInvoice or +1234567890">
                        <p class="mt-1 text-xs text-gray-500">Sender ID or phone number</p>
                    </div>
                </div>
            </div>

            <!-- MessageBird Configuration -->
            <div id="messagebird-config" class="provider-config hidden">
                <h3 class="text-lg font-semibold text-gray-900 mb-4">MessageBird Configuration</h3>
                <div class="mb-4 p-4 bg-blue-50 border border-blue-200 rounded-lg">
                    <div class="flex items-start gap-3">
                        <span class="material-symbols-outlined text-blue-600 text-lg">info</span>
                        <div class="flex-1">
                            <h4 class="text-sm font-semibold text-blue-900 mb-2">How to Get Your MessageBird Credentials</h4>
                            <ol class="text-xs text-blue-800 space-y-1.5 list-decimal list-inside">
                                <li>Sign up at <a href="https://www.messagebird.com/" target="_blank" class="underline font-medium">MessageBird</a> (free trial available)</li>
                                <li>Go to <strong>Dashboard</strong> → <strong>API Keys</strong></li>
                                <li><strong>API Key:</strong> Copy your Live API Key from the API Keys section</li>
                                <li><strong>Originator:</strong> Use your verified sender ID or phone number</li>
                                <li>Verify your phone number or sender ID in <strong>Settings</strong> → <strong>Phone Numbers</strong></li>
                            </ol>
                            <p class="mt-2 text-xs text-blue-700">
                                <strong>Note:</strong> Free tier includes limited messages. Originator can be a phone number (E.164 format) or alphanumeric sender ID.
                            </p>
                        </div>
                    </div>
                </div>
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div>
                        <label for="messagebird_api_key" class="block text-sm font-medium text-gray-700 mb-2">
                            API Key <span class="text-red-500">*</span>
                        </label>
                        <input type="text" name="messagebird_api_key" id="messagebird_api_key" value="{{ old('messagebird_api_key', env('MESSAGEBIRD_API_KEY', $smsConfig->api_key ?? '')) }}" required class="w-full rounded-lg border border-gray-300 bg-white text-gray-900 px-4 py-2.5 shadow-sm placeholder:text-gray-400 focus:border-primary focus:ring-2 focus:ring-primary/20 transition-colors sm:text-sm" placeholder="Your MessageBird API Key">
                    </div>
                    <div>
                        <label for="messagebird_originator" class="block text-sm font-medium text-gray-700 mb-2">
                            Originator <span class="text-red-500">*</span>
                        </label>
                        <input type="text" name="messagebird_originator" id="messagebird_originator" value="{{ old('messagebird_originator', env('MESSAGEBIRD_ORIGINATOR', $smsConfig->config['originator'] ?? '')) }}" required class="w-full rounded-lg border border-gray-300 bg-white text-gray-900 px-4 py-2.5 shadow-sm placeholder:text-gray-400 focus:border-primary focus:ring-2 focus:ring-primary/20 transition-colors sm:text-sm" placeholder="ProInvoice or +1234567890">
                        <p class="mt-1 text-xs text-gray-500">Sender ID or phone number</p>
                    </div>
                </div>
            </div>

            <!-- Custom Configuration -->
            <div id="custom-config" class="provider-config hidden">
                <h3 class="text-lg font-semibold text-gray-900 mb-4">Custom SMS Provider Configuration</h3>
                <div class="mb-4 p-4 bg-blue-50 border border-blue-200 rounded-lg">
                    <div class="flex items-start gap-3">
                        <span class="material-symbols-outlined text-blue-600 text-lg">info</span>
                        <div class="flex-1">
                            <h4 class="text-sm font-semibold text-blue-900 mb-2">How to Configure Custom SMS Provider</h4>
                            <p class="text-xs text-blue-800 mb-2">
                                Use this option if you have your own SMS API endpoint or are using a third-party service not listed above.
                            </p>
                            <ol class="text-xs text-blue-800 space-y-1.5 list-decimal list-inside mb-2">
                                <li><strong>API URL:</strong> Your custom endpoint URL (must be publicly accessible via HTTPS)</li>
                                <li><strong>API Key:</strong> (Optional) Authentication key for your API</li>
                                <li><strong>API Secret:</strong> (Optional) Additional security token for your API</li>
                            </ol>
                            <div class="mt-2 p-2 bg-blue-100 rounded text-xs text-blue-900">
                                <strong>Expected Request Format:</strong>
                                <pre class="mt-1 text-xs bg-white p-2 rounded overflow-x-auto">POST {API_URL}
{
  "to": "+1234567890",
  "message": "Your SMS message",
  "sender_id": "ProInvoice"
}</pre>
                            </div>
                            <div class="mt-2 p-2 bg-blue-100 rounded text-xs text-blue-900">
                                <strong>Expected Response Format:</strong>
                                <pre class="mt-1 text-xs bg-white p-2 rounded overflow-x-auto">{
  "success": true,
  "message": "SMS sent successfully",
  "id": "message_id_123"
}</pre>
                            </div>
                            <p class="mt-2 text-xs text-blue-700">
                                <strong>Note:</strong> Your API must accept POST requests, return JSON responses, and handle phone numbers in E.164 format.
                            </p>
                        </div>
                    </div>
                </div>
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div class="md:col-span-2">
                        <label for="custom_api_url" class="block text-sm font-medium text-gray-700 mb-2">
                            API URL <span class="text-red-500">*</span>
                        </label>
                        <input type="url" name="custom_api_url" id="custom_api_url" value="{{ old('custom_api_url', env('CUSTOM_SMS_API_URL', '')) }}" required class="w-full rounded-lg border border-gray-300 bg-white text-gray-900 px-4 py-2.5 shadow-sm placeholder:text-gray-400 focus:border-primary focus:ring-2 focus:ring-primary/20 transition-colors sm:text-sm" placeholder="https://api.example.com/sms/send">
                        <p class="mt-1 text-xs text-gray-500">Full URL endpoint for sending SMS</p>
                    </div>
                    <div>
                        <label for="custom_api_key" class="block text-sm font-medium text-gray-700 mb-2">API Key</label>
                        <input type="text" name="custom_api_key" id="custom_api_key" value="{{ old('custom_api_key', env('CUSTOM_SMS_API_KEY', $smsConfig->api_key ?? '')) }}" class="w-full rounded-lg border border-gray-300 bg-white text-gray-900 px-4 py-2.5 shadow-sm placeholder:text-gray-400 focus:border-primary focus:ring-2 focus:ring-primary/20 transition-colors sm:text-sm" placeholder="Optional API key">
                    </div>
                    <div>
                        <label for="custom_api_secret" class="block text-sm font-medium text-gray-700 mb-2">API Secret</label>
                        <input type="password" name="custom_api_secret" id="custom_api_secret" value="{{ old('custom_api_secret') }}" class="w-full rounded-lg border border-gray-300 bg-white text-gray-900 px-4 py-2.5 shadow-sm placeholder:text-gray-400 focus:border-primary focus:ring-2 focus:ring-primary/20 transition-colors sm:text-sm" placeholder="Leave blank to keep current">
                    </div>
                </div>
            </div>

            <!-- Sender ID (Common for all providers) -->
            <div class="pt-6 border-t border-gray-200">
                <div>
                    <label for="sender_id" class="block text-sm font-medium text-gray-700 mb-2">Sender ID</label>
                    <input type="text" name="sender_id" id="sender_id" value="{{ old('sender_id', $smsConfig->sender_id ?? env('SMS_SENDER_ID', '')) }}" class="w-full rounded-lg border border-gray-300 bg-white text-gray-900 px-4 py-2.5 shadow-sm placeholder:text-gray-400 focus:border-primary focus:ring-2 focus:ring-primary/20 transition-colors sm:text-sm" placeholder="ProInvoice">
                    <p class="mt-1 text-xs text-gray-500">Optional: Default sender name/ID for SMS messages</p>
                </div>
            </div>

            <!-- Form Actions -->
            <div class="flex items-center justify-end gap-3 pt-6 border-t border-gray-200">
                <button type="button" onclick="openTestSmsModal()" class="px-4 py-2.5 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 transition-colors font-medium">
                    <span class="material-symbols-outlined text-sm mr-2 align-middle">sms</span>
                    Test SMS
                </button>
                <button type="submit" class="px-4 py-2.5 bg-primary text-white rounded-lg hover:bg-primary/90 transition-colors font-medium shadow-sm focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary">
                    Save Settings
                </button>
            </div>
        </form>
    </div>
</div>

<!-- Test SMS Modal -->
<div id="test-sms-modal" data-admin-modal class="hidden fixed inset-0 z-[100] overflow-y-auto" aria-labelledby="modal-title" role="dialog" aria-modal="true">
    <div class="flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
        <div class="fixed inset-0 bg-gray-500 bg-opacity-75 transition-opacity" aria-hidden="true" onclick="closeTestSmsModal()"></div>
        <span class="hidden sm:inline-block sm:align-middle sm:h-screen" aria-hidden="true">&#8203;</span>
        <div class="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full">
            <form method="POST" action="{{ route('admin.settings.sms.test') }}">
                @csrf
                <div class="bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
                    <h3 class="text-lg leading-6 font-medium text-gray-900 mb-4">Send Test SMS</h3>
                    <div>
                        <label for="test_phone" class="block text-sm font-medium text-gray-700 mb-2">
                            Phone Number <span class="text-red-500">*</span>
                        </label>
                        <input type="text" name="test_phone" id="test_phone" required class="w-full rounded-lg border border-gray-300 bg-white text-gray-900 px-4 py-2.5 shadow-sm placeholder:text-gray-400 focus:border-primary focus:ring-2 focus:ring-primary/20 transition-colors sm:text-sm" placeholder="+1234567890">
                        <p class="mt-1 text-xs text-gray-500">Enter phone number in E.164 format (e.g., +1234567890)</p>
                    </div>
                </div>
                <div class="bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse">
                    <button type="submit" class="w-full inline-flex justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-primary text-base font-medium text-white hover:bg-primary/90 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary sm:ml-3 sm:w-auto sm:text-sm">
                        Send Test SMS
                    </button>
                    <button type="button" onclick="closeTestSmsModal()" class="mt-3 w-full inline-flex justify-center rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary sm:mt-0 sm:ml-3 sm:w-auto sm:text-sm">
                        Cancel
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
function toggleProviderFields() {
    const provider = document.getElementById('provider').value;
    
    // Hide all config sections
    document.querySelectorAll('.provider-config').forEach(el => {
        el.classList.add('hidden');
    });
    
    // Show relevant config section
    if (provider === 'twilio') {
        document.getElementById('twilio-config').classList.remove('hidden');
        document.getElementById('twilio_account_sid').required = true;
        document.getElementById('twilio_auth_token').required = true;
        document.getElementById('twilio_from_number').required = true;
    } else {
        document.getElementById('twilio_account_sid').required = false;
        document.getElementById('twilio_auth_token').required = false;
        document.getElementById('twilio_from_number').required = false;
    }
    
    if (provider === 'nexmo') {
        document.getElementById('nexmo-config').classList.remove('hidden');
        document.getElementById('nexmo_api_key').required = true;
        document.getElementById('nexmo_api_secret').required = true;
        document.getElementById('nexmo_from').required = true;
    } else {
        document.getElementById('nexmo_api_key').required = false;
        document.getElementById('nexmo_api_secret').required = false;
        document.getElementById('nexmo_from').required = false;
    }
    
    if (provider === 'messagebird') {
        document.getElementById('messagebird-config').classList.remove('hidden');
        document.getElementById('messagebird_api_key').required = true;
        document.getElementById('messagebird_originator').required = true;
    } else {
        document.getElementById('messagebird_api_key').required = false;
        document.getElementById('messagebird_originator').required = false;
    }
    
    if (provider === 'custom') {
        document.getElementById('custom-config').classList.remove('hidden');
        document.getElementById('custom_api_url').required = true;
    } else {
        document.getElementById('custom_api_url').required = false;
    }
}

function openTestSmsModal() {
    document.getElementById('test-sms-modal').classList.remove('hidden');
}

function closeTestSmsModal() {
    document.getElementById('test-sms-modal').classList.add('hidden');
}

// Initialize on page load
document.addEventListener('DOMContentLoaded', function() {
    toggleProviderFields();
});
</script>
@endsection
