@section('header')
	@include('common.header')
@stop

@section('content')
<meta name="csrf-token" content="{{ csrf_token() }}">
<div class="row">
    <div class="col-md-12">
        <div class="panel panel-default">
            <div class="panel-heading">
                <h3 class="panel-title">
                    <i class="fa fa-plug"></i> Integration Settings
                </h3>
                <p class="text-muted">Configure SMS notifications and phone system integration</p>
            </div>
            <div class="panel-body">
                @if(session('success'))
                    <div class="alert alert-success alert-dismissible">
                        <button type="button" class="close" data-dismiss="alert">&times;</button>
                        {{ session('success') }}
                    </div>
                @endif

                @if($errors->any())
                    <div class="alert alert-danger alert-dismissible">
                        <button type="button" class="close" data-dismiss="alert">&times;</button>
                        <ul class="mb-0">
                            @foreach($errors->all() as $error)
                                <li>{{ $error }}</li>
                            @endforeach
                        </ul>
                    </div>
                @endif

                <form method="POST" action="{{ route('admin.settings.integrations.update') }}" id="integrations-form">
                    @csrf
                    
                    <!-- SMS Notifications Section -->
                    <div class="panel panel-info">
                        <div class="panel-heading">
                            <h4><i class="fa fa-mobile"></i> SMS Notifications</h4>
                            <small>Automatically send SMS notifications when tasks are completed</small>
                        </div>
                        <div class="panel-body">
                            <div class="row">
                                <div class="col-md-6">
                                    <!-- SMS Enabled -->
                                    <div class="form-group">
                                        <label class="checkbox">
                                            <input type="checkbox" name="sms_enabled" value="1" 
                                                   {{ $settings['sms_enabled'] ? 'checked' : '' }}>
                                            Enable SMS Notifications
                                        </label>
                                        <p class="help-block">Send automatic SMS when tasks are completed</p>
                                    </div>

                                    <!-- SMS Completion Message -->
                                    <div class="form-group">
                                        <label for="sms_completion_message">Completion Message</label>
                                        <textarea name="sms_completion_message" id="sms_completion_message" 
                                                  class="form-control" rows="3" maxlength="500"
                                                  placeholder="Thank you for choosing our services!">{{ $settings['sms_completion_message'] }}</textarea>
                                        <p class="help-block">Custom message added to task completion SMS (optional)</p>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="alert alert-info">
                                        <h6><i class="fa fa-info-circle"></i> How it works:</h6>
                                        <ul>
                                            <li>SMS sent automatically when tasks are marked as completed</li>
                                            <li>System detects customer phone number from client/customer records</li>
                                            <li>All SMS activity is logged in customer notifications</li>
                                            <li>Configure your SMS provider below to enable this feature</li>
                                        </ul>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Twilio SMS Settings -->
                    <div class="panel panel-primary">
                        <div class="panel-heading">
                            <h4><i class="fa fa-cloud"></i> Twilio SMS Service (Recommended)</h4>
                            <small>Primary SMS provider with high reliability</small>
                        </div>
                        <div class="panel-body">
                            <div class="row">
                                <div class="col-md-6">
                                    <!-- Twilio Enabled -->
                                    <div class="form-group">
                                        <label class="checkbox">
                                            <input type="checkbox" name="twilio_enabled" value="1" 
                                                   {{ $settings['twilio_enabled'] ? 'checked' : '' }}>
                                            Enable Twilio SMS
                                        </label>
                                    </div>

                                    <!-- Twilio SID -->
                                    <div class="form-group">
                                        <label for="twilio_sid">Account SID</label>
                                        <input type="text" name="twilio_sid" id="twilio_sid" 
                                               class="form-control" value="{{ $settings['twilio_sid'] }}"
                                               placeholder="ACxxxx...">
                                    </div>

                                    <!-- Twilio Token -->
                                    <div class="form-group">
                                        <label for="twilio_token">Auth Token</label>
                                        <input type="password" name="twilio_token" id="twilio_token" 
                                               class="form-control" value="{{ $settings['twilio_token'] }}"
                                               placeholder="Your auth token">
                                    </div>

                                    <!-- Twilio From Number -->
                                    <div class="form-group">
                                        <label for="twilio_from">From Phone Number</label>
                                        <input type="text" name="twilio_from" id="twilio_from" 
                                               class="form-control" value="{{ $settings['twilio_from'] }}"
                                               placeholder="+1234567890">
                                        <p class="help-block">Your Twilio phone number (include country code)</p>
                                    </div>

                                    <!-- Test Connection -->
                                    <div class="form-group">
                                        <button type="button" class="btn btn-info btn-block" id="test-twilio-connection-btn">
                                            <i class="fa fa-flash"></i> Test Connection
                                        </button>
                                        <p class="help-block">Test your Twilio credentials and connection</p>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <!-- Test SMS Section -->
                                    <div class="well">
                                        <h6><i class="fa fa-paper-plane"></i> Test SMS</h6>
                                        <div class="form-group">
                                            <input type="text" id="test_phone" class="form-control" 
                                                   placeholder="+44123456789" maxlength="20">
                                            <small class="text-muted">Enter phone number to test SMS</small>
                                        </div>
                                        <div class="form-group">
                                            <textarea id="test_message" class="form-control" rows="2" 
                                                      placeholder="Test message..." maxlength="160">This is a test SMS from Seraph3 integration settings.</textarea>
                                        </div>
                                        <button type="button" class="btn btn-warning btn-sm" id="test-sms-btn">
                                            <i class="fa fa-paper-plane"></i> Send Test SMS
                                        </button>
                                    </div>

                                    <!-- Twilio Setup Instructions -->
                                    <div class="alert alert-info">
                                        <h6><i class="fa fa-question-circle"></i> Setup Instructions:</h6>
                                        <ol>
                                            <li>Sign up at <a href="https://www.twilio.com" target="_blank">twilio.com</a></li>
                                            <li>Get your Account SID and Auth Token from console</li>
                                            <li>Purchase a phone number</li>
                                            <li>Enter credentials above and test connection</li>
                                            <li>Send a test SMS to verify everything works</li>
                                        </ol>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- TextMagic SMS Settings -->
                    <div class="panel panel-primary">
                        <div class="panel-heading">
                            <h4><i class="fa fa-cloud"></i> TextMagic SMS Service</h4>
                            <small>Alternative SMS provider with reliable delivery</small>
                        </div>
                        <div class="panel-body">
                            <div class="row">
                                <div class="col-md-6">
                                    <!-- TextMagic Enabled -->
                                    <div class="form-group">
                                        <label class="checkbox">
                                            <input type="checkbox" name="textmagic_enabled" value="1"
                                                   {{ $settings['textmagic_enabled'] ? 'checked' : '' }}>
                                            Enable TextMagic SMS
                                        </label>
                                    </div>

                                    <!-- TextMagic Username -->
                                    <div class="form-group">
                                        <label for="textmagic_username">Username</label>
                                        <input type="text" name="textmagic_username" id="textmagic_username"
                                               class="form-control" value="{{ $settings['textmagic_username'] }}"
                                               placeholder="Your TextMagic username">
                                    </div>

                                    <!-- TextMagic API Key -->
                                    <div class="form-group">
                                        <label for="textmagic_api_key">API Key</label>
                                        <input type="password" name="textmagic_api_key" id="textmagic_api_key"
                                               class="form-control" value="{{ $settings['textmagic_api_key'] }}"
                                               placeholder="Your API key">
                                    </div>

                                    <!-- Test Connection -->
                                    <div class="form-group">
                                        <button type="button" class="btn btn-info btn-block" id="test-textmagic-connection-btn">
                                            <i class="fa fa-flash"></i> Test Connection
                                        </button>
                                        <p class="help-block">Test your TextMagic credentials and connection</p>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <!-- Test SMS Section -->
                                    <div class="well">
                                        <h6><i class="fa fa-paper-plane"></i> Test SMS</h6>
                                        <div class="form-group">
                                            <input type="text" id="test_phone_textmagic" class="form-control"
                                                   placeholder="+44123456789" maxlength="20">
                                            <small class="text-muted">Enter phone number to test SMS</small>
                                        </div>
                                        <div class="form-group">
                                            <textarea id="test_message_textmagic" class="form-control" rows="2"
                                                      placeholder="Test message..." maxlength="160">This is a test SMS from Seraph3 via TextMagic.</textarea>
                                        </div>
                                        <button type="button" class="btn btn-warning btn-sm" id="test-sms-textmagic-btn">
                                            <i class="fa fa-paper-plane"></i> Send Test SMS
                                        </button>
                                    </div>

                                    <!-- TextMagic Setup Instructions -->
                                    <div class="alert alert-info">
                                        <h6><i class="fa fa-question-circle"></i> Setup Instructions:</h6>
                                        <ol>
                                            <li>Sign up at <a href="https://www.textmagic.com" target="_blank">textmagic.com</a></li>
                                            <li>Get your username and API key from your dashboard</li>
                                            <li>Enter credentials above and test connection</li>
                                            <li>Send a test SMS to verify everything works</li>
                                        </ol>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Phone System Integration -->
                    <div class="panel panel-success">
                        <div class="panel-heading">
                            <h4><i class="fa fa-phone"></i> 3CX Phone System Integration</h4>
                            <small>Connect to 3CX PBX for call management and logging</small>
                        </div>
                        <div class="panel-body">
                            <div class="row">
                                <div class="col-md-6">
                                    <!-- 3CX Enabled -->
                                    <div class="form-group">
                                        <label class="checkbox">
                                            <input type="checkbox" name="threecx_enabled" value="1" 
                                                   {{ $settings['threecx_enabled'] ? 'checked' : '' }}>
                                            Enable 3CX Phone System Integration
                                        </label>
                                    </div>

                                    <!-- 3CX Base URL -->
                                    <div class="form-group">
                                        <label for="threecx_base_url">3CX Base URL</label>
                                        <input type="url" name="threecx_base_url" id="threecx_base_url" 
                                               class="form-control" value="{{ $settings['threecx_base_url'] }}"
                                               placeholder="https://pbx.yourdomain.com">
                                        <p class="help-block">Full URL to your 3CX management console</p>
                                    </div>

                                    <!-- 3CX OAuth2 Client ID -->
                                    <div class="form-group">
                                        <label for="threecx_client_id">OAuth2 Client ID <span class="text-danger">*</span></label>
                                        <input type="text" name="threecx_client_id" id="threecx_client_id" 
                                               class="form-control" value="{{ $settings['threecx_client_id'] }}"
                                               placeholder="Your 3CX OAuth2 Client ID">
                                        <p class="help-block">OAuth2 client ID from 3CX Management Console</p>
                                    </div>

                                    <!-- 3CX OAuth2 Client Secret -->
                                    <div class="form-group">
                                        <label for="threecx_client_secret">OAuth2 Client Secret <span class="text-danger">*</span></label>
                                        <input type="password" name="threecx_client_secret" id="threecx_client_secret" 
                                               class="form-control" value="{{ $settings['threecx_client_secret'] }}"
                                               placeholder="Your 3CX OAuth2 Client Secret">
                                        <p class="help-block">OAuth2 client secret from 3CX Management Console</p>
                                    </div>


                                    <!-- Extension for Calls -->
                                    <div class="form-group">
                                        <label for="threecx_extension">Default Extension</label>
                                        <input type="text" name="threecx_extension" id="threecx_extension" 
                                               class="form-control" value="{{ $settings['threecx_extension'] ?? '324' }}"
                                               placeholder="324" maxlength="10">
                                        <p class="help-block">Extension to use for making calls when user profile extension is not set</p>
                                    </div>

                                </div>
                                <div class="col-md-6">
                                    <!-- Test 3CX System -->
                                    <div class="well">
                                        <h6><i class="fa fa-flask"></i> Test 3CX Connection</h6>
                                        <p>Test connection to 3CX API</p>
                                        <button type="button" class="btn btn-success btn-sm" id="test-3cx-btn">
                                            <i class="fa fa-phone"></i> Test 3CX Connection
                                        </button>
                                    </div>

                                    <!-- Test 3CX Call -->
                                    <div class="well">
                                        <h6><i class="fa fa-phone-square"></i> Test 3CX Call</h6>
                                        <div class="form-group">
                                            <input type="text" id="test_to_number" class="form-control" 
                                                   placeholder="07776668338" maxlength="20" value="07776668338">
                                            <small class="text-muted">Phone number to call (will use extension from settings above)</small>
                                        </div>
                                        <div class="alert alert-info">
                                            <small>
                                                <strong>How it works:</strong><br>
                                                1. Call is made from: <strong><span id="display-extension">laravelapp</span></strong><br>
                                                2. Answer the extension when it rings<br>
                                                3. You'll be connected to the destination number<br>
                                                <strong>Timeout:</strong> 30 seconds for call establishment
                                            </small>
                                        </div>
                                        <button type="button" class="btn btn-warning btn-sm" id="test-3cx-call-btn">
                                            <i class="fa fa-phone"></i> Make Test Call
                                        </button>
                                    </div>


                                    <!-- Recording Path -->
                                    <div class="form-group">
                                        <label for="threecx_recording_path">Recording Path</label>
                                        <input type="text" name="threecx_recording_path" id="threecx_recording_path" 
                                               class="form-control" value="{{ $settings['threecx_recording_path'] }}"
                                               placeholder="/var/lib/3cx/Recordings/">
                                        <p class="help-block">Path to call recordings (optional)</p>
                                    </div>


                                </div>
                            </div>
                        </div>
                    </div>



                    <!-- Xero Integration -->
                    <div class="panel panel-warning">
                        <div class="panel-heading">
                            <h4><i class="fa fa-cloud"></i> Xero Integration</h4>
                            <small>Direct connection to Xero for invoice and accounting sync</small>
                        </div>
                        <div class="panel-body">
                            <div class="row">
                                <div class="col-md-6">
                                    <!-- Xero Enabled -->
                                    <div class="form-group">
                                        <label class="checkbox">
                                            <input type="checkbox" name="xero_enabled" value="1" 
                                                   {{ $settings['xero_enabled'] ? 'checked' : '' }}>
                                            Enable Xero Integration
                                        </label>
                                        <p class="help-block">Direct API integration replacing microservice</p>
                                    </div>

                                    <!-- Xero Client ID -->
                                    <div class="form-group">
                                        <label for="xero_client_id">Client ID</label>
                                        <input type="text" name="xero_client_id" id="xero_client_id" 
                                               class="form-control" value="{{ $settings['xero_client_id'] }}"
                                               placeholder="Your Xero app Client ID">
                                        <p class="help-block">From your Xero app configuration</p>
                                    </div>

                                    <!-- Xero Client Secret -->
                                    <div class="form-group">
                                        <label for="xero_client_secret">Client Secret</label>
                                        <input type="password" name="xero_client_secret" id="xero_client_secret" 
                                               class="form-control" value="{{ $settings['xero_client_secret'] }}"
                                               placeholder="Your Xero app Client Secret">
                                        <p class="help-block">Keep this secure and private</p>
                                    </div>

                                    <!-- Xero Redirect URI -->
                                    <div class="form-group">
                                        <label for="xero_redirect_uri">Redirect URI</label>
                                        <input type="url" name="xero_redirect_uri" id="xero_redirect_uri" 
                                               class="form-control" value="{{ $settings['xero_redirect_uri'] }}"
                                               readonly>
                                        <p class="help-block">Use this in your Xero app configuration</p>
                                    </div>

                                    <!-- Xero Bank Account ID -->
                                    <div class="form-group">
                                        <label for="xero_bank_account_id">Bank Account ID</label>
                                        <input type="text" name="xero_bank_account_id" id="xero_bank_account_id" 
                                               class="form-control" value="{{ $settings['xero_bank_account_id'] ?? '' }}"
                                               placeholder="Enter Xero bank account ID">
                                        <p class="help-block">Will be auto-populated when sending first paid invoice, or you can enter it manually</p>
                                    </div>

                                    <!-- Test Connection -->
                                    <div class="form-group">
                                        <button type="button" class="btn btn-info btn-block" id="test-xero-btn">
                                            <i class="fa fa-flash"></i> Test Connection
                                        </button>
                                        <p class="help-block">Test your Client ID and Secret</p>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="alert alert-info">
                                        <h6><i class="fa fa-info-circle"></i> Xero Setup:</h6>
                                        <ol>
                                            <li>Create a Xero app at <a href="https://developer.xero.com" target="_blank">developer.xero.com</a></li>
                                            <li>Copy the Client ID and Secret here</li>
                                            <li>Set the redirect URI in your Xero app</li>
                                            <li>Save settings and test connection</li>
                                        </ol>
                                    </div>
                                    
                                    <div class="alert alert-warning">
                                        <h6><i class="fa fa-exclamation-triangle"></i> Features:</h6>
                                        <ul>
                                            <li>Chart of accounts sync</li>
                                            <li>Invoice creation</li>
                                            <li>Purchase order sync</li>
                                            <li>Contact management</li>
                                        </ul>
                                    </div>

                                    
                                                </div>
            </div>
        </div>
    </div>

    <!-- Office 365 Calendar Integration -->
    <div class="panel panel-info">
        <div class="panel-heading">
            <h4><i class="fa fa-calendar"></i> Office 365 Calendar Integration</h4>
            <small>Connect to Office 365 calendar for event synchronization</small>
        </div>
        <div class="panel-body">
            <div class="row">
                <div class="col-md-6">
                    <!-- Office 365 Status -->
                    <div class="form-group">
                        <label class="checkbox">
                            <input type="checkbox" name="office365_enabled" value="1" 
                                   {{ $settings['office365_enabled'] ?? false ? 'checked' : '' }}>
                            Enable Office 365 Calendar Integration
                        </label>
                        <p class="help-block">Show Office 365 events in dashboard calendar</p>
                    </div>

                    <!-- Office 365 Client ID -->
                    <div class="form-group">
                        <label for="office365_client_id">App ID</label>
                        <input type="text" name="office365_client_id" id="office365_client_id" 
                               class="form-control" value="{{ $settings['office365_client_id'] ?? '' }}"
                               placeholder="Your Office 365 app App ID">
                        <p class="help-block">From your Azure app registration</p>
                    </div>

                    <!-- Office 365 Client Secret -->
                    <div class="form-group">
                        <label for="office365_client_secret">Client Secret</label>
                        <input type="password" name="office365_client_secret" id="office365_client_secret" 
                               class="form-control" value="{{ $settings['office365_client_secret'] ?? '' }}"
                               placeholder="Your Office 365 app Client Secret">
                        <p class="help-block">Keep this secure and private</p>
                    </div>

                    <!-- Office 365 Tenant ID -->
                    <div class="form-group">
                        <label for="office365_tenant_id">Tenant ID</label>
                        <input type="text" name="office365_tenant_id" id="office365_tenant_id" 
                               class="form-control" value="{{ $settings['office365_tenant_id'] ?? '' }}"
                               placeholder="Your Azure Directory (tenant) ID">
                        <p class="help-block">Found in Azure Portal → Azure Active Directory → Overview</p>
                    </div>

                    <!-- Office 365 Redirect URI -->
                    <div class="form-group">
                        <label for="office365_redirect_uri">Redirect URI</label>
                        <input type="url" name="office365_redirect_uri" id="office365_redirect_uri" 
                               class="form-control" value="{{ url('/admin/settings/office365/callback') }}"
                               readonly>
                        <p class="help-block">Use this in your Azure app configuration</p>
                    </div>

                    <!-- Calendar Selection -->
                    <div class="form-group" id="office365-calendar-selection" style="display: none;">
                        <label for="office365_selected_calendars">Select Calendars</label>
                        <div id="office365-calendars-list" class="checkbox-group">
                            <p class="text-muted">Loading calendars...</p>
                        </div>
                        <input type="hidden" name="office365_selected_calendars" id="office365_selected_calendars" value="{{ $settings['office365_selected_calendars'] ?? '' }}">
                        <p class="help-block">Choose which calendars to sync to your dashboard</p>
                    </div>

                    <!-- Test Connection -->
                    <div class="form-group">
                        <button type="button" class="btn btn-info btn-block" id="test-office365-btn">
                            <i class="fa fa-flash"></i> Test Connection
                        </button>
                        <p class="help-block">Test your Office 365 calendar connection</p>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="alert alert-info">
                        <h6><i class="fa fa-info-circle"></i> Office 365 Setup:</h6>
                        <ol>
                            <li>Create an app at <a href="https://portal.azure.com" target="_blank">Azure Portal</a></li>
                            <li>Go to App Registrations → New Registration</li>
                            <li>Set redirect URI to the value shown above</li>
                            <li>Copy Client ID and create a Client Secret</li>
                            <li>Grant Calendar permissions: Calendar.Read</li>
                            <li>Save settings and connect to authorize</li>
                        </ol>
                    </div>

                    <div class="alert alert-warning">
                        <h6><i class="fa fa-calendar-check-o"></i> Features:</h6>
                        <ul>
                            <li>View Office 365 calendar events in dashboard</li>
                            <li>Automatic token refresh</li>
                            <li>Support for all-day events</li>
                            <li>Event details and locations</li>
                            <li>Secure OAuth2 authentication</li>
                        </ul>
                    </div>

                    <!-- Connection Status -->
                    <div class="well" id="office365-status">
                        <h6><i class="fa fa-info-circle"></i> Connection Status</h6>
                        <p class="text-muted">Click "Test Connection" to check status</p>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- KashFlow Integration removed - migrated to Xero -->

    <!-- Save Button -->
    <div class="form-group">
        <button type="submit" class="btn btn-primary btn-lg">
            <i class="fa fa-save"></i> Save Integration Settings
        </button>
        <a href="{{ url('admin') }}" class="btn btn-default btn-lg">
            <i class="fa fa-arrow-left"></i> Back to Admin
        </a>
    </div>
                </form>
            </div>
        </div>
    </div>
