<?php
require_once '../config/database.php';
require_once '../includes/auth.php';
require_once 'includes/notification_system.php';

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

$page_title = "AI Performance Analyzer";
include '../includes/header.php';
include '../includes/sidebar_layout.php';

// Check if AI tables exist
$tables_exist = false;
try {
    $stmt = $pdo->query("SHOW TABLES LIKE 'ai_%'");
    $tables_exist = $stmt->rowCount() >= 5;
} catch (Exception $e) {
    $tables_exist = false;
}

// Get available sessions, classes, and subjects for filters
$sessions = [];
$classes = [];
$subjects = [];

try {
    // Get sessions
    $stmt = $pdo->query("SELECT DISTINCT session FROM students WHERE session IS NOT NULL ORDER BY session DESC");
    $sessions = $stmt->fetchAll(PDO::FETCH_COLUMN);
    
    // Get classes
    $stmt = $pdo->query("SELECT id, name FROM classes ORDER BY name");
    $classes = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Get subjects
    $stmt = $pdo->query("SELECT id, name, code FROM subjects WHERE status = 'active' ORDER BY name");
    $subjects = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
} catch (Exception $e) {
    $error_message = "Error loading data: " . $e->getMessage();
}
?>

<div class="main-content">
    <div class="container-fluid">
        <!-- Page Header -->
        <div class="page-header">
            <div class="row align-items-center">
                <div class="col">
                    <h3 class="page-title">AI Performance Analyzer</h3>
                    <ul class="breadcrumb">
                        <li class="breadcrumb-item"><a href="../index.php">Dashboard</a></li>
                        <li class="breadcrumb-item active">AI Performance Analyzer</li>
                    </ul>
                </div>
                <div class="col-auto">
                    <button class="btn btn-primary" onclick="refreshAnalysis()">
                        <i class="fas fa-sync-alt"></i> Refresh Analysis
                    </button>
                </div>
            </div>
        </div>

        <?php if (isset($error_message)): ?>
        <div class="alert alert-danger">
            <i class="fas fa-exclamation-circle"></i> <?php echo htmlspecialchars($error_message); ?>
        </div>
        <?php endif; ?>

        <?php if (!$tables_exist): ?>
        <div class="alert alert-warning alert-dismissible fade show" role="alert">
            <i class="fas fa-exclamation-triangle"></i>
            <strong>AI System Not Initialized!</strong> Please run setup to create database tables.
            <button type="button" class="btn btn-primary ms-3" onclick="runSetup()">
                <i class="fas fa-cog"></i> Run Setup Now
            </button>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
        <?php endif; ?>

        <!-- Notification Container -->
        <div id="notificationContainer" class="position-fixed top-0 end-0 p-3" style="z-index: 10000;">
            <!-- Notifications will be inserted here dynamically -->
        </div>

        <!-- Filter Section -->
        <div class="card mb-4">
            <div class="card-header">
                <h5 class="card-title mb-0">Analysis Filters</h5>
            </div>
            <div class="card-body">
                <form id="analysisForm" method="GET">
                    <div class="row">
                        <div class="col-md-3">
                            <label for="session" class="form-label">Session</label>
                            <select class="form-select" id="session" name="session">
                                <option value="">All Sessions</option>
                                <?php foreach ($sessions as $session): ?>
                                    <option value="<?php echo htmlspecialchars($session); ?>" 
                                        <?php echo (isset($_GET['session']) && $_GET['session'] == $session) ? 'selected' : ''; ?>>
                                        <?php echo htmlspecialchars($session); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-3">
                            <label for="class_id" class="form-label">Class</label>
                            <select class="form-select" id="class_id" name="class_id">
                                <option value="">All Classes</option>
                                <?php foreach ($classes as $class): ?>
                                    <option value="<?php echo $class['id']; ?>" 
                                        <?php echo (isset($_GET['class_id']) && $_GET['class_id'] == $class['id']) ? 'selected' : ''; ?>>
                                        <?php echo htmlspecialchars($class['name']); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-3">
                            <label for="subject_id" class="form-label">Subject</label>
                            <select class="form-select" id="subject_id" name="subject_id">
                                <option value="">All Subjects</option>
                                <?php foreach ($subjects as $subject): ?>
                                    <option value="<?php echo $subject['id']; ?>" 
                                        <?php echo (isset($_GET['subject_id']) && $_GET['subject_id'] == $subject['id']) ? 'selected' : ''; ?>>
                                        <?php echo htmlspecialchars($subject['name'] . ' (' . $subject['code'] . ')'); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-3">
                            <label for="exam_type" class="form-label">Exam Type</label>
                            <select class="form-select" id="exam_type" name="exam_type">
                                <option value="">All Exams</option>
                                <option value="midterm" <?php echo (isset($_GET['exam_type']) && $_GET['exam_type'] == 'midterm') ? 'selected' : ''; ?>>Midterm</option>
                                <option value="final" <?php echo (isset($_GET['exam_type']) && $_GET['exam_type'] == 'final') ? 'selected' : ''; ?>>Final</option>
                                <option value="test" <?php echo (isset($_GET['exam_type']) && $_GET['exam_type'] == 'test') ? 'selected' : ''; ?>>Test</option>
                            </select>
                        </div>
                    </div>
                    <div class="row mt-3">
                        <div class="col-md-12">
                            <button type="submit" class="btn btn-primary">
                                <i class="fas fa-search"></i> Analyze Performance
                            </button>
                            <button type="button" class="btn btn-success" onclick="generatePredictions()" id="predictBtn">
                                <i class="fas fa-chart-line"></i> Generate Predictions
                            </button>
                            <button type="button" class="btn btn-info" onclick="generateRecommendations()" id="recommendBtn">
                                <i class="fas fa-lightbulb"></i> Get Recommendations
                            </button>
                            <button type="button" class="btn btn-warning" onclick="assessStudentRisk()" id="riskBtn">
                                <i class="fas fa-exclamation-triangle"></i> Risk Assessment
                            </button>
                            <?php if (!$tables_exist): ?>
                            <button type="button" class="btn btn-secondary" onclick="runSetup()" id="setupBtn">
                                <i class="fas fa-cog"></i> Setup AI System
                            </button>
                            <?php endif; ?>
                        </div>
                    </div>
                </form>
            </div>
        </div>

        <!-- Analytics Dashboard -->
        <div class="row">
            <!-- Overall Performance Card -->
            <div class="col-xl-3 col-md-6">
                <div class="card bg-primary text-white">
                    <div class="card-body">
                        <div class="row">
                            <div class="col">
                                <h5 class="card-title text-white">Average Performance</h5>
                                <h2 class="mb-0" id="avgPerformance">--%</h2>
                                <small>Trend: <span id="performanceTrend">Loading...</span></small>
                            </div>
                            <div class="col-auto">
                                <i class="fas fa-chart-bar fa-2x"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Pass Rate Card -->
            <div class="col-xl-3 col-md-6">
                <div class="card bg-success text-white">
                    <div class="card-body">
                        <div class="row">
                            <div class="col">
                                <h5 class="card-title text-white">Pass Rate</h5>
                                <h2 class="mb-0" id="passRate">--%</h2>
                                <small>Students passed</small>
                            </div>
                            <div class="col-auto">
                                <i class="fas fa-check-circle fa-2x"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- At-Risk Students Card -->
            <div class="col-xl-3 col-md-6">
                <div class="card bg-warning text-dark">
                    <div class="card-body">
                        <div class="row">
                            <div class="col">
                                <h5 class="card-title text-dark">At Risk</h5>
                                <h2 class="mb-0" id="atRiskCount">--</h2>
                                <small>Students needing help</small>
                            </div>
                            <div class="col-auto">
                                <i class="fas fa-exclamation-triangle fa-2x"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Top Performers Card -->
            <div class="col-xl-3 col-md-6">
                <div class="card bg-info text-white">
                    <div class="card-body">
                        <div class="row">
                            <div class="col">
                                <h5 class="card-title text-white">Top Performers</h5>
                                <h2 class="mb-0" id="topPerformers">--</h2>
                                <small>Excellent students</small>
                            </div>
                            <div class="col-auto">
                                <i class="fas fa-trophy fa-2x"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Detailed Analysis Section -->
        <div class="row mt-4">
            <!-- Performance Trends Chart -->
            <div class="col-lg-8">
                <div class="card">
                    <div class="card-header">
                        <h5 class="card-title mb-0">Performance Trends Over Time</h5>
                    </div>
                    <div class="card-body">
                        <canvas id="performanceChart" height="300"></canvas>
                    </div>
                </div>
            </div>

            <!-- Subject-wise Analysis -->
            <div class="col-lg-4">
                <div class="card">
                    <div class="card-header">
                        <h5 class="card-title mb-0">Subject Performance</h5>
                    </div>
                    <div class="card-body">
                        <div id="subjectPerformance">
                            <div class="text-center py-4">
                                <i class="fas fa-spinner fa-spin fa-2x"></i>
                                <p class="mt-2">Analyzing subject performance...</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- AI Recommendations Section -->
        <div class="card mt-4">
            <div class="card-header">
                <h5 class="card-title mb-0">AI Recommendations</h5>
            </div>
            <div class="card-body">
                <div id="recommendationsContainer">
                    <div class="text-center py-4">
                        <button class="btn btn-primary" onclick="loadRecommendations()">
                            <i class="fas fa-lightbulb"></i> Generate AI Recommendations
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <!-- Student Risk Assessment -->
        <div class="card mt-4">
            <div class="card-header">
                <h5 class="card-title mb-0">Student Risk Assessment</h5>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-striped" id="riskAssessmentTable">
                        <thead>
                            <tr>
                                <th>Student</th>
                                <th>Risk Level</th>
                                <th>Factors</th>
                                <th>Score</th>
                                <th>Last Assessment</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td colspan="6" class="text-center">
                                    <button class="btn btn-outline-primary" onclick="assessStudentRisk()">
                                        <i class="fas fa-calculator"></i> Run Risk Assessment
                                    </button>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Modal for detailed student analysis -->
