<?php
include 'config.php';
include 'auth.php';
checkAuth();
$user = getCurrentUser();

// Get server and session information
$server_info = [
    'PHP_VERSION' => PHP_VERSION,
    'SERVER_SOFTWARE' => $_SERVER['SERVER_SOFTWARE'] ?? 'Unknown',
    'HTTP_HOST' => $_SERVER['HTTP_HOST'] ?? 'Unknown',
    'REQUEST_URI' => $_SERVER['REQUEST_URI'] ?? 'Unknown',
    'HTTPS' => isset($_SERVER['HTTPS']) ? 'Yes' : 'No',
    'USER_AGENT' => $_SERVER['HTTP_USER_AGENT'] ?? 'Unknown'
];

$session_info = [
    'user_id' => $_SESSION['user_id'] ?? 'Not set',
    'username' => $_SESSION['username'] ?? 'Not set', 
    'role' => $_SESSION['role'] ?? 'Not set',
    'session_id' => session_id()
];
?>
<!DOCTYPE html>
<html>
<head>
    <title>🔧 Complete System Diagnostic</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet" crossorigin="anonymous">
    
    <!-- Font Awesome CSS - Multiple Sources -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet" crossorigin="anonymous">
    <link href="https://use.fontawesome.com/releases/v6.4.0/css/all.css" rel="stylesheet" crossorigin="anonymous">
    
    <!-- Backup Font Awesome -->
    <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
    
    <style>
        body { 
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); 
            color: white; 
            padding: 20px; 
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }
        .diagnostic-card { 
            background: rgba(255,255,255,0.1); 
            padding: 20px; 
            margin: 15px 0; 
            border-radius: 15px; 
            backdrop-filter: blur(10px);
            border: 1px solid rgba(255,255,255,0.2);
        }
        .status-ok { color: #28a745; font-weight: bold; }
        .status-error { color: #dc3545; font-weight: bold; }
        .status-warning { color: #ffc107; font-weight: bold; }
        .icon-test { font-size: 2rem; margin: 10px; display: inline-block; }
        .code-block { background: rgba(0,0,0,0.3); padding: 15px; border-radius: 8px; font-family: monospace; }
        .test-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 15px; }
        .test-item { text-align: center; padding: 15px; background: rgba(255,255,255,0.05); border-radius: 8px; }
    </style>
</head>
<body>
    <div class="container-fluid">
        <h1>🔧 COMPLETE SYSTEM DIAGNOSTIC</h1>
        <p class="lead">Comprehensive check for icon loading issues after login</p>
        
        <!-- Session Status -->
        <div class="diagnostic-card">
            <h3>👤 Authentication Status</h3>
            <div class="row">
                <div class="col-md-6">
                    <h5>Session Information:</h5>
                    <?php foreach($session_info as $key => $value): ?>
                        <p><strong><?= $key ?>:</strong> 
                            <span class="<?= $value !== 'Not set' ? 'status-ok' : 'status-error' ?>"><?= $value ?></span>
                        </p>
                    <?php endforeach; ?>
                </div>
                <div class="col-md-6">
                    <h5>Server Information:</h5>
                    <?php foreach($server_info as $key => $value): ?>
                        <p><strong><?= $key ?>:</strong> <code><?= $value ?></code></p>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>

        <!-- Icon Loading Test -->
        <div class="diagnostic-card">
            <h3>🎯 Icon Loading Test</h3>
            <div class="test-grid">
                <div class="test-item">
                    <i class="fas fa-shield-alt icon-test" style="color: #ffc107;"></i>
                    <p>Shield (FA6)</p>
                    <p id="shield-status" class="status-warning">Testing...</p>
                </div>
                <div class="test-item">
                    <i class="fas fa-cash-register icon-test" style="color: #28a745;"></i>
                    <p>Cash Register</p>
                    <p id="cash-status" class="status-warning">Testing...</p>
                </div>
                <div class="test-item">
                    <i class="fas fa-barcode icon-test" style="color: #17a2b8;"></i>
                    <p>Barcode</p>
                    <p id="barcode-status" class="status-warning">Testing...</p>
                </div>
                <div class="test-item">
                    <i class="fas fa-box icon-test" style="color: #6f42c1;"></i>
                    <p>Box</p>
                    <p id="box-status" class="status-warning">Testing...</p>
                </div>
                <div class="test-item">
                    <i class="fa fa-home icon-test" style="color: #fd7e14;"></i>
                    <p>Home (FA4)</p>
                    <p id="home-status" class="status-warning">Testing...</p>
                </div>
            </div>
        </div>

        <!-- CSS Loading Status -->
        <div class="diagnostic-card">
            <h3>📄 CSS Loading Status</h3>
            <div id="css-status">Checking CSS files...</div>
            <div class="code-block mt-3" id="css-details"></div>
        </div>

        <!-- Network Connectivity -->
        <div class="diagnostic-card">
            <h3>🌐 Network Connectivity</h3>
            <div id="network-status">Testing CDN connectivity...</div>
            <div class="mt-3" id="network-details"></div>
        </div>

        <!-- Browser Compatibility -->
        <div class="diagnostic-card">
            <h3>🌍 Browser Information</h3>
            <div id="browser-info">
                <p><strong>User Agent:</strong> <code id="user-agent"></code></p>
                <p><strong>Browser:</strong> <span id="browser-name"></span></p>
                <p><strong>Supports CSS Grid:</strong> <span id="css-grid-support"></span></p>
                <p><strong>Local Storage:</strong> <span id="local-storage-support"></span></p>
            </div>
        </div>

        <!-- Error Console -->
        <div class="diagnostic-card">
            <h3>❌ JavaScript Errors</h3>
            <div class="code-block" id="js-errors">No errors detected yet...</div>
        </div>

        <!-- Action Buttons -->
        <div class="diagnostic-card text-center">
            <h3>🔧 Actions</h3>
            <button onclick="runFullDiagnostic()" class="btn btn-warning btn-lg me-3">
                <i class="fas fa-sync"></i> Re-run Tests
            </button>
            <button onclick="clearBrowserCache()" class="btn btn-info btn-lg me-3">
                <i class="fas fa-broom"></i> Clear Cache
            </button>
            <a href="dashboard.php" class="btn btn-success btn-lg me-3">
                <i class="fas fa-home"></i> Back to Dashboard
            </a>
            <button onclick="downloadDiagnostic()" class="btn btn-secondary btn-lg">
                <i class="fas fa-download"></i> Download Report
            </button>
        </div>
    </div>

    <script>
        let errors = [];
        
        // Capture JavaScript errors
        window.onerror = function(msg, url, line, col, error) {
            errors.push(`${msg} at ${url}:${line}:${col}`);
            document.getElementById('js-errors').innerHTML = errors.join('<br>');
        };

        function checkIconLoading() {
            const icons = [
                {element: '.fas.fa-shield-alt', statusId: 'shield-status', name: 'Shield'},
                {element: '.fas.fa-cash-register', statusId: 'cash-status', name: 'Cash Register'},
                {element: '.fas.fa-barcode', statusId: 'barcode-status', name: 'Barcode'},
                {element: '.fas.fa-box', statusId: 'box-status', name: 'Box'},
                {element: '.fa.fa-home', statusId: 'home-status', name: 'Home'}
            ];

            setTimeout(function() {
                icons.forEach(function(icon) {
                    const element = document.querySelector(icon.element);
                    const statusElement = document.getElementById(icon.statusId);
                    
                    if (element) {
                        const computedStyle = window.getComputedStyle(element, '::before');
                        const content = computedStyle.getPropertyValue('content');
                        const fontFamily = computedStyle.getPropertyValue('font-family');
                        
                        if (content && content !== 'none' && content !== '""') {
                            statusElement.innerHTML = '✅ Loaded';
                            statusElement.className = 'status-ok';
                        } else {
                            statusElement.innerHTML = '❌ Failed';
                            statusElement.className = 'status-error';
                        }
                    }
                });
            }, 1500);
        }

        function checkCSSLoading() {
            const statusDiv = document.getElementById('css-status');
            const detailsDiv = document.getElementById('css-details');
            
            const stylesheets = Array.from(document.querySelectorAll('link[rel="stylesheet"]'));
            let cssDetails = '';
            let loadedCount = 0;
            
            stylesheets.forEach(function(link, index) {
                cssDetails += `${index + 1}. ${link.href}\n`;
                
                // Test if CSS loaded
                const testLoad = new Image();
                testLoad.onerror = function() { loadedCount++; };
                testLoad.onload = function() { loadedCount++; };
                testLoad.src = link.href;
            });
            
            statusDiv.innerHTML = `Found ${stylesheets.length} CSS files`;
            detailsDiv.innerHTML = cssDetails;
            
            setTimeout(function() {
                statusDiv.innerHTML = `${loadedCount}/${stylesheets.length} CSS files accessible`;
            }, 2000);
        }

        function checkNetworkConnectivity() {
            const statusDiv = document.getElementById('network-status');
            const detailsDiv = document.getElementById('network-details');
            
            const cdnUrls = [
                'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css',
                'https://use.fontawesome.com/releases/v6.4.0/css/all.css',
                'https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css'
            ];
            
            let results = '';
            let completedTests = 0;
            
            cdnUrls.forEach(function(url) {
                fetch(url, {method: 'HEAD'})
                    .then(response => {
                        completedTests++;
                        results += `✅ ${url.split('/')[2]} - OK (${response.status})\n`;
                        if (completedTests === cdnUrls.length) {
                            detailsDiv.innerHTML = '<pre>' + results + '</pre>';
                            statusDiv.innerHTML = '✅ All CDNs accessible';
                        }
                    })
                    .catch(error => {
                        completedTests++;
                        results += `❌ ${url.split('/')[2]} - Error: ${error.message}\n`;
                        if (completedTests === cdnUrls.length) {
                            detailsDiv.innerHTML = '<pre>' + results + '</pre>';
                            statusDiv.innerHTML = '❌ Some CDNs unreachable';
                        }
                    });
            });
        }

        function checkBrowserInfo() {
            document.getElementById('user-agent').textContent = navigator.userAgent;
            
            // Detect browser
            let browserName = 'Unknown';
            if (navigator.userAgent.indexOf('Chrome') > -1) browserName = 'Chrome';
            else if (navigator.userAgent.indexOf('Firefox') > -1) browserName = 'Firefox';
            else if (navigator.userAgent.indexOf('Safari') > -1) browserName = 'Safari';
            else if (navigator.userAgent.indexOf('Edge') > -1) browserName = 'Edge';
            
            document.getElementById('browser-name').textContent = browserName;
            
            // Check CSS Grid support
            document.getElementById('css-grid-support').textContent = 
                CSS.supports('display: grid') ? '✅ Supported' : '❌ Not supported';
            
            // Check localStorage
            try {
                localStorage.setItem('test', 'test');
                localStorage.removeItem('test');
                document.getElementById('local-storage-support').textContent = '✅ Available';
            } catch(e) {
                document.getElementById('local-storage-support').textContent = '❌ Blocked';
            }
        }

        function runFullDiagnostic() {
            checkIconLoading();
            checkCSSLoading(); 
            checkNetworkConnectivity();
            checkBrowserInfo();
        }

        function clearBrowserCache() {
            if (confirm('This will reload the page to clear browser cache. Continue?')) {
                window.location.reload(true);
            }
        }

        function downloadDiagnostic() {
            const report = `TEXTILE POS DIAGNOSTIC REPORT
Generated: ${new Date().toISOString()}
User: <?= $user['username'] ?> (<?= $user['role'] ?>)
URL: ${window.location.href}
User Agent: ${navigator.userAgent}

ERRORS:
${errors.join('\\n')}

CSS FILES:
${Array.from(document.querySelectorAll('link[rel="stylesheet"]')).map(l => l.href).join('\\n')}
`;
            
            const blob = new Blob([report], {type: 'text/plain'});
            const url = window.URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = 'pos-diagnostic-' + new Date().toISOString().split('T')[0] + '.txt';
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            window.URL.revokeObjectURL(url);
        }

        // Run diagnostics on page load
        setTimeout(runFullDiagnostic, 500);
    </script>
</body>
</html>