</div>

@stop

@section('js')

<!-- 3CX module uses simplified polling integration -->

<script>
$(document).ready(function() {
    // Test Twilio connection functionality
    $('#test-twilio-connection-btn').click(function() {
        var sid = $('#twilio_sid').val();
        var token = $('#twilio_token').val();
        var from = $('#twilio_from').val();
        
        if (!sid || !token || !from) {
            alert('Please enter Account SID, Auth Token, and From Number before testing');
            return;
        }
        
        var btn = $(this);
        btn.prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i> Testing...');
        
        $.ajax({
            url: '/api/v1/twilio/config/test-credentials',
            method: 'POST',
            data: {
                twilio_sid: sid,
                twilio_token: token,
                twilio_from: from,
                _token: $('meta[name="csrf-token"]').attr('content')
            },
            success: function(response) {
                if (response.success && response.valid) {
                    alert('✅ Twilio connection test successful! Your credentials are valid.');
                    if (response.account_info) {
                        alert('Account Info: ' + JSON.stringify(response.account_info, null, 2));
                    }
                } else {
                    alert('❌ Connection test failed: ' + (response.error || 'Unknown error'));
                }
            },
            error: function(xhr) {
                var response = xhr.responseJSON;
                alert('❌ Test failed: ' + (response ? response.message : 'Network error. Check your settings and try again.'));
            },
            complete: function() {
                btn.prop('disabled', false).html('<i class="fa fa-flash"></i> Test Connection');
            }
        });
    });
    
    // Test TextMagic connection functionality
    $('#test-textmagic-connection-btn').click(function() {
        var username = $('#textmagic_username').val();
        var apiKey = $('#textmagic_api_key').val();

        if (!username || !apiKey) {
            alert('Please enter Username and API Key before testing');
            return;
        }

        var btn = $(this);
        btn.prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i> Testing...');

        $.ajax({
            url: '/api/v1/integrations/test-textmagic',
            method: 'POST',
            data: {
                textmagic_username: username,
                textmagic_api_key: apiKey,
                _token: $('meta[name="csrf-token"]').attr('content')
            },
            success: function(response) {
                if (response.success && response.valid) {
                    var msg = '✅ TextMagic connection test successful! Your credentials are valid.';
                    if (response.account_info) {
                        msg += '\n\nAccount: ' + (response.account_info.username || 'Unknown');
                        if (response.account_info.balance !== undefined) {
                            msg += '\nBalance: ' + response.account_info.balance;
                        }
                    }
                    alert(msg);
                } else {
                    alert('❌ Connection test failed: ' + (response.message || 'Unknown error'));
                }
            },
            error: function(xhr) {
                var response = xhr.responseJSON;
                alert('❌ Test failed: ' + (response ? response.message : 'Network error. Check your settings and try again.'));
            },
            complete: function() {
                btn.prop('disabled', false).html('<i class="fa fa-flash"></i> Test Connection');
            }
        });
    });

    // Test TextMagic SMS functionality
    $('#test-sms-textmagic-btn').click(function() {
        var phone = $('#test_phone_textmagic').val();
        var message = $('#test_message_textmagic').val();

        if (!phone || !message) {
            alert('Please enter both phone number and message');
            return;
        }

        var btn = $(this);
        btn.prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i> Sending...');

        $.ajax({
            url: '/api/v1/textmagic/send',
            method: 'POST',
            data: {
                send_to: phone,
                message: message,
                _token: $('meta[name="csrf-token"]').attr('content')
            },
            success: function(response) {
                if (response.success) {
                    alert('✅ Test SMS sent successfully via TextMagic!\nMessage ID: ' + (response.message_id || 'N/A') + '\nStatus: ' + (response.status || 'sent'));
                } else {
                    alert('❌ Failed to send SMS: ' + response.error);
                }
            },
            error: function(xhr) {
                var response = xhr.responseJSON;
                alert('❌ Error: ' + (response ? response.error : 'Unknown error'));
            },
            complete: function() {
                btn.prop('disabled', false).html('<i class="fa fa-paper-plane"></i> Send Test SMS');
            }
        });
    });

    // Test SMS functionality
    $('#test-sms-btn').click(function() {
        var phone = $('#test_phone').val();
        var message = $('#test_message').val();
        
        if (!phone || !message) {
            alert('Please enter both phone number and message');
            return;
        }
        
        var btn = $(this);
        btn.prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i> Sending...');
        
        $.ajax({
            url: '/api/v1/twilio/send',
            method: 'POST',
            data: {
                send_to: phone,
                message: message,
                _token: $('meta[name="csrf-token"]').attr('content')
            },
            success: function(response) {
                if (response.success) {
                    alert('✅ Test SMS sent successfully!\nMessage SID: ' + response.message_sid + '\nStatus: ' + response.status);
                } else {
                    alert('❌ Failed to send SMS: ' + response.error);
                }
            },
            error: function(xhr) {
                var response = xhr.responseJSON;
                alert('❌ Error: ' + (response ? response.error : 'Unknown error'));
            },
            complete: function() {
                btn.prop('disabled', false).html('<i class="fa fa-paper-plane"></i> Send Test SMS');
            }
        });
    });
    
    // Test phone system functionality
    $('#test-phone-btn').click(function() {
        var btn = $(this);
        btn.prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i> Testing...');
        
        $.ajax({
            url: '/api/v1/integrations/test-phone',
            method: 'POST',
            data: {
                _token: $('meta[name="csrf-token"]').attr('content')
            },
            success: function(response) {
                if (response.success) {
                    alert('Phone system connection successful!');
                } else {
                    alert('Connection failed: ' + response.message);
                }
            },
            error: function(xhr) {
                var response = xhr.responseJSON;
                alert('Error: ' + (response ? response.message : 'Unknown error'));
            },
            complete: function() {
                btn.prop('disabled', false).html('<i class="fa fa-phone"></i> Test Connection');
            }
        });
    });
    
    // Test 3CX system functionality
    $('#test-3cx-btn').click(function() {
        var btn = $(this);
        btn.prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i> Testing...');
        
        $.ajax({
            url: '/api/v1/integrations/test-3cx',
            method: 'POST',
            data: {
                _token: $('meta[name="csrf-token"]').attr('content')
            },
            success: function(response) {
                if (response.success) {
                    alert('✅ 3CX connection successful! ' + response.message);
                } else {
                    alert('❌ 3CX connection failed: ' + response.message);
                }
            },
            error: function(xhr) {
                var response = xhr.responseJSON;
                alert('❌ Error: ' + (response ? response.message : 'Unknown error'));
            },
            complete: function() {
                btn.prop('disabled', false).html('<i class="fa fa-phone"></i> Test 3CX Connection');
            }
        });
    });

    // Update display extension - use fixed laravelapp extension
    $('#display-extension').text('laravelapp');
    
    // Test 3CX call functionality - use ThreeCX Core with admin context
    $('#test-3cx-call-btn').click(function() {
        var toNumber = $('#test_to_number').val();
        
        if (!toNumber) {
            alert('Please enter a phone number');
            return;
        }
        
        ThreeCXCore.makeCall(toNumber);
    });

    // Xero integration functionality
    $('#test-xero-btn').click(function() {
        console.log('Xero test button clicked');
        var clientId = $('#xero_client_id').val();
        var clientSecret = $('#xero_client_secret').val();
        
        console.log('Client ID length:', clientId ? clientId.length : 0);
        console.log('Client Secret length:', clientSecret ? clientSecret.length : 0);
        
        if (!clientId || !clientSecret) {
            alert('Please enter both Client ID and Client Secret before testing');
            return;
        }
        
        var btn = $(this);
        btn.prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i> Testing...');
        
        // Simple validation test - just check if credentials are properly formatted
        if (clientId.length < 10 || clientSecret.length < 10) {
            alert('Client ID and Secret appear to be too short. Please check your Xero app configuration.');
            btn.prop('disabled', false).html('<i class="fa fa-flash"></i> Test Connection');
            return;
        }
        
        // Test the API endpoint
        console.log('Making AJAX call to test Xero credentials...');
        $.ajax({
            url: '/api/v1/integrations/test-xero',
            method: 'POST',
            data: {
                client_id: clientId,
                client_secret: clientSecret,
                _token: $('meta[name="csrf-token"]').attr('content')
            },
            success: function(response) {
                if (response && response.success) {
                    alert('✅ Xero configuration test successful! Your credentials appear to be valid.');
                } else if (response && response.needs_oauth) {
                    // Need OAuth authorization
                    if (confirm('🔐 Xero authorization required. Click OK to authorize the application with Xero.')) {
                        window.location.href = response.auth_url;
                    }
                } else {
                    alert('⚠️ Connection test completed but returned: ' + (response.message || 'Unknown status'));
                }
            },
            error: function(xhr, status, error) {
                console.error('Xero test error:', xhr, status, error);
                if (xhr.status === 401) {
                    alert('❌ Authentication failed. Please check your Client ID and Secret.');
                } else if (xhr.status === 404) {
                    alert('❌ API endpoint not found. Please save your settings first.');
                } else {
                    alert('❌ Test failed: ' + (error || 'Network error. Check your settings and try again.'));
                }
            },
            complete: function() {
                btn.prop('disabled', false).html('<i class="fa fa-flash"></i> Test Connection');
            }
        });
    });

    // Office 365 integration functionality
    
    // Auto-test after successful OAuth callback
    @if(session('auto_test_office365'))
    $(document).ready(function() {
        setTimeout(function() {
            $('#test-office365-btn').click();
        }, 1000);
    });
    @endif

    $('#test-office365-btn').click(function() {
        console.log('=== TEST CONNECTION BUTTON CLICKED ===');
        var btn = $(this);
        btn.prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i> Testing...');
        
        $.ajax({
            url: '/api/v1/integrations/test-office365',
            method: 'POST',
            data: {
                _token: $('meta[name="csrf-token"]').attr('content')
            },
            success: function(response) {
                console.log('Test connection button response:', response);
                if (response.success) {
                    $('#office365-status').html(
                        '<h6><i class="fa fa-check-circle text-success"></i> Connection Successful</h6>' +
                        '<p class="text-success">' + response.message + '</p>' +
                        (response.data ? '<pre class="small">' + JSON.stringify(response.data, null, 2) + '</pre>' : '')
                    );
                    
                    // Fetch and display calendars after successful connection
                    // If calendars are already in the response (nested in calendars_debug), use them directly
                    if (response.calendars_debug && response.calendars_debug.calendars) {
                        console.log('Test connection: calendars found in response, displaying...');
                        displayOffice365Calendars(response.calendars_debug.calendars);
                        $('#office365-calendar-selection').show();
                        console.log('Test connection: calendar selection should now be visible');
                    } else {
                        console.log('Test connection: no calendars in response, calling loadOffice365Calendars...');
                        loadOffice365Calendars();
                    }
                } else if (response.auto_redirect && response.redirect_url) {
                    // Automatic redirect to OAuth
                    $('#office365-status').html(
                        '<h6><i class="fa fa-spinner fa-spin text-info"></i> Redirecting to Microsoft</h6>' +
                        '<p class="text-info">' + response.message + '</p>'
                    );
                    
                    setTimeout(function() {
                        window.location.href = response.redirect_url;
                    }, 1000);
                } else if (response.auth_url || response.requires_auth) {
                    $('#office365-status').html(
                        '<h6><i class="fa fa-exclamation-triangle text-warning"></i> Authorization Required</h6>' +
                        '<p class="text-warning">' + response.message + '</p>' +
                        '<p><button class="btn btn-primary btn-sm" onclick="window.location.href=\'' + response.auth_url + '\'"><i class="fa fa-link"></i> Connect to Office 365</button></p>' +
                        '<p class="help-block small">You will be redirected to Microsoft to authorize access, then returned here automatically.</p>'
                    );
                } else {
                    $('#office365-status').html(
                        '<h6><i class="fa fa-exclamation-circle text-danger"></i> Test Failed</h6>' +
                        '<p class="text-danger">' + (response.message || 'Connection test failed') + '</p>'
                    );
                }
            },
            error: function(xhr) {
                var response = xhr.responseJSON;
                var errorMsg = response ? response.message : 'Network error occurred';
                $('#office365-status').html(
                    '<h6><i class="fa fa-times-circle text-danger"></i> Connection Error</h6>' +
                    '<p class="text-danger">' + errorMsg + '</p>'
                );
            },
            complete: function() {
                btn.prop('disabled', false).html('<i class="fa fa-flash"></i> Test Connection');
            }
        });
    });

    // KashFlow integration functionality removed - migrated to Xero
    
});