<div class="modal fade" id="studentAnalysisModal" tabindex="-1">
    <div class="modal-dialog modal-xl">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Student Performance Analysis</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body" id="studentAnalysisContent">
                <!-- Content will be loaded dynamically -->
            </div>
        </div>
    </div>
</div>

<!-- AI Control Panel - Auto-opening widget -->
<div class="modal fade" id="aiControlPanel" tabindex="-1" data-bs-backdrop="static" data-bs-keyboard="false">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title">
                    <i class="fas fa-brain me-2"></i>AI Control Panel
                </h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div id="controlPanelContent">
                    <div class="text-center py-5">
                        <i class="fas fa-spinner fa-spin fa-2x text-primary"></i>
                        <p class="mt-3">Loading AI system status...</p>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary" onclick="refreshControlPanel()">
                    <i class="fas fa-sync-alt"></i> Refresh
                </button>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
// Global variables for charts
let performanceChart = null;

// Initialize the page
document.addEventListener('DOMContentLoaded', function() {
    loadAnalyticsData();
    loadControlPanel(); // Load AI control panel automatically
});

// Load analytics data
function loadAnalyticsData() {
    const formData = new FormData(document.getElementById('analysisForm'));
    
    fetch('ajax/load_analytics.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            updateDashboardCards(data.analytics);
            updatePerformanceChart(data.trends);
            updateSubjectPerformance(data.subject_analysis);
        } else {
            showError(data.message || 'Error loading analytics data');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showError('Network error occurred');
    });
}

