<?php
// Test AI Performance Analyzer Setup
require_once '../config/database.php';

echo "<h2>AI Performance Analyzer - System Test</h2>\n";

// Test 1: Check database connection
echo "<h3>1. Database Connection Test</h3>\n";
try {
    $stmt = $pdo->query("SELECT 1");
    echo "<span style='color: green;'>✅ Database connection successful</span><br>\n";
} catch (Exception $e) {
    echo "<span style='color: red;'>❌ Database connection failed: " . $e->getMessage() . "</span><br>\n";
    exit();
}

// Test 2: Check if AI tables exist
echo "<h3>2. AI Tables Status</h3>\n";
try {
    $stmt = $pdo->query("SHOW TABLES LIKE 'ai_%'");
    $tables = $stmt->fetchAll();
    
    if (count($tables) >= 5) {
        echo "<span style='color: green;'>✅ All AI tables exist (" . count($tables) . " tables found)</span><br>\n";
        foreach ($tables as $table) {
            echo "&nbsp;&nbsp;- " . $table[0] . "<br>\n";
        }
    } else {
        echo "<span style='color: orange;'>⚠️ AI tables not fully set up (" . count($tables) . "/5 tables found)</span><br>\n";
        echo "<a href='setup.php'>Click here to run setup</a><br>\n";
    }
} catch (Exception $e) {
    echo "<span style='color: red;'>❌ Error checking tables: " . $e->getMessage() . "</span><br>\n";
}

// Test 3: Check sample data availability
echo "<h3>3. Data Availability Test</h3>\n";
try {
    // Check students
    $stmt = $pdo->query("SELECT COUNT(*) FROM students WHERE status = 'active'");
    $student_count = $stmt->fetchColumn();
    echo "Active students: <strong>$student_count</strong><br>\n";
    
    // Check results
    $stmt = $pdo->query("SELECT COUNT(*) FROM results WHERE marks_obtained IS NOT NULL");
    $result_count = $stmt->fetchColumn();
    echo "Result records: <strong>$result_count</strong><br>\n";
    
    // Check subjects
    $stmt = $pdo->query("SELECT COUNT(*) FROM subjects WHERE status = 'active'");
    $subject_count = $stmt->fetchColumn();
    echo "Active subjects: <strong>$subject_count</strong><br>\n";
    
    if ($student_count > 0 && $result_count > 10) {
        echo "<span style='color: green;'>✅ Sufficient data for AI analysis</span><br>\n";
    } else {
        echo "<span style='color: orange;'>⚠️ Limited data available. Add more student results for better AI insights.</span><br>\n";
    }
} catch (Exception $e) {
    echo "<span style='color: red;'>❌ Error checking data: " . $e->getMessage() . "</span><br>\n";
}

// Test 4: Quick functionality test
echo "<h3>4. Quick Functionality Test</h3>\n";
echo "<button onclick='testAIController()' style='padding: 10px 20px; margin: 5px; background: #007bff; color: white; border: none; border-radius: 5px; cursor: pointer;'>Test AI Controller</button>\n";
echo "<button onclick='testNotifications()' style='padding: 10px 20px; margin: 5px; background: #28a745; color: white; border: none; border-radius: 5px; cursor: pointer;'>Test Notifications</button>\n";
echo "<div id='testResults' style='margin-top: 20px; padding: 15px; border: 1px solid #ddd; border-radius: 5px;'></div>\n";

echo "<br><br><a href='index.php' style='padding: 10px 20px; background: #17a2b8; color: white; text-decoration: none; border-radius: 5px;'>Go to AI Dashboard</a>\n";
?>

<script>
function testAIController() {
    const resultsDiv = document.getElementById('testResults');
    resultsDiv.innerHTML = '<p>Testing AI controller...</p>';
    
    fetch('ajax/ai_controller.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: 'action=load_analytics'
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            resultsDiv.innerHTML = `
                <h4 style="color: green;">✅ AI Controller Working!</h4>
                <p><strong>Response:</strong> ${data.message}</p>
                <p><strong>Data received:</strong> ${JSON.stringify(data.analytics)}</p>
            `;
        } else {
            resultsDiv.innerHTML = `
                <h4 style="color: orange;">⚠️ Controller responded but with error</h4>
                <p><strong>Error:</strong> ${data.message}</p>
            `;
        }
    })
    .catch(error => {
        resultsDiv.innerHTML = `
            <h4 style="color: red;">❌ Connection Error</h4>
            <p><strong>Error:</strong> ${error.message}</p>
        `;
    });
}

function testNotifications() {
    const resultsDiv = document.getElementById('testResults');
    resultsDiv.innerHTML = '<p>Testing notifications...</p>';
    
    // Simulate different notification types
    const notifications = [
        {
            type: 'success',
            title: 'Test Success',
            message: 'This is a success notification test',
            icon: 'fas fa-check-circle',
            duration: 3000
        },
        {
            type: 'error',
            title: 'Test Error',
            message: 'This is an error notification test',
            icon: 'fas fa-exclamation-circle',
            duration: 4000
        },
        {
            type: 'warning',
            title: 'Test Warning',
            message: 'This is a warning notification test',
            icon: 'fas fa-exclamation-triangle',
            duration: 5000
        }
    ];
    
    // Create temporary notification container
    const tempContainer = document.createElement('div');
    tempContainer.id = 'tempNotificationContainer';
    tempContainer.style.position = 'fixed';
    tempContainer.style.top = '20px';
    tempContainer.style.right = '20px';
    tempContainer.style.zIndex = '10000';
    document.body.appendChild(tempContainer);
    
    // Show notifications one by one
    let index = 0;
    function showNextNotification() {
        if (index < notifications.length) {
            showTestNotification(notifications[index], tempContainer);
            index++;
            setTimeout(showNextNotification, 1500);
        } else {
            resultsDiv.innerHTML = '<h4 style="color: green;">✅ All notifications displayed successfully!</h4>';
            // Clean up after delay
            setTimeout(() => {
                document.body.removeChild(tempContainer);
            }, 3000);
        }
    }
    
    showNextNotification();
}

function showTestNotification(notification, container) {
    const notificationEl = document.createElement('div');
    notificationEl.className = `toast show mb-2`;
    notificationEl.style.minWidth = '350px';
    
    let bgColor = 'bg-primary';
    if (notification.type === 'success') bgColor = 'bg-success';
    else if (notification.type === 'error') bgColor = 'bg-danger';
    else if (notification.type === 'warning') bgColor = 'bg-warning';
    else if (notification.type === 'info') bgColor = 'bg-info';
    
    notificationEl.innerHTML = `
        <div class="toast-header ${bgColor} text-white">
            <i class="${notification.icon} me-2"></i>
            <strong class="me-auto">${notification.title}</strong>
            <small>Test</small>
            <button type="button" class="btn-close btn-close-white" data-bs-dismiss="toast" onclick="this.parentElement.parentElement.remove()"></button>
        </div>
        <div class="toast-body">
            ${notification.message}
        </div>
    `;
    
    container.appendChild(notificationEl);
    
    if (notification.duration > 0) {
        setTimeout(() => {
            if (notificationEl.parentElement) {
                notificationEl.remove();
            }
        }, notification.duration);
    }
}
</script>