// Real-time call status polling - global scope with adaptive rates
var statusPollingInterval = null;
var currentPollingRate = 1000; // Start with 1 second
var lastStatusResponse = null;
var consecutiveStableStatus = 0;
var isRequestInProgress = false;

// Adaptive polling rates based on call state
var POLLING_RATES = {
    initiating: 800,    // Fast for initial states
    dialing: 1000,      // Medium for transitional states
    ringing: 1000,      // Medium for transitional states  
    connecting: 800,    // Fast for transitional states
    connected: 2000,    // Slow for stable states
    ended: 0,           // Stop polling
    failed: 0,          // Stop polling
    cancelled: 0,       // Stop polling
    completed: 0        // Stop polling
};
    
function startCallStatusPolling(participantId) {
        console.log('🔄 Starting adaptive call status polling for participant:', participantId);
        console.log('🔄 Participant ID type:', typeof participantId);
        console.log('🔄 Current statusPollingInterval:', statusPollingInterval);
        
        // Clear any existing interval
        if (statusPollingInterval) {
            console.log('🔄 Clearing existing polling interval');
            clearTimeout(statusPollingInterval);
            statusPollingInterval = null;
        }
        
        // Reset polling state
        currentPollingRate = 1000;
        consecutiveStableStatus = 0;
        isRequestInProgress = false;
        lastStatusResponse = null;
        
        // Start with initial polling rate
        console.log('🔄 Setting up adaptive polling interval (initial: 1000ms)');
        scheduleNextPoll(participantId);
        
        // Stop polling after 5 minutes max
        setTimeout(function() {
            if (statusPollingInterval) {
                clearTimeout(statusPollingInterval); // Use clearTimeout since we're using setTimeout
                statusPollingInterval = null;
                isRequestInProgress = false;
                $('#status-indicator').html('⏱️ Monitoring timeout reached');
                console.log('⏱️ Polling stopped due to 5-minute timeout');
            }
        }, 300000);
    }