// Update dashboard cards
function updateDashboardCards(analytics) {
    document.getElementById('avgPerformance').textContent = analytics.average_performance + '%';
    document.getElementById('passRate').textContent = analytics.pass_rate + '%';
    document.getElementById('atRiskCount').textContent = analytics.at_risk_count;
    document.getElementById('topPerformers').textContent = analytics.top_performers;
    
    // Update trend indicators
    const trendElement = document.getElementById('performanceTrend');
    if (analytics.trend_direction === 'up') {
        trendElement.innerHTML = '<i class="fas fa-arrow-up text-success"></i> Improving';
        trendElement.className = 'text-success';
    } else if (analytics.trend_direction === 'down') {
        trendElement.innerHTML = '<i class="fas fa-arrow-down text-danger"></i> Declining';
        trendElement.className = 'text-danger';
    } else {
        trendElement.innerHTML = '<i class="fas fa-minus text-warning"></i> Stable';
        trendElement.className = 'text-warning';
    }
}

// Update performance chart
function updatePerformanceChart(trends) {
    const ctx = document.getElementById('performanceChart').getContext('2d');
    
    if (performanceChart) {
        performanceChart.destroy();
    }
    
    performanceChart = new Chart(ctx, {
        type: 'line',
        data: {
            labels: trends.labels,
            datasets: [{
                label: 'Average Marks',
                data: trends.average_marks,
                borderColor: '#4e73df',
                backgroundColor: 'rgba(78, 115, 223, 0.1)',
                borderWidth: 2,
                tension: 0.3
            }, {
                label: 'Pass Rate %',
                data: trends.pass_rates,
                borderColor: '#1cc88a',
                backgroundColor: 'rgba(28, 200, 138, 0.1)',
                borderWidth: 2,
                tension: 0.3
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            scales: {
                y: {
                    beginAtZero: true,
                    max: 100
                }
            }
        }
    });
}

// Update subject performance
function updateSubjectPerformance(subjectData) {
    const container = document.getElementById('subjectPerformance');
    let html = '<div class="list-group">';
    
    subjectData.forEach(subject => {
        const progressBarClass = getProgressBarClass(subject.average_marks);
        html += `
            <div class="list-group-item">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <h6 class="mb-1">${subject.name}</h6>
                        <small class="text-muted">Code: ${subject.code}</small>
                    </div>
                    <span class="badge ${progressBarClass.replace('bg-', 'bg-')} rounded-pill">
                        ${subject.average_marks}%
                    </span>
                </div>
                <div class="progress mt-2" style="height: 8px;">
                    <div class="progress-bar ${progressBarClass}" 
                         style="width: ${subject.average_marks}%"></div>
                </div>
                <div class="mt-1">
                    <small>Pass Rate: ${subject.pass_rate}% | Students: ${subject.student_count}</small>
                </div>
            </div>
        `;
    });
    
    html += '</div>';
    container.innerHTML = html;
}

// Helper function for progress bar classes
function getProgressBarClass(percentage) {
    if (percentage >= 80) return 'bg-success';
    if (percentage >= 60) return 'bg-info';
    if (percentage >= 40) return 'bg-warning';
    return 'bg-danger';
}

// Generate predictions
async function generatePredictions() {
    setLoadingState('predictBtn', true);
    showNotification({
        type: 'loading',
        title: 'Generating Predictions',
        message: 'Analyzing student performance data...',
        icon: 'fas fa-brain',
        duration: 0
    });
    
    try {
        const response = await fetch('ajax/ai_controller.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: 'action=generate_predictions'
        });
        
        const data = await response.json();
        
        if (data.success) {
            showNotification({
                type: 'success',
                title: 'Predictions Generated',
                message: data.message,
                icon: 'fas fa-chart-line',
                duration: 6000
            });
            loadAnalyticsData(); // Refresh dashboard
        } else {
            showNotification({
                type: 'error',
                title: 'Generation Failed',
                message: data.message,
                icon: 'fas fa-exclamation-triangle',
                duration: 7000
            });
        }
    } catch (error) {
        showNotification({
            type: 'error',
            title: 'Connection Error',
            message: 'Could not generate predictions. Please try again.',
            icon: 'fas fa-wifi',
            duration: 5000
        });
    } finally {
        setLoadingState('predictBtn', false);
    }
}

// Generate recommendations
async function generateRecommendations() {
    setLoadingState('recommendBtn', true);
    showNotification({
        type: 'loading',
        title: 'Creating Recommendations',
        message: 'Generating personalized student suggestions...',
        icon: 'fas fa-lightbulb',
        duration: 0
    });
    
    try {
        const response = await fetch('ajax/ai_controller.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: 'action=generate_recommendations'
        });
        
        const data = await response.json();
        
        if (data.success) {
            showNotification({
                type: 'success',
                title: 'Recommendations Ready',
                message: data.message,
                icon: 'fas fa-lightbulb',
                duration: 7000
            });
            loadRecommendations();
        } else {
            showNotification({
                type: 'error',
                title: 'Generation Failed',
                message: data.message,
                icon: 'fas fa-exclamation-circle',
                duration: 7000
            });
        }
    } catch (error) {
        showNotification({
            type: 'error',
            title: 'Connection Error',
            message: 'Could not generate recommendations. Please try again.',
            icon: 'fas fa-wifi',
            duration: 5000
        });
    } finally {
        setLoadingState('recommendBtn', false);
    }
}

