<?php
/**
 * Debug Login Page - Use this to troubleshoot login issues
 * File: auth/login-debug.php
 */
define('AIMS_ACCESS', true);
require_once '../config/config.php';

$pageTitle = 'Debug Login - AIMS';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $pageTitle; ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body {
            padding: 20px;
            font-family: monospace;
        }
        .debug-box {
            background: #f8f9fa;
            border: 1px solid #dee2e6;
            border-radius: 5px;
            padding: 15px;
            margin-bottom: 20px;
        }
        .success { color: #28a745; }
        .error { color: #dc3545; }
        .info { color: #17a2b8; }
    </style>
</head>
<body>
    <div class="container">
        <h1>Login Debug Tool</h1>
        
        <div class="debug-box">
            <h5>Test Admin Login</h5>
            <form id="loginForm">
                <div class="mb-3">
                    <label>Phone Number:</label>
                    <input type="text" class="form-control" id="phone" value="+256787842061">
                </div>
                <div class="mb-3">
                    <label>Password:</label>
                    <input type="password" class="form-control" id="password" value="admin123">
                </div>
                <button type="submit" class="btn btn-primary">Test Login</button>
            </form>
        </div>
        
        <div class="debug-box">
            <h5>Debug Output:</h5>
            <div id="debugOutput" style="white-space: pre-wrap;"></div>
        </div>
        
        <div class="debug-box">
            <h5>Response Data:</h5>
            <pre id="responseData"></pre>
        </div>
    </div>

    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
    <script>
        const APP_URL = '<?php echo APP_URL; ?>';
        
        function log(message, type = 'info') {
            const colors = { success: '#28a745', error: '#dc3545', info: '#17a2b8' };
            const output = $('#debugOutput');
            const timestamp = new Date().toLocaleTimeString();
            output.append(`<span style="color: ${colors[type]}">[${timestamp}] ${message}</span>\n`);
        }
        
        $('#loginForm').submit(function(e) {
            e.preventDefault();
            
            $('#debugOutput').empty();
            $('#responseData').empty();
            
            const phone = $('#phone').val();
            const password = $('#password').val();
            
            log('Starting login test...', 'info');
            log('Phone: ' + phone, 'info');
            log('Password: ' + password.replace(/./g, '*'), 'info');
            log('API URL: ' + APP_URL + '/api/auth.php', 'info');
            
            const formData = {
                action: 'login',
                phone: phone,
                password: password
            };
            
            log('Sending request...', 'info');
            
            $.ajax({
                url: APP_URL + '/api/auth.php',
                method: 'POST',
                data: formData,
                dataType: 'json',
                success: function(response) {
                    log('✓ Request successful!', 'success');
                    log('Response received:', 'success');
                    $('#responseData').text(JSON.stringify(response, null, 2));
                    
                    if (response.success) {
                        log('✓ Login successful!', 'success');
                        log('User Type: ' + response.user_type, 'success');
                        log('Redirect: ' + response.redirect, 'success');
                        
                        setTimeout(() => {
                            log('Redirecting in 2 seconds...', 'info');
                            setTimeout(() => {
                                window.location.href = response.redirect;
                            }, 2000);
                        }, 1000);
                    } else {
                        log('✗ Login failed: ' + response.message, 'error');
                    }
                },
                error: function(xhr, status, error) {
                    log('✗ Request failed!', 'error');
                    log('Status: ' + status, 'error');
                    log('Error: ' + error, 'error');
                    log('HTTP Status: ' + xhr.status, 'error');
                    
                    $('#responseData').text(
                        'Status: ' + xhr.status + '\n' +
                        'Status Text: ' + xhr.statusText + '\n' +
                        'Response Text:\n' + xhr.responseText
                    );
                    
                    if (xhr.responseJSON) {
                        log('JSON Response: ' + JSON.stringify(xhr.responseJSON), 'error');
                    }
                    
                    // Common issues
                    if (xhr.status === 0) {
                        log('⚠ Network error - Check if API file exists and is accessible', 'error');
                    } else if (xhr.status === 404) {
                        log('⚠ API endpoint not found - Check path: ' + APP_URL + '/api/auth.php', 'error');
                    } else if (xhr.status === 500) {
                        log('⚠ Server error - Check PHP error logs', 'error');
                    }
                }
            });
        });
        
        // Auto-submit on page load for quick testing
        log('Page loaded. Ready to test.', 'info');
    </script>
</body>
</html>