function scheduleNextPoll(participantId) {
    statusPollingInterval = setTimeout(function() {
        pollCallStatus(participantId);
    }, currentPollingRate);
}

function pollCallStatus(participantId) {
    // Prevent multiple simultaneous requests
    if (isRequestInProgress) {
        console.log('⏭️ Skipping poll - request already in progress');
        scheduleNextPoll(participantId);
        return;
    }
    
    isRequestInProgress = true;
    console.log('🔄 Polling tick - checking status for participant:', participantId, 'rate:', currentPollingRate + 'ms');
    
    $.ajax({
        url: '/admin/integrations/threecx/call-status/' + participantId,
        method: 'GET',
        timeout: 15000, // 15 second timeout to prevent hanging requests
        success: function(statusResponse) {
            console.log('📊 Status polling response:', statusResponse);
            if (statusResponse.success && statusResponse.data) {
                console.log('📊 Status data:', statusResponse.data);
                
                var currentStatus = statusResponse.data.status.toLowerCase();
                console.log('📊 Current status for polling check:', currentStatus);
                
                // Check if status has changed
                var statusChanged = !lastStatusResponse || 
                    lastStatusResponse.status !== currentStatus;
                
                if (statusChanged) {
                    consecutiveStableStatus = 0;
                    console.log('🔄 Status changed to:', currentStatus);
                } else {
                    consecutiveStableStatus++;
                    console.log('🔄 Status stable for', consecutiveStableStatus, 'polls');
                }
                
                lastStatusResponse = statusResponse.data;
                updateCallStatusDisplay(statusResponse.data);
                
                // Update polling rate based on current status
                var newRate = POLLING_RATES[currentStatus] || 1500;
                
                // If status is stable for multiple polls, slow down even more
                if (consecutiveStableStatus >= 3 && currentStatus === 'connected') {
                    newRate = 3000; // Even slower for very stable connected state
                }
                
                currentPollingRate = newRate;
                
                // Check if we should stop polling
                if (['ended', 'failed', 'cancelled', 'completed'].includes(currentStatus)) {
                    console.log('⏹️ Call ended - stopping status polling');
                    $('#status-indicator').html('✅ Call monitoring completed');
                    statusPollingInterval = null;
                    isRequestInProgress = false;
                    return;
                } else {
                    console.log('🔄 Call still active, continuing polling at', newRate + 'ms intervals');
                    scheduleNextPoll(participantId);
                }
            } else {
                // Schedule next poll even if response was unsuccessful
                scheduleNextPoll(participantId);
            }
        },
        error: function(xhr, status, error) {
            console.log('❌ Status polling error:', error);
            console.log('❌ XHR Status:', xhr.status);
            console.log('❌ Response Text:', xhr.responseText);
            
            // Check if backend indicates call ended (404, 500 with call_ended flag)
            var responseData = null;
            try {
                responseData = JSON.parse(xhr.responseText);
            } catch(e) {
                // Ignore JSON parse errors
            }
            
            if (xhr.status === 404 || (responseData && responseData.call_ended)) {
                console.log('📞 Call ended - stopping polling (server indicated end)');
                showCallState('ended');
                $('#status-indicator').html('✅ Call monitoring completed');
                statusPollingInterval = null;
                isRequestInProgress = false;
                return;
            }
            
            // For other errors, continue polling but slow down
            currentPollingRate = Math.min(currentPollingRate * 1.5, 5000);
            console.log('⚠️ Error occurred, slowing down polling to:', currentPollingRate + 'ms');
            scheduleNextPoll(participantId);
        },
        complete: function() {
            isRequestInProgress = false;
        }
    });
}
    
    function showCallState(state, statusData = null) {
        console.log('🔄 State change requested:', state);
        console.log('🔄 Available call-state elements:', $('.call-state').length);
        console.log('🔄 call-init element exists:', $('#call-init').length > 0);
        console.log('🔄 call-dialing element exists:', $('#call-dialing').length > 0);
        console.log('🔄 call-init currently visible:', $('#call-init').is(':visible'));
        
        // Hide all call states immediately - no jumping animation
        $('.call-state').hide();
        console.log('🔄 Hiding all call-state elements immediately');
        
        // Show the specific state immediately - smooth icon animation only
        console.log('🔄 Executing state change to:', state);
        switch(state) {
            case 'init':
                console.log('🔄 Showing init state');
                $('#call-init').show();
                $('#call-init .modern-icon').addClass('pulse');
                break;
            case 'dialing':
                console.log('🔄 Showing dialing state');
                $('#call-dialing').show();
                $('#call-dialing .modern-icon').addClass('pulse');
                // Don't start timer yet - wait for connected state
                break;
            case 'ringing':
                console.log('🔄 Showing ringing state');
                $('#call-ringing').show();
                $('#call-ringing .modern-icon').addClass('ring-animation');
                break;
            case 'connected':
                console.log('🔄 Showing connected state');
                $('#call-connected').show();
                $('#call-connected .modern-icon').removeClass('pulse ring-animation').addClass('connected-glow');
                // Only start timer if not already running
                if (!callTimer) {
                    // Use backend connected_at timestamp for accurate timing
                    const connectedAt = statusData ? statusData.connected_at || null : null;
                    startCallTimer(connectedAt);
                }
                console.log('📞 Call Connected - Real-time UI update!');
                break;
            case 'ended':
                console.log('🔄 Showing ended state');
                $('#call-ended').show();
                $('.modern-icon').removeClass('pulse ring-animation connected-glow');
                stopCallTimer();
                
                // Call history is automatically logged server-side only for task calls (when task_id exists)
                // For admin test calls, no logging is needed - this is correct behavior
                
                // Stop polling when call ends
                if (statusPollingInterval) {
                    clearInterval(statusPollingInterval);
                    statusPollingInterval = null;
                    console.log('📞 Call ended - Polling stopped');
                }
                break;
            case 'error':
                console.log('🔄 Showing error state');
                $('#call-error').show();
                $('.modern-icon').removeClass('pulse ring-animation connected-glow');
                break;
        }
    }
    
    let callTimer = null;
    let callConnectedTime = null;
    
    function startCallTimer(connectedAt = null) {
        // Use backend connected_at timestamp if provided, otherwise use current time
        if (connectedAt) {
            callConnectedTime = new Date(connectedAt);
            console.log('⏱️ Starting timer with backend connected_at:', connectedAt);
        } else {
            callConnectedTime = new Date();
            console.log('⏱️ Starting timer with frontend time (fallback)');
        }
        
        callTimer = setInterval(function() {
            const elapsed = Math.floor((new Date() - callConnectedTime) / 1000);
            const minutes = Math.floor(elapsed / 60).toString().padStart(2, '0');
            const seconds = (elapsed % 60).toString().padStart(2, '0');
            $('#timer-display').text(minutes + ':' + seconds);
        }, 1000);
    }
    
    function stopCallTimer() {
        if (callTimer) {
            clearInterval(callTimer);
            if (callConnectedTime) {
                const elapsed = Math.floor((new Date() - callConnectedTime) / 1000);
                const minutes = Math.floor(elapsed / 60).toString().padStart(2, '0');
                const seconds = (elapsed % 60).toString().padStart(2, '0');
                $('#final-duration').text('Duration: ' + minutes + ':' + seconds);
            } else {
                $('#final-duration').text('Duration: --:--');
            }
            callTimer = null;
            callConnectedTime = null;
        }
    }
    
    function updateCallStatusDisplay(statusData) {
        let status = (statusData.status || 'Unknown').toLowerCase();
        console.log('🔄 Processing status update:', status);
        console.log('🔄 Full status data:', statusData);
        
        // Map 3CX statuses to our UI states
        if (status === 'dialing') {
            showCallState('dialing', statusData);
        } else if (status === 'ringing') {
            showCallState('ringing', statusData); 
        } else if (status === 'connected' || status === 'talking') {
            showCallState('connected', statusData);
        } else if (['ended', 'completed', 'failed', 'cancelled', 'busy', 'unknown'].includes(status)) {
            showCallState('ended', statusData);
        }
        
        console.log('Call status updated to:', status);
    }