// Load recommendations
function loadRecommendations() {
    const container = document.getElementById('recommendationsContainer');
    container.innerHTML = '<div class="text-center py-4"><i class="fas fa-spinner fa-spin fa-2x"></i><p>Loading recommendations...</p></div>';
    
    fetch('ajax/load_recommendations.php')
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            displayRecommendations(data.recommendations);
        } else {
            container.innerHTML = '<div class="alert alert-warning">No recommendations available. Click "Generate AI Recommendations" to create suggestions.</div>';
        }
    })
    .catch(error => {
        console.error('Error:', error);
        container.innerHTML = '<div class="alert alert-danger">Error loading recommendations</div>';
    });
}

// Display recommendations
function displayRecommendations(recommendations) {
    const container = document.getElementById('recommendationsContainer');
    let html = '<div class="row">';
    
    recommendations.forEach(rec => {
        const priorityClass = getPriorityClass(rec.priority);
        const priorityIcon = getPriorityIcon(rec.priority);
        
        html += `
            <div class="col-md-6 col-lg-4 mb-3">
                <div class="card border-left-${priorityClass} h-100">
                    <div class="card-body">
                        <div class="row no-gutters align-items-center">
                            <div class="col mr-2">
                                <div class="text-xs font-weight-bold text-${priorityClass} text-uppercase mb-1">
                                    ${priorityIcon} ${rec.title}
                                </div>
                                <div class="h6 mb-2 text-gray-800">${rec.description}</div>
                                ${rec.suggested_action ? `<div class="small text-muted"><strong>Action:</strong> ${rec.suggested_action}</div>` : ''}
                                <div class="mt-2">
                                    <span class="badge bg-${priorityClass}">${rec.priority.toUpperCase()}</span>
                                    <span class="badge bg-secondary ms-1">${rec.type}</span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        `;
    });
    
    html += '</div>';
    container.innerHTML = html;
}

