<?php
// smart_connection_test.php
session_start();
require_once 'layouts/dbconn.php';

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}
?>

<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'SMART API Connection Test')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
    
    <style>
        .test-status {
            padding: 15px 20px;
            border-radius: 8px;
            font-weight: 500;
            animation: slideDown 0.3s ease-out;
            margin-bottom: 1.5rem;
        }

        .test-status.success {
            background-color: #d1fae5;
            color: #065f46;
            border: 1px solid #34d399;
        }

        .test-status.error {
            background-color: #fee2e2;
            color: #991b1b;
            border: 1px solid #f87171;
        }

        .test-status i {
            font-size: 1.2em;
            vertical-align: middle;
        }

        @keyframes slideDown {
            from {
                opacity: 0;
                transform: translateY(-10px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .info-card {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            margin-bottom: 1.5rem;
        }

        .info-card h5 {
            font-size: 1.125rem;
            font-weight: 600;
            color: #1e293b;
            margin-bottom: 1.25rem;
            padding-bottom: 0.75rem;
            border-bottom: 2px solid #e2e8f0;
        }

        .config-table {
            width: 100%;
        }

        .config-table td {
            padding: 0.75rem 0;
            border-bottom: 1px solid #f1f5f9;
        }

        .config-table td:first-child {
            color: #64748b;
            font-weight: 500;
            width: 180px;
        }

        .config-table td:last-child {
            color: #1e293b;
        }

        .config-table tr:last-child td {
            border-bottom: none;
        }

        .checklist-item {
            padding: 1rem;
            background: #f8fafc;
            border-radius: 8px;
            margin-bottom: 0.75rem;
            border-left: 4px solid #e2e8f0;
            transition: all 0.2s;
        }

        .checklist-item.completed {
            background: #d1fae5;
            border-left-color: #059669;
        }

        .checklist-item .check-icon {
            width: 24px;
            height: 24px;
            border: 2px solid #cbd5e1;
            border-radius: 50%;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            margin-right: 0.75rem;
            transition: all 0.2s;
        }

        .checklist-item.completed .check-icon {
            background: #059669;
            border-color: #059669;
            color: white;
        }

        .details-table {
            width: 100%;
            font-size: 0.9rem;
        }

        .details-table td {
            padding: 0.75rem 0;
            border-bottom: 1px solid #f1f5f9;
        }

        .details-table td:first-child {
            font-weight: 600;
            color: #64748b;
            width: 180px;
        }

        .details-table td:last-child {
            color: #1e293b;
        }

        .details-table tr:last-child td {
            border-bottom: none;
        }

        .badge-custom {
            padding: 0.35em 0.65em;
            font-size: 0.85rem;
            border-radius: 6px;
            font-weight: 500;
        }

        .btn-test {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 0.75rem 2rem;
            border: none;
            border-radius: 8px;
            font-weight: 500;
            font-size: 1rem;
            cursor: pointer;
            transition: all 0.2s;
        }

        .btn-test:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
        }

        .btn-test:disabled {
            opacity: 0.6;
            cursor: not-allowed;
            transform: none;
        }

        .alert-info-custom {
            background: #dbeafe;
            border-left: 4px solid #3b82f6;
            padding: 1rem 1.25rem;
            border-radius: 8px;
            margin-bottom: 1.5rem;
        }

        .alert-info-custom i {
            color: #3b82f6;
            font-size: 1.1rem;
            margin-right: 0.5rem;
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>

        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <!-- Page Title -->
                    <div class="row">
                        <div class="col-12">
                            <div class="page-title-box d-sm-flex align-items-center justify-content-between">
                                <h4 class="mb-sm-0">SMART Health Systems API Connection Test</h4>
                                <div class="page-title-right">
                                    <ol class="breadcrumb m-0">
                                        <li class="breadcrumb-item"><a href="index.php">Dashboard</a></li>
                                        <li class="breadcrumb-item"><a href="system_settings.php">Settings</a></li>
                                        <li class="breadcrumb-item active">SMART Connection Test</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-lg-8 mx-auto">
                            <!-- Info Alert -->
                            <div class="alert-info-custom">
                                <i class="ri-information-line"></i>
                                <strong>About this test:</strong> This will verify the connection to SMART Health Systems API by attempting to generate an OAuth2 bearer token using your configured credentials.
                            </div>

                            <!-- Configuration Info -->
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="info-card">
                                        <h5><i class="ri-settings-3-line me-2"></i>Configuration</h5>
                                        <table class="config-table">
                                            <tr>
                                                <td>Endpoint:</td>
                                                <td><span class="badge bg-primary badge-custom">Development</span></td>
                                            </tr>
                                            <tr>
                                                <td>Base URL:</td>
                                                <td><small class="text-muted">data.smartapplicationsgroup.com</small></td>
                                            </tr>
                                            <tr>
                                                <td>Auth Type:</td>
                                                <td>OAuth2 Bearer Token</td>
                                            </tr>
                                            <tr>
                                                <td>API Version:</td>
                                                <td>January 2025 V2</td>
                                            </tr>
                                        </table>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="info-card">
                                        <h5><i class="ri-shield-check-line me-2"></i>Credentials Status</h5>
                                        <table class="config-table">
                                            <tr>
                                                <td>Provider Key:</td>
                                                <td><span class="badge bg-success badge-custom">Configured</span></td>
                                            </tr>
                                            <tr>
                                                <td>Username:</td>
                                                <td><span class="badge bg-success badge-custom">Configured</span></td>
                                            </tr>
                                            <tr>
                                                <td>Password:</td>
                                                <td><span class="badge bg-success badge-custom">Configured</span></td>
                                            </tr>
                                            <tr>
                                                <td>Status:</td>
                                                <td><span class="badge bg-warning badge-custom">Not Tested</span></td>
                                            </tr>
                                        </table>
                                    </div>
                                </div>
                            </div>

                            <!-- Test Button -->
                            <div class="info-card text-center">
                                <button type="button" class="btn-test" onclick="testSmartConnection()">
                                    <i class="ri-flask-line me-2"></i>Run Connection Test
                                </button>
                            </div>

                            <!-- Status Display -->
                            <div id="smartStatus" style="display: none;"></div>

                            <!-- Details Display -->
                            <div id="testDetails" style="display: none;" class="info-card">
                                <h5><i class="ri-file-list-3-line me-2"></i>Test Details</h5>
                                <div id="detailsContent"></div>
                            </div>

                            <!-- Integration Checklist -->
                            <div class="info-card">
                                <h5><i class="ri-list-check-2 me-2"></i>Integration Checklist</h5>
                                <div id="checklist">
                                    <div class="checklist-item" id="check1">
                                        <span class="check-icon">
                                            <i class="ri-check-line" style="display: none;"></i>
                                        </span>
                                        <strong>OAuth2 Token Generation</strong>
                                        <small class="d-block text-muted ms-5">Verify bearer token can be generated successfully</small>
                                    </div>
                                    <div class="checklist-item" id="check2">
                                        <span class="check-icon">
                                            <i class="ri-check-line" style="display: none;"></i>
                                        </span>
                                        <strong>Provider Key Validation</strong>
                                        <small class="d-block text-muted ms-5">Ensure provider-key header is accepted</small>
                                    </div>
                                    <div class="checklist-item" id="check3">
                                        <span class="check-icon">
                                            <i class="ri-check-line" style="display: none;"></i>
                                        </span>
                                        <strong>Credentials Authentication</strong>
                                        <small class="d-block text-muted ms-5">Verify username and password authentication</small>
                                    </div>
                                    <div class="checklist-item" id="check4">
                                        <span class="check-icon">
                                            <i class="ri-check-line" style="display: none;"></i>
                                        </span>
                                        <strong>API Response Format</strong>
                                        <small class="d-block text-muted ms-5">Confirm response includes access_token and expires_in</small>
                                    </div>
                                </div>
                            </div>

                            <!-- Documentation -->
                            <div class="info-card text-center">
                                <p class="text-muted mb-0">
                                    <i class="ri-book-2-line me-2"></i>
                                    For more information, refer to the SMART Health Systems API Documentation
                                </p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
    
    <script>
    function testSmartConnection() {
        const btn = event.target;
        const originalText = btn.innerHTML;
        btn.disabled = true;
        btn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Testing Connection...';
        
        // Hide previous results
        document.getElementById('smartStatus').style.display = 'none';
        document.getElementById('testDetails').style.display = 'none';
        
        // Reset checklist
        for (let i = 1; i <= 4; i++) {
            const item = document.getElementById('check' + i);
            item.classList.remove('completed');
            item.querySelector('.ri-check-line').style.display = 'none';
        }
        
        fetch('smart_connection_test_handler.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: 'action=test_connection'
        })
        .then(response => response.json())
        .then(data => {
            const statusDiv = document.getElementById('smartStatus');
            const detailsDiv = document.getElementById('testDetails');
            const detailsContent = document.getElementById('detailsContent');
            
            statusDiv.style.display = 'block';
            
            if (data.success) {
                statusDiv.className = 'test-status success';
                statusDiv.innerHTML = '<i class="ri-checkbox-circle-line me-2"></i>' + data.message;
                
                // Update checklist
                for (let i = 1; i <= 4; i++) {
                    const item = document.getElementById('check' + i);
                    item.classList.add('completed');
                    item.querySelector('.ri-check-line').style.display = 'inline';
                }
                
                // Show details
                detailsDiv.style.display = 'block';
                detailsContent.innerHTML = `
                    <table class="details-table">
                        <tr>
                            <td>HTTP Status Code:</td>
                            <td><span class="badge bg-success badge-custom">${data.details.http_code}</span></td>
                        </tr>
                        <tr>
                            <td>Token Type:</td>
                            <td>${data.details.token_type}</td>
                        </tr>
                        <tr>
                            <td>Token Preview:</td>
                            <td><code>${data.details.token_preview}</code></td>
                        </tr>
                        <tr>
                            <td>Expires In:</td>
                            <td>${data.details.expires_in} seconds</td>
                        </tr>
                        <tr>
                            <td>Timestamp:</td>
                            <td>${data.details.timestamp}</td>
                        </tr>
                    </table>
                `;
                
                Swal.fire({
                    icon: 'success',
                    title: 'Connection Successful!',
                    html: `
                        <p class="mb-2">Successfully connected to SMART Health Systems API</p>
                        <div class="text-start mt-3">
                            <small class="text-muted">
                                <i class="ri-check-line text-success me-1"></i> OAuth2 token generated<br>
                                <i class="ri-check-line text-success me-1"></i> Authentication successful<br>
                                <i class="ri-check-line text-success me-1"></i> API is accessible
                            </small>
                        </div>
                    `,
                    confirmButtonColor: '#059669'
                });
            } else {
                statusDiv.className = 'test-status error';
                statusDiv.innerHTML = '<i class="ri-error-warning-line me-2"></i>' + data.message;
                
                // Show error details
                if (data.details) {
                    detailsDiv.style.display = 'block';
                    let detailsHtml = '<table class="details-table">';
                    
                    if (data.details.http_code) {
                        detailsHtml += `
                            <tr>
                                <td>HTTP Status Code:</td>
                                <td><span class="badge bg-danger badge-custom">${data.details.http_code}</span></td>
                            </tr>
                        `;
                    }
                    
                    if (data.details.error) {
                        detailsHtml += `
                            <tr>
                                <td>Error:</td>
                                <td>${data.details.error}</td>
                            </tr>
                        `;
                    }
                    
                    if (data.details.error_description) {
                        detailsHtml += `
                            <tr>
                                <td>Description:</td>
                                <td>${data.details.error_description}</td>
                            </tr>
                        `;
                    }
                    
                    if (data.details.error_type) {
                        detailsHtml += `
                            <tr>
                                <td>Error Type:</td>
                                <td><span class="badge bg-warning text-dark badge-custom">${data.details.error_type}</span></td>
                            </tr>
                        `;
                    }
                    
                    detailsHtml += '</table>';
                    detailsContent.innerHTML = detailsHtml;
                }
                
                // Determine which checks failed
                if (data.details.http_code === 401) {
                    document.getElementById('check1').classList.add('completed');
                    document.getElementById('check1').querySelector('.ri-check-line').style.display = 'inline';
                } else if (data.details.error_type === 'CURL_ERROR') {
                    // Network issue - none complete
                }
                
                Swal.fire({
                    icon: 'error',
                    title: 'Connection Failed',
                    html: `<p>${data.message}</p>`,
                    footer: '<small>Check your credentials and network connection</small>'
                });
            }
            
            btn.disabled = false;
            btn.innerHTML = originalText;
        })
        .catch(error => {
            const statusDiv = document.getElementById('smartStatus');
            statusDiv.style.display = 'block';
            statusDiv.className = 'test-status error';
            statusDiv.innerHTML = '<i class="ri-error-warning-line me-2"></i>Connection test failed: ' + error.message;
            
            Swal.fire({
                icon: 'error',
                title: 'Connection Error',
                text: 'Failed to connect to SMART API: ' + error.message
            });
            
            btn.disabled = false;
            btn.innerHTML = originalText;
        });
    }
    </script>

    <script src="assets/js/app.js"></script>
</body>
</html>