// Hang up call function
function hangUpCall() {
    if (window.currentCall && window.currentCall.participantId) {
        console.log('🔴 End Call button clicked', {
            participant_id: window.currentCall.participantId,
            call_id: window.currentCall.callId
        });
        
        $.ajax({
            url: '/admin/integrations/threecx/hangup-call',
            method: 'POST',
            data: {
                participant_id: window.currentCall.participantId,
                _token: $('meta[name="csrf-token"]').attr('content')
            },
            success: function(response) {
                console.log('🔴 Hangup API success:', response);
                showCallState('ended');
            },
            error: function(xhr) {
                console.log('🔴 Hangup API failed:', xhr.status, xhr.responseText);
                console.log('🔴 Showing ended state anyway');
                showCallState('ended');
            }
        });
    } else {
        showCallState('ended');
    }
}

// Call history is now automatically logged server-side - no complex frontend logic needed!

// Clean up polling when modal is closed
$(document).on('hidden.bs.modal', '#admin-3cx-modal', function() {
    if (statusPollingInterval) {
        clearTimeout(statusPollingInterval); // Use clearTimeout since we're using setTimeout
        statusPollingInterval = null;
        isRequestInProgress = false;
        console.log('Call status polling stopped');
    }
    
    // Re-enable test button and input when modal is closed, remove processing class
    $('#test-3cx-call-btn').prop('disabled', false).removeClass('processing').html('<i class="fa fa-phone"></i> Make Test Call');
    $('#test_to_number').prop('disabled', false);
    
    // Clear current call data
    window.currentCall = null;
});