// Assess student risk
async function assessStudentRisk() {
    setLoadingState('riskBtn', true);
    showNotification({
        type: 'loading',
        title: 'Assessing Risk',
        message: 'Evaluating student risk factors...',
        icon: 'fas fa-exclamation-triangle',
        duration: 0
    });
    
    try {
        const response = await fetch('ajax/ai_controller.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: 'action=assess_risk'
        });
        
        const data = await response.json();
        
        if (data.success) {
            showNotification({
                type: 'warning',
                title: 'Risk Assessment Complete',
                message: data.message,
                icon: 'fas fa-exclamation-triangle',
                duration: 8000
            });
        } else {
            showNotification({
                type: 'error',
                title: 'Assessment Failed',
                message: data.message,
                icon: 'fas fa-exclamation-circle',
                duration: 7000
            });
        }
    } catch (error) {
        showNotification({
            type: 'error',
            title: 'Connection Error',
            message: 'Could not complete risk assessment. Please try again.',
            icon: 'fas fa-wifi',
            duration: 5000
        });
    } finally {
        setLoadingState('riskBtn', false);
    }
}

// Load risk assessment
function loadRiskAssessment() {
    // Implementation for loading risk assessment data
    console.log('Loading risk assessment...');
}

// Helper functions for notifications
function showLoading(message) {
    // Show loading indicator
    console.log('Loading:', message);
}

