@extends('templates.admin.layout')

@section('header')
    <div class="row">
        <div class="col-xs-12">
            <div class="page-header">
                <h1>
                    <i class="fa fa-cloud"></i> Xero Integration Management
                    <small>Direct API Connection</small>
                </h1>
            </div>
        </div>
    </div>
@endsection

@section('content')
<div class="row">
    <div class="col-md-8">
        <div class="widget-box">
            <div class="widget-header">
                <h4 class="widget-title">
                    <i class="fa fa-link"></i>
                    Connection Status
                </h4>
            </div>
            <div class="widget-body">
                <div class="widget-main">
                    @if($connectionStatus['connected'])
                        <div class="alert alert-success">
                            <i class="fa fa-check"></i>
                            <strong>Connected to Xero!</strong>
                            <br>
                            <strong>Organization:</strong> {{ $connectionStatus['tenant_name'] ?? 'Unknown' }}
                            <br>
                            <strong>Connected:</strong> {{ $connectionStatus['connected_at']->format('d/m/Y H:i') ?? 'Unknown' }}
                            <br>
                            <strong>Token Expires:</strong> {{ $connectionStatus['expires_at']->format('d/m/Y H:i') ?? 'Unknown' }}
                        </div>
                        
                        <div class="btn-group">
                            <button type="button" class="btn btn-warning" onclick="testConnection()">
                                <i class="fa fa-flash"></i> Test Connection
                            </button>
                            <button type="button" class="btn btn-danger" onclick="disconnectXero()">
                                <i class="fa fa-unlink"></i> Disconnect
                            </button>
                        </div>
                    @else
                        <div class="alert alert-warning">
                            <i class="fa fa-exclamation-triangle"></i>
                            <strong>Not connected to Xero</strong>
                            <br>
                            @if(isset($connectionStatus['error']))
                                Error: {{ $connectionStatus['error'] }}
                            @else
                                Click the button below to connect to your Xero organization.
                            @endif
                        </div>
                        
                        <button type="button" class="btn btn-success btn-lg" onclick="connectToXero()">
                            <i class="fa fa-link"></i> Connect to Xero
                        </button>
                    @endif
                </div>
            </div>
        </div>
    </div>
    
    <div class="col-md-4">
        <div class="widget-box">
            <div class="widget-header">
                <h4 class="widget-title">
                    <i class="fa fa-info-circle"></i>
                    Integration Details
                </h4>
            </div>
            <div class="widget-body">
                <div class="widget-main">
                    <h5>Direct Integration</h5>
                    <p>This module provides direct integration with Xero using OAuth2, replacing the previous microservice architecture.</p>
                    
                    <h5>Features</h5>
                    <ul>
                        <li>Direct API calls to Xero</li>
                        <li>OAuth2 authentication</li>
                        <li>Automatic token refresh</li>
                        <li>Chart of accounts sync</li>
                        <li>Invoice creation</li>
                        <li>Purchase order sync</li>
                    </ul>
                    
                    <h5>Environment</h5>
                    <p>
                        <strong>Mode:</strong> 
                        @if(config('xero.sandbox'))
                            <span class="label label-warning">Sandbox</span>
                        @else
                            <span class="label label-success">Production</span>
                        @endif
                    </p>
                </div>
            </div>
        </div>
        
        <div class="widget-box">
            <div class="widget-header">
                <h4 class="widget-title">
                    <i class="fa fa-cogs"></i>
                    Quick Actions
                </h4>
            </div>
            <div class="widget-body">
                <div class="widget-main">
                    <div class="btn-group-vertical btn-block">
                        <button type="button" class="btn btn-info" onclick="checkStatus()">
                            <i class="fa fa-refresh"></i> Refresh Status
                        </button>
                        <a href="/api/v1/xero/test-connection" target="_blank" class="btn btn-default">
                            <i class="fa fa-external-link"></i> API Test
                        </a>
                        <button type="button" class="btn btn-default" onclick="clearCache()">
                            <i class="fa fa-trash"></i> Clear Cache
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Status Display -->
<div id="status-messages"></div>

@endsection

@section('scripts')
<script>
function connectToXero() {
    // Get authorization URL and redirect
    fetch('/api/v1/xero/auth', {
        method: 'GET',
        headers: {
            'Accept': 'application/json',            
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            window.location.href = data.auth_url;
        } else {
            showAlert('error', 'Failed to initiate Xero connection: ' + data.message);
        }
    })
    .catch(error => {
        showAlert('error', 'Connection error: ' + error.message);
    });
}

function disconnectXero() {
    if (!confirm('Are you sure you want to disconnect from Xero? This will revoke access tokens.')) {
        return;
    }
    
    fetch('/api/v1/xero/disconnect', {
        method: 'DELETE',
        headers: {
            'Accept': 'application/json',            
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showAlert('success', 'Successfully disconnected from Xero');
            setTimeout(() => location.reload(), 2000);
        } else {
            showAlert('error', 'Failed to disconnect: ' + data.message);
        }
    })
    .catch(error => {
        showAlert('error', 'Disconnect error: ' + error.message);
    });
}

function testConnection() {
    showAlert('info', 'Testing Xero connection...');
    
    fetch('/api/v1/xero/test-connection', {
        method: 'GET',
        headers: {
            'Accept': 'application/json',            
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success && data.connected) {
            showAlert('success', 'Xero connection test successful!');
        } else {
            showAlert('error', 'Connection test failed: ' + (data.message || 'Unknown error'));
        }
    })
    .catch(error => {
        showAlert('error', 'Test error: ' + error.message);
    });
}

function checkStatus() {
    showAlert('info', 'Checking connection status...');
    
    fetch('/api/v1/xero/status', {
        method: 'GET',
        headers: {
            'Accept': 'application/json',            
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showAlert('info', 'Status refreshed');
            setTimeout(() => location.reload(), 1000);
        } else {
            showAlert('error', 'Failed to check status: ' + data.message);
        }
    })
    .catch(error => {
        showAlert('error', 'Status check error: ' + error.message);
    });
}

function clearCache() {
    showAlert('info', 'Clearing Xero cache...');
    
    // This would need a dedicated endpoint
    fetch('/api/v1/xero/clear-cache', {
        method: 'POST',
        headers: {
            'Accept': 'application/json',            
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showAlert('success', 'Cache cleared successfully');
        } else {
            showAlert('error', 'Failed to clear cache: ' + data.message);
        }
    })
    .catch(error => {
        showAlert('warning', 'Cache clear not implemented yet');
    });
}

function showAlert(type, message) {
    const alertClass = type === 'success' ? 'alert-success' : 
                      type === 'error' ? 'alert-danger' : 
                      type === 'warning' ? 'alert-warning' : 'alert-info';
    
    const alertHtml = `
        <div class="alert ${alertClass} alert-dismissible">
            <button type="button" class="close" data-dismiss="alert">&times;</button>
            ${message}
        </div>
    `;
    
    document.getElementById('status-messages').innerHTML = alertHtml;
    
    // Auto-dismiss after 5 seconds
    setTimeout(() => {
        const alert = document.querySelector('#status-messages .alert');
        if (alert) {
            alert.remove();
        }
    }, 5000);
}

// Check for success/error messages from redirect
@if(session('success'))
    showAlert('success', '{{ session('success') }}');
@endif

@if(session('error'))
    showAlert('error', '{{ session('error') }}');
@endif
</script>
@endsection 