// Office 365 calendar management functions
function loadOffice365Calendars() {
    $('#office365-calendars-list').html('<p class="text-muted"><i class="fa fa-spinner fa-spin"></i> Loading calendars...</p>');
    $('#office365-calendar-selection').show();
    
    $.post('/{{ Config::get('app.api_path') }}/integrations/test-office365', {
        _token: $('meta[name="csrf-token"]').attr('content'),
        action: 'get_calendars'
    })
    .done(function(response) {
        if (response.success && response.calendars) {
            displayOffice365Calendars(response.calendars);
        } else {
            $('#office365-calendars-list').html('<p class="text-danger"><i class="fa fa-exclamation-triangle"></i> ' + (response.message || 'Failed to load calendars') + '</p>');
        }
    })
    .fail(function(xhr) {
        console.error('Failed to load Office365 calendars:', xhr);
        $('#office365-calendars-list').html('<p class="text-danger"><i class="fa fa-exclamation-triangle"></i> Error loading calendars. Please check your connection.</p>');
    });
}

function displayOffice365Calendars(calendars) {
    var selectedCalendars = $('#office365_selected_calendars').val();
    var selectedArray = selectedCalendars ? selectedCalendars.split(',') : [];
    
    var html = '';
    calendars.forEach(function(calendar) {
        var isChecked = selectedArray.includes(calendar.id) ? 'checked' : '';
        var isDefault = calendar.isDefaultCalendar ? '<small class="text-muted">(Default)</small>' : '';
        
        html += '<div class="checkbox">' +
                '<label>' +
                '<input type="checkbox" value="' + calendar.id + '" ' + isChecked + ' onchange="updateSelectedCalendars()"> ' +
                calendar.name + ' ' + isDefault +
                '</label>' +
                '</div>';
    });
    
    $('#office365-calendars-list').html(html);
}