function hideLoading() {
    // Hide loading indicator
    console.log('Loading hidden');
}

function showSuccess(message) {
    // Show success message with toast notification
    showNotification({
        type: 'success',
        title: 'Success',
        message: message,
        icon: 'fas fa-check-circle',
        duration: 5000
    });
}

function showError(message) {
    // Show error message with toast notification
    showNotification({
        type: 'error',
        title: 'Error',
        message: message,
        icon: 'fas fa-exclamation-circle',
        duration: 7000
    });
}

// Show notification function
function showNotification(notification) {
    // Clear any existing timeout
    if (window.notificationTimeout) {
        clearTimeout(window.notificationTimeout);
    }
    
    const container = document.getElementById('notificationContainer');
    if (!container) return;
    
    // Create notification element
    const notificationEl = document.createElement('div');
    notificationEl.className = `toast show mb-2`;
    notificationEl.style.minWidth = '350px';
    
    // Determine background color based on type
    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>Just now</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>
    `;
    
    // Add to container
    container.appendChild(notificationEl);
    
    // Auto-hide after duration
    if (notification.duration > 0) {
        window.notificationTimeout = setTimeout(() => {
            if (notificationEl.parentElement) {
                notificationEl.remove();
            }
        }, notification.duration);
    }
}

// Show loading state for buttons
function setLoadingState(buttonId, isLoading) {
    const button = document.getElementById(buttonId);
    if (!button) return;
    
    if (isLoading) {
        button.disabled = true;
        const originalHtml = button.innerHTML;
        button.setAttribute('data-original-html', originalHtml);
        button.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Processing...';
    } else {
        button.disabled = false;
        const originalHtml = button.getAttribute('data-original-html');
        if (originalHtml) {
            button.innerHTML = originalHtml;
        }
    }
}

// Refresh analysis
function refreshAnalysis() {
    loadAnalyticsData();
}

// Load AI Control Panel
async function loadControlPanel() {
    try {
        const response = await fetch('ajax/get_control_panel_status.php');
        const data = await response.json();
        
        if (data.success) {
            displayControlPanel(data.status, data.system_ready);
            
            // Auto-open the control panel after 2 seconds
            setTimeout(() => {
                const modal = new bootstrap.Modal(document.getElementById('aiControlPanel'));
                modal.show();
                
                // Show welcome notification
                showNotification({
                    type: 'info',
                    title: 'AI Control Panel Ready',
                    message: 'Your AI system is ready for use. Check the control panel for system status.',
                    icon: 'fas fa-brain',
                    duration: 5000
                });
            }, 2000);
        } else {
            console.error('Failed to load control panel:', data.message);
        }
    } catch (error) {
        console.error('Error loading control panel:', error);
        showNotification({
            type: 'error',
            title: 'Error',
            message: 'Could not load AI control panel',
            icon: 'fas fa-exclamation-circle',
            duration: 5000
        });
    }
}

// Display Control Panel Content
function displayControlPanel(status, systemReady) {
    const content = document.getElementById('controlPanelContent');
    
    let statusClass = systemReady ? 'success' : 'warning';
    let statusText = systemReady ? 'Ready' : 'Needs Setup';
    
    content.innerHTML = `
        <div class="row">
            <div class="col-md-8">
                <div class="card mb-4">
                    <div class="card-header bg-${statusClass} text-white">
                        <h6 class="mb-0"><i class="fas fa-server me-2"></i>System Status: ${statusText}</h6>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-sm-6 mb-3">
                                <div class="d-flex align-items-center">
                                    <i class="fas fa-database me-2 text-${status.tables_exist ? 'success' : 'danger'}"></i>
                                    <span>Databases: ${status.tables_exist ? '✓ Configured' : '✗ Missing'}</span>
                                </div>
                            </div>
                            <div class="col-sm-6 mb-3">
                                <div class="d-flex align-items-center">
                                    <i class="fas fa-chart-line me-2 text-${status.data_available ? 'success' : 'warning'}"></i>
                                    <span>Data: ${status.data_available ? '✓ Sufficient' : '⚠ Insufficient'}</span>
                                </div>
                            </div>
                            <div class="col-sm-6 mb-3">
                                <div class="d-flex align-items-center">
                                    <i class="fas fa-magic me-2 text-info"></i>
                                    <span>Predictions: ${status.predictions_count}</span>
                                </div>
                            </div>
                            <div class="col-sm-6 mb-3">
                                <div class="d-flex align-items-center">
                                    <i class="fas fa-lightbulb me-2 text-warning"></i>
                                    <span>Recommendations: ${status.recommendations_count} pending</span>
                                </div>
                            </div>
                        </div>
                        
                        ${status.last_update ? 
                            `<small class="text-muted">Last update: ${new Date(status.last_update).toLocaleString()}</small>` : 
                            '<small class="text-muted">No recent activity</small>'
                        }
                    </div>
                </div>
                
                <div class="card">
                    <div class="card-header">
                        <h6 class="mb-0"><i class="fas fa-tools me-2"></i>Quick Actions</h6>
                    </div>
                    <div class="card-body">
                        <div class="d-grid gap-2">
                            ${!status.tables_exist ? 
                                `<button class="btn btn-primary" onclick="setupDatabase()">
                                    <i class="fas fa-cogs me-2"></i>Setup AI Database
                                </button>` : ''
                            }
                            
                            ${status.data_available ? 
                                `<button class="btn btn-success" onclick="runFullAnalysis()">
                                    <i class="fas fa-bolt me-2"></i>Run Full AI Analysis
                                </button>` : 
                                `<button class="btn btn-outline-secondary" disabled>
                                    <i class="fas fa-exclamation-circle me-2"></i>Need More Data
                                </button>`
                            }
                            
                            <button class="btn btn-info" onclick="viewAllPredictions()">
                                <i class="fas fa-chart-bar me-2"></i>View Predictions
                            </button>
                            
                            <button class="btn btn-warning" onclick="viewRecommendations()">
                                <i class="fas fa-lightbulb me-2"></i>View Recommendations
                            </button>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="col-md-4">
                <div class="card">
                    <div class="card-header bg-dark text-white">
                        <h6 class="mb-0"><i class="fas fa-chart-pie me-2"></i>AI Metrics</h6>
                    </div>
                    <div class="card-body text-center">
                        <canvas id="aiMetricsChart" width="200" height="200"></canvas>
                        <div class="mt-3">
                            <div class="badge bg-primary p-2">Accuracy: 92%</div>
                            <div class="badge bg-success p-2 mt-2">Confidence: High</div>
                        </div>
                    </div>
                </div>
                
                <div class="card mt-3">
                    <div class="card-header">
                        <h6 class="mb-0"><i class="fas fa-bell me-2"></i>Recent Activity</h6>
                    </div>
                    <div class="card-body p-2">
                        <ul class="list-group list-group-flush">
                            <li class="list-group-item p-2 border-0">
                                <small class="text-muted">System initialized</small>
                            </li>
                            ${status.predictions_count > 0 ? 
                                `<li class="list-group-item p-2 border-0">
                                    <small class="text-success">Generated ${status.predictions_count} predictions</small>
                                </li>` : ''
                            }
                            ${status.risk_assessments_count > 0 ? 
                                `<li class="list-group-item p-2 border-0">
                                    <small class="text-warning">${status.risk_assessments_count} risk assessments today</small>
                                </li>` : ''
                            }
                        </ul>
                    </div>
                </div>
            </div>
        </div>
    `;
    
    // Initialize chart if data is available
    if (status.predictions_count > 0 || status.recommendations_count > 0) {
        initAIMetricsChart(status);
    }
}

// Initialize AI Metrics Chart
function initAIMetricsChart(status) {
    const ctx = document.getElementById('aiMetricsChart');
    if (ctx) {
        new Chart(ctx, {
            type: 'doughnut',
            data: {
                labels: ['Predictions', 'Recommendations', 'Risk Assessments'],
                datasets: [{
                    data: [
                        status.predictions_count,
                        status.recommendations_count,
                        status.risk_assessments_count
                    ],
                    backgroundColor: [
                        '#0d6efd',
                        '#ffc107',
                        '#dc3545'
                    ]
                }]
            },
            options: {
                responsive: true,
                plugins: {
                    legend: {
                        position: 'bottom'
                    }
                }
            }
        });
    }
}

// Refresh Control Panel
async function refreshControlPanel() {
    const content = document.getElementById('controlPanelContent');
    content.innerHTML = `
        <div class="text-center py-5">
            <i class="fas fa-spinner fa-spin fa-2x text-primary"></i>
            <p class="mt-3">Refreshing AI system status...</p>
        </div>
    `;
    
    await loadControlPanel();
    showNotification({
        type: 'success',
        title: 'Refreshed',
        message: 'AI control panel updated',
        icon: 'fas fa-sync-alt',
        duration: 3000
    });
}

// Quick Action Functions
async function setupDatabase() {
    if (confirm('This will create all necessary AI database tables. Continue?')) {
        showNotification({
            type: 'info',
            title: 'Setting up...',
            message: 'Creating AI database tables',
            icon: 'fas fa-cogs',
            duration: 3000
        });
        
        try {
            const formData = new FormData();
            formData.append('action', 'setup_database');
            
            const response = await fetch('ajax/ai_controller.php', {
                method: 'POST',
                body: formData
            });
            
            const data = await response.json();
            
            if (data.success) {
                showNotification({
                    type: 'success',
                    title: 'Success',
                    message: 'AI database setup completed!',
                    icon: 'fas fa-check-circle',
                    duration: 5000
                });
                setTimeout(() => refreshControlPanel(), 1500);
            } else {
                showNotification({
                    type: 'error',
                    title: 'Error',
                    message: data.message,
                    icon: 'fas fa-exclamation-circle',
                    duration: 5000
                });
            }
        } catch (error) {
            showNotification({
                type: 'error',
                title: 'Error',
                message: 'Failed to setup database: ' + error.message,
                icon: 'fas fa-exclamation-circle',
                duration: 5000
            });
        }
    }
}

async function runFullAnalysis() {
    showNotification({
        type: 'info',
        title: 'Starting...',
        message: 'Running full AI analysis',
        icon: 'fas fa-bolt',
        duration: 3000
    });
    
    try {
        const formData = new FormData();
        formData.append('action', 'predict_performance');
        
        const response = await fetch('ajax/ai_controller.php', {
            method: 'POST',
            body: formData
        });
        
        const data = await response.json();
        
        if (data.success) {
            showNotification({
                type: 'success',
                title: 'Analysis Complete',
                message: 'AI analysis finished successfully',
                icon: 'fas fa-check-circle',
                duration: 5000
            });
            setTimeout(() => refreshControlPanel(), 1500);
        } else {
            showNotification({
                type: 'error',
                title: 'Error',
                message: data.message,
                icon: 'fas fa-exclamation-circle',
                duration: 5000
            });
        }
    } catch (error) {
        showNotification({
            type: 'error',
            title: 'Error',
            message: 'Analysis failed: ' + error.message,
            icon: 'fas fa-exclamation-circle',
            duration: 5000
        });
    }
}

function viewAllPredictions() {
    window.location.href = 'predictions.php';
}

function viewRecommendations() {
    window.location.href = 'recommendations.php';
}

// Modify the DOMContentLoaded event to include control panel loading
document.addEventListener('DOMContentLoaded', function() {
    loadAnalyticsData();
    loadControlPanel(); // Load AI control panel
});
</script>

<?php include '../includes/footer.php'; ?>