<?php
session_start();
require_once '../config/database.php';
require_once '../includes/site_settings.php';

$system_name = get_system_name($pdo);

// Get teachers data
$stmt = $pdo->query("SELECT id, employee_id, first_name, last_name, photo FROM teachers WHERE status = 'active' ORDER BY first_name, last_name");
$teachers = $stmt->fetchAll();

// Check attendance table structure
$table_check = $pdo->query("SHOW TABLES LIKE 'attendance'");
$table_exists = $table_check->rowCount() > 0;

if ($table_exists) {
    $columns_check = $pdo->query("SHOW COLUMNS FROM attendance");
    $columns = $columns_check->fetchAll();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Auto Attendance Diagnostic - <?php echo htmlspecialchars($system_name); ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
</head>
<body>
    <div class="container mt-4">
        <div class="row">
            <div class="col-md-12">
                <h1><i class="fas fa-stethoscope"></i> Auto Attendance System Diagnostic</h1>
                <p class="text-muted">Comprehensive system check for auto attendance functionality</p>
                
                <!-- System Status Overview -->
                <div class="card mb-4">
                    <div class="card-header bg-primary text-white">
                        <h5 class="mb-0"><i class="fas fa-tachometer-alt"></i> System Status Overview</h5>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-3">
                                <div class="card text-center">
                                    <div class="card-body">
                                        <h3 class="text-<?php echo count($teachers) > 0 ? 'success' : 'danger'; ?>">
                                            <?php echo count($teachers); ?>
                                        </h3>
                                        <p class="card-text">Active Teachers</p>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="card text-center">
                                    <div class="card-body">
                                        <h3 class="text-<?php echo $table_exists ? 'success' : 'danger'; ?>">
                                            <?php echo $table_exists ? 'YES' : 'NO'; ?>
                                        </h3>
                                        <p class="card-text">Attendance Table</p>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="card text-center">
                                    <div class="card-body">
                                        <h3 class="text-<?php echo isset($_SERVER['HTTPS']) || $_SERVER['SERVER_NAME'] === 'localhost' ? 'success' : 'warning'; ?>">
                                            <?php echo isset($_SERVER['HTTPS']) || $_SERVER['SERVER_NAME'] === 'localhost' ? 'SECURE' : 'INSECURE'; ?>
                                        </h3>
                                        <p class="card-text">Connection Type</p>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="card text-center">
                                    <div class="card-body">
                                        <h3 class="text-<?php echo function_exists('json_encode') ? 'success' : 'danger'; ?>">
                                            <?php echo function_exists('json_encode') ? 'AVAILABLE' : 'MISSING'; ?>
                                        </h3>
                                        <p class="card-text">JSON Support</p>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Database Check -->
                <div class="card mb-4">
                    <div class="card-header bg-info text-white">
                        <h5 class="mb-0"><i class="fas fa-database"></i> Database Configuration</h5>
                    </div>
                    <div class="card-body">
                        <h6>Teachers Table Data:</h6>
                        <?php if (count($teachers) > 0): ?>
                            <div class="table-responsive">
                                <table class="table table-striped">
                                    <thead>
                                        <tr>
                                            <th>ID</th>
                                            <th>Employee ID</th>
                                            <th>Name</th>
                                            <th>Photo Status</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($teachers as $teacher): ?>
                                            <tr>
                                                <td><?php echo $teacher['id']; ?></td>
                                                <td><?php echo htmlspecialchars($teacher['employee_id']); ?></td>
                                                <td><?php echo htmlspecialchars($teacher['first_name'] . ' ' . $teacher['last_name']); ?></td>
                                                <td>
                                                    <span class="badge bg-<?php echo !empty($teacher['photo']) ? 'success' : 'secondary'; ?>">
                                                        <?php echo !empty($teacher['photo']) ? 'Has Photo' : 'No Photo'; ?>
                                                    </span>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php else: ?>
                            <div class="alert alert-danger">
                                <i class="fas fa-exclamation-triangle"></i> No active teachers found in database!
                            </div>
                        <?php endif; ?>
                        
                        <h6 class="mt-4">Attendance Table Structure:</h6>
                        <?php if ($table_exists): ?>
                            <div class="table-responsive">
                                <table class="table table-sm">
                                    <thead>
                                        <tr>
                                            <th>Column</th>
                                            <th>Type</th>
                                            <th>Null</th>
                                            <th>Key</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($columns as $column): ?>
                                            <tr>
                                                <td><?php echo $column['Field']; ?></td>
                                                <td><?php echo $column['Type']; ?></td>
                                                <td><?php echo $column['Null']; ?></td>
                                                <td><?php echo $column['Key']; ?></td>
                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php else: ?>
                            <div class="alert alert-danger">
                                <i class="fas fa-times-circle"></i> Attendance table does not exist!
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
                
                <!-- Browser Compatibility Check -->
                <div class="card mb-4">
                    <div class="card-header bg-warning text-dark">
                        <h5 class="mb-0"><i class="fas fa-browser"></i> Browser Compatibility</h5>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-6">
                                <h6>Browser Features:</h6>
                                <ul class="list-group">
                                    <li class="list-group-item d-flex justify-content-between align-items-center">
                                        Media Devices API
                                        <span class="badge bg-<?php echo isset($_SERVER['HTTP_USER_AGENT']) && strpos($_SERVER['HTTP_USER_AGENT'], 'Chrome') !== false ? 'success' : 'secondary'; ?>">Chrome Recommended</span>
                                    </li>
                                    <li class="list-group-item d-flex justify-content-between align-items-center">
                                        getUserMedia Support
                                        <span id="getUserMediaStatus" class="badge bg-secondary">Checking...</span>
                                    </li>
                                    <li class="list-group-item d-flex justify-content-between align-items-center">
                                        Secure Context
                                        <span class="badge bg-<?php echo isset($_SERVER['HTTPS']) || $_SERVER['SERVER_NAME'] === 'localhost' ? 'success' : 'warning'; ?>">
                                            <?php echo isset($_SERVER['HTTPS']) || $_SERVER['SERVER_NAME'] === 'localhost' ? 'Yes' : 'No (May cause issues)'; ?>
                                        </span>
                                    </li>
                                    <li class="list-group-item d-flex justify-content-between align-items-center">
                                        Camera Permission
                                        <span id="cameraPermissionStatus" class="badge bg-secondary">Unknown</span>
                                    </li>
                                </ul>
                            </div>
                            <div class="col-md-6">
                                <h6>System Tests:</h6>
                                <button class="btn btn-primary mb-2" onclick="testCameraAccess()">
                                    <i class="fas fa-camera"></i> Test Camera Access
                                </button>
                                <button class="btn btn-info mb-2" onclick="testAjax()">
                                    <i class="fas fa-exchange-alt"></i> Test AJAX Connection
                                </button>
                                <button class="btn btn-success mb-2" onclick="testFaceApi()">
                                    <i class="fas fa-face-smile"></i> Test Face Detection
                                </button>
                                
                                <div id="testResults" class="mt-3"></div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Quick Fix Buttons -->
                <div class="card">
                    <div class="card-header bg-success text-white">
                        <h5 class="mb-0"><i class="fas fa-tools"></i> Quick Fixes</h5>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-4">
                                <button class="btn btn-outline-primary w-100 mb-2" onclick="window.location.href='teacher_photo_registration.php'">
                                    <i class="fas fa-redo"></i> Reload Main Page
                                </button>
                            </div>
                            <div class="col-md-4">
                                <button class="btn btn-outline-info w-100 mb-2" onclick="clearConsoleLogs()">
                                    <i class="fas fa-broom"></i> Clear Console Logs
                                </button>
                            </div>
                            <div class="col-md-4">
                                <button class="btn btn-outline-warning w-100 mb-2" onclick="showFullDiagnostic()">
                                    <i class="fas fa-file-medical"></i> Full Diagnostic Report
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        // Test browser features
        document.addEventListener('DOMContentLoaded', function() {
            // Check getUserMedia support
            const getUserMediaStatus = document.getElementById('getUserMediaStatus');
            if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
                getUserMediaStatus.className = 'badge bg-success';
                getUserMediaStatus.textContent = 'Supported';
            } else {
                getUserMediaStatus.className = 'badge bg-danger';
                getUserMediaStatus.textContent = 'Not Supported';
            }
            
            // Check camera permission status
            checkCameraPermission();
        });
        
        async function checkCameraPermission() {
            const permissionStatus = document.getElementById('cameraPermissionStatus');
            try {
                if (navigator.permissions) {
                    const status = await navigator.permissions.query({name: 'camera'});
                    permissionStatus.className = 'badge bg-' + (status.state === 'granted' ? 'success' : status.state === 'denied' ? 'danger' : 'warning');
                    permissionStatus.textContent = status.state.charAt(0).toUpperCase() + status.state.slice(1);
                } else {
                    permissionStatus.className = 'badge bg-secondary';
                    permissionStatus.textContent = 'Cannot Check';
                }
            } catch (error) {
                permissionStatus.className = 'badge bg-secondary';
                permissionStatus.textContent = 'Error Checking';
            }
        }
        
        async function testCameraAccess() {
            const resultsDiv = document.getElementById('testResults');
            resultsDiv.innerHTML = '<div class="alert alert-info">Testing camera access...</div>';
            
            try {
                const stream = await navigator.mediaDevices.getUserMedia({video: true});
                stream.getTracks().forEach(track => track.stop());
                resultsDiv.innerHTML = '<div class="alert alert-success">✓ Camera access test PASSED</div>';
            } catch (error) {
                resultsDiv.innerHTML = `<div class="alert alert-danger">✗ Camera access FAILED: ${error.message}</div>`;
            }
        }
        
        async function testAjax() {
            const resultsDiv = document.getElementById('testResults');
            resultsDiv.innerHTML = '<div class="alert alert-info">Testing AJAX connection...</div>';
            
            try {
                const response = await fetch('teacher_photo_registration.php', {
                    method: 'POST',
                    headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                    body: 'action=test_connection'
                });
                
                if (response.ok) {
                    resultsDiv.innerHTML = '<div class="alert alert-success">✓ AJAX connection test PASSED</div>';
                } else {
                    resultsDiv.innerHTML = `<div class="alert alert-danger">✗ AJAX connection FAILED: ${response.status}</div>`;
                }
            } catch (error) {
                resultsDiv.innerHTML = `<div class="alert alert-danger">✗ AJAX connection FAILED: ${error.message}</div>`;
            }
        }
        
        async function testFaceApi() {
            const resultsDiv = document.getElementById('testResults');
            resultsDiv.innerHTML = '<div class="alert alert-info">Testing face-api.js availability...</div>';
            
            if (typeof faceapi !== 'undefined') {
                resultsDiv.innerHTML = '<div class="alert alert-success">✓ face-api.js is loaded</div>';
            } else {
                resultsDiv.innerHTML = '<div class="alert alert-warning">⚠ face-api.js not loaded - will load from CDN</div>';
            }
        }
        
        function clearConsoleLogs() {
            console.clear();
            document.getElementById('testResults').innerHTML = '<div class="alert alert-info">Console logs cleared. Refresh page to restart diagnostics.</div>';
        }
        
        function showFullDiagnostic() {
            const diagnosticInfo = {
                userAgent: navigator.userAgent,
                platform: navigator.platform,
                cookiesEnabled: navigator.cookieEnabled,
                language: navigator.language,
                onLine: navigator.onLine,
                mediaDevices: !!navigator.mediaDevices,
                getUserMedia: !!(navigator.mediaDevices && navigator.mediaDevices.getUserMedia),
                secureContext: window.isSecureContext,
                location: window.location.href,
                timestamp: new Date().toISOString()
            };
            
            console.log('=== FULL DIAGNOSTIC REPORT ===');
            console.log(diagnosticInfo);
            console.log('==============================');
            
            alert('Diagnostic information logged to console. Press F12 to view.');
        }
    </script>
</body>
</html>