function updateSelectedCalendars() {
    var selected = [];
    $('#office365-calendars-list input[type="checkbox"]:checked').each(function() {
        selected.push($(this).val());
    });
    $('#office365_selected_calendars').val(selected.join(','));
}

// Load calendars on page load if already connected
$(document).ready(function() {
    console.log('=== OFFICE 365 DEBUG START ===');
    console.log('Page loaded, checking Office 365 status...');
    console.log('jQuery version:', $.fn.jquery);
    console.log('office365_enabled checkbox exists:', $('input[name="office365_enabled"]').length > 0);
    console.log('office365_enabled is checked:', $('input[name="office365_enabled"]').is(':checked'));
    
    // Check if Office 365 is enabled and try to load calendars
    if ($('input[name="office365_enabled"]').is(':checked')) {
        console.log('Office 365 is enabled, testing connection...');
        
        // First test if we have a valid connection
        $.post('/{{ Config::get('app.api_path') }}/integrations/test-office365', {
            _token: $('meta[name="csrf-token"]').attr('content')
        })
        .done(function(response) {
            console.log('Test connection response:', response);
            
            if (response.success && response.calendars_debug && response.calendars_debug.calendars) {
                console.log('Connection successful with calendars, displaying...');
                
                // Update status display
                $('#office365-status').html(
                    '<h6><i class="fa fa-check text-success"></i> Connection Successful</h6>' +
                    '<p class="text-success">' + response.message + '</p>'
                );
                
                // Connection successful, show calendars
                displayOffice365Calendars(response.calendars_debug.calendars);
                $('#office365-calendar-selection').show();
            } else if (response.success) {
                console.log('Connection successful but no calendars in response, trying separate call...');
                
                // Update status display
                $('#office365-status').html(
                    '<h6><i class="fa fa-check text-success"></i> Connection Successful</h6>' +
                    '<p class="text-success">' + response.message + '</p>'
                );
                
                // Connected but no calendars in response, try separate call
                loadOffice365Calendars();
            } else {
                console.log('Connection test failed:', response.message);
            }
        })
        .fail(function(xhr, status, error) {
            console.log('Connection test request failed:', error);
            // Connection failed, calendars section stays hidden
        });
    } else {
        console.log('Office 365 is not enabled');
    }
});
</script>

@endsection
