<?php

/**

 * AI Analytics — ML-based payment predictions and at-risk student identification.

 * This page was formerly ai_dashboard.php; now accessible from the AI Analytics sidebar link.

 */

if (session_status() === PHP_SESSION_NONE) {

    session_start();

}



if (!isset($_SESSION['user_id'])) {

    header('Location: index.php');

    exit;

}



$allowed_roles = ['admin', 'accountant', 'director', 'supervisor', 'headteacher'];

if (!in_array($_SESSION['role'], $allowed_roles)) {

    header('Location: dashboard.php?error=access_denied');

    exit;

}



require_once 'config.php';

requireModule('ai_analytics');

require_once 'ai_config.php';



$conn = getDBConnection();



$predictor       = new AIPaymentPredictor();

$recommendations = new AIRecommendations();

$trainer         = new AITrainer();



$trainingMessage     = '';

$trainingMessageType = '';



if (isset($_POST['train_model'])) {

    $result = $trainer->trainPaymentPredictorDirect(true);

    if ($result['status'] === 'success') {

        $trainingMessage     = 'Model trained successfully with ' . $result['samples'] . ' samples. Accuracy: ' . round($result['accuracy'] * 100, 1) . '%';

        $trainingMessageType = 'success';

    } elseif ($result['status'] === 'skipped') {

        $trainingMessage     = 'Model training skipped: ' . $result['message'];

        $trainingMessageType = 'info';

    } else {

        $trainingMessage     = 'Training failed: ' . $result['message'];

        $trainingMessageType = 'danger';

    }

}



try {

    $revenueForecast          = $predictor->predictMonthlyRevenue(6);

    $atRiskStudents           = $predictor->identifyAtRiskStudents();

    $dashboardRecommendations = $recommendations->getDashboardRecommendations();

    $trainingStats            = $trainer->getTrainingStats();

    $modelMetrics             = (new AIPaymentPredictor())->getPerformanceMetrics();

} catch (Exception $e) {

    $revenueForecast          = ['forecast' => [0,0,0,0,0,0], 'total_expected' => 0, 'confidence_interval' => ['lower_bound' => 0, 'upper_bound' => 0], 'based_on_months' => 0, 'generated_at' => date('Y-m-d H:i:s')];

    $atRiskStudents           = [];

    $dashboardRecommendations = [];

    $trainingStats            = [];

    $modelMetrics             = ['is_trained' => false, 'accuracy' => 0, 'version' => '1.0', 'last_training' => null];

}



$totalStudents = 0;

$result = $conn->query("SELECT COUNT(*) as count FROM students WHERE status = 'active'");

if ($result) {

    $totalStudents = (int) $result->fetch_assoc()['count'];

}

?>

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>AI Analytics - EduTrack PRO</title>

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">

    <link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap5.min.css">

    <link rel="stylesheet" href="css/style.css">

    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

    <style>

        .ai-stat-card{background:white;border-radius:10px;padding:20px;box-shadow:0 2px 10px rgba(0,0,0,.1);transition:transform .3s,box-shadow .3s;height:100%;display:flex;flex-direction:column}

        .ai-stat-card:hover{transform:translateY(-5px);box-shadow:0 5px 20px rgba(0,0,0,.15)}

        .ai-stat-icon{width:50px;height:50px;border-radius:10px;display:flex;align-items:center;justify-content:center;margin-bottom:15px;font-size:24px}

        .ai-stat-icon.primary{background:#e8f4fd;color:#3498db}.ai-stat-icon.success{background:#d4edda;color:#27ae60}

        .ai-stat-icon.warning{background:#fff3cd;color:#f39c12}.ai-stat-icon.danger{background:#f8d7da;color:#e74c3c}

        .ai-stat-icon.info{background:#d1ecf1;color:#17a2b8}

        .ai-stat-value{font-size:28px;font-weight:bold;color:#2c3e50;margin-bottom:5px}

        .ai-stat-label{color:#7f8c8d;font-size:14px;margin-bottom:0}

        .risk-badge{padding:5px 12px;border-radius:20px;font-size:12px;font-weight:600;display:inline-block}

        .risk-critical{background:#f8d7da;color:#721c24}.risk-high{background:#fff3cd;color:#856404}

        .risk-medium{background:#d1ecf1;color:#0c5460}.risk-low{background:#d4edda;color:#155724}

        .recommendation-item{border-left:4px solid;padding:15px;margin-bottom:10px;background:white;border-radius:5px;box-shadow:0 1px 3px rgba(0,0,0,.1);transition:transform .2s}

        .recommendation-item:hover{transform:translateX(5px)}

        .recommendation-high{border-left-color:#e74c3c}.recommendation-medium{border-left-color:#f39c12}.recommendation-low{border-left-color:#3498db}

        .progress-sm{height:8px;border-radius:4px}

        .model-status-badge{padding:3px 10px;border-radius:15px;font-size:11px;font-weight:600}

        .status-active{background:#d4edda;color:#155724}.status-inactive{background:#f8d7da;color:#721c24}

    </style>

</head>

<body>

<div class="wrapper">

    <nav id="sidebar" class="sidebar">

        <?php echo buildSidebar(basename($_SERVER['PHP_SELF'])); ?>

        </nav>

    <div class="main-content">

        <header class="header">

            <button class="btn-toggle" id="sidebarToggle"><i class="fas fa-bars"></i></button>

            <div class="header-right">

                <div class="dropdown">

                    <button class="btn btn-link dropdown-toggle" type="button" data-bs-toggle="dropdown">

                        <i class="fas fa-user-circle me-2"></i><?php echo htmlspecialchars($_SESSION['full_name']); ?>

                    </button>

                    <ul class="dropdown-menu dropdown-menu-end">

                        <li><a class="dropdown-item" href="settings.php"><i class="fas fa-cog me-2"></i>Settings</a></li>

                        <li><hr class="dropdown-divider"></li>

                        <li><a class="dropdown-item" href="logout.php"><i class="fas fa-sign-out-alt me-2"></i>Logout</a></li>

                    </ul>

                </div>

            </div>

        </header>

        <main class="content">

            <div class="content-header">

                <h2><i class="fas fa-robot me-2"></i>AI Analytics Dashboard</h2>

                <p>Intelligent predictions and insights powered by machine learning</p>

            </div>



            <?php if ($trainingMessage): ?>

            <div class="alert alert-<?php echo $trainingMessageType; ?> alert-dismissible fade show">

                <?php echo htmlspecialchars($trainingMessage); ?>

                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>

            </div>

            <?php endif; ?>



            <!-- Model Status -->

            <div class="row mb-4">

                <div class="col-12">

                    <div class="ai-stat-card">

                        <div class="d-flex justify-content-between align-items-center mb-3">

                            <h5 class="mb-0"><i class="fas fa-microchip me-2 text-primary"></i>AI Model Status</h5>

                            <div>

                                <span class="model-status-badge <?php echo $modelMetrics['is_trained'] ? 'status-active' : 'status-inactive'; ?> me-2">

                                    <i class="fas fa-<?php echo $modelMetrics['is_trained'] ? 'check-circle' : 'exclamation-circle'; ?> me-1"></i>

                                    <?php echo $modelMetrics['is_trained'] ? 'Active' : 'Learning'; ?>

                                </span>

                                <form method="POST" style="display:inline;">

                                    <button type="submit" name="train_model" class="btn btn-sm btn-primary">

                                        <i class="fas fa-sync-alt me-1"></i>Retrain

                                    </button>

                                </form>

                            </div>

                        </div>

                        <div class="row">

                            <div class="col-md-3"><div class="ai-stat-value"><?php echo round($modelMetrics['accuracy'] * 100, 1); ?>%</div><div class="ai-stat-label">Prediction Accuracy</div></div>

                            <div class="col-md-3"><div class="ai-stat-value">v<?php echo $modelMetrics['version']; ?></div><div class="ai-stat-label">Model Version</div></div>

                            <div class="col-md-3"><div class="ai-stat-value"><?php echo $modelMetrics['last_training'] ? date('d M Y', strtotime($modelMetrics['last_training'])) : 'Never'; ?></div><div class="ai-stat-label">Last Training</div></div>

                            <div class="col-md-3"><div class="ai-stat-value"><?php echo count($atRiskStudents); ?></div><div class="ai-stat-label">At-Risk Students</div></div>

                        </div>

                    </div>

                </div>

            </div>



            <!-- Key Metrics -->

            <div class="row mb-4">

                <div class="col-md-3">

                    <div class="ai-stat-card"><div class="ai-stat-icon warning"><i class="fas fa-exclamation-triangle"></i></div>

                    <div class="ai-stat-value"><?php echo count($atRiskStudents); ?></div><div class="ai-stat-label">Students at Risk</div><small class="text-muted">High probability of late payment</small></div>

                </div>

                <div class="col-md-3">

                    <div class="ai-stat-card"><div class="ai-stat-icon success"><i class="fas fa-chart-line"></i></div>

                    <div class="ai-stat-value"><?php echo formatCurrency($revenueForecast['total_expected']); ?></div><div class="ai-stat-label">6-Month Forecast</div><small class="text-muted">Expected revenue</small></div>

                </div>

                <div class="col-md-3">

                    <div class="ai-stat-card"><div class="ai-stat-icon primary"><i class="fas fa-calendar-check"></i></div>

                    <div class="ai-stat-value"><?php echo formatCurrency($revenueForecast['forecast'][0] ?? 0); ?></div><div class="ai-stat-label">Next Month Expected</div><small class="text-muted"><?php echo date('F Y'); ?></small></div>

                </div>

                <div class="col-md-3">

                    <div class="ai-stat-card"><div class="ai-stat-icon info"><i class="fas fa-users"></i></div>

                    <div class="ai-stat-value"><?php echo $totalStudents; ?></div><div class="ai-stat-label">Total Students</div><small class="text-muted">Active enrollment</small></div>

                </div>

            </div>



            <!-- Revenue Chart -->

            <div class="row mb-4">

                <div class="col-lg-8">

                    <div class="card"><div class="card-header"><h5 class="mb-0"><i class="fas fa-chart-line me-2 text-primary"></i>Revenue Forecast (Next 6 Months)</h5></div>

                    <div class="card-body" style="height:320px"><canvas id="revenueChart"></canvas></div></div>

                </div>

                <div class="col-lg-4">

                    <div class="card"><div class="card-header"><h5 class="mb-0"><i class="fas fa-info-circle me-2 text-info"></i>Forecast Details</h5></div>

                    <div class="card-body">

                        <div class="mb-3"><label class="text-muted mb-1">Confidence Interval</label>

                        <div class="progress progress-sm mb-2"><div class="progress-bar bg-info" style="width:95%"></div></div>

                        <div class="d-flex justify-content-between small">

                            <span>₵<?php echo number_format($revenueForecast['confidence_interval']['lower_bound'], 0); ?></span>

                            <span>₵<?php echo number_format($revenueForecast['confidence_interval']['upper_bound'], 0); ?></span>

                        </div></div>

                        <hr>

                        <div class="mb-2"><span class="text-muted">Based on:</span><span class="float-end fw-bold"><?php echo $revenueForecast['based_on_months']; ?> months</span></div>

                        <div><span class="text-muted">Model Confidence:</span><span class="float-end fw-bold text-success">95%</span></div>

                    </div></div>

                </div>

            </div>



            <!-- At-Risk Students Table -->

            <div class="row">

                <div class="col-12">

                    <div class="card"><div class="card-header"><h5 class="mb-0"><i class="fas fa-exclamation-triangle me-2 text-danger"></i>Students at Risk of Late Payment</h5></div>

                    <div class="card-body">

                        <table class="table table-hover" id="atRiskTable">

                            <thead><tr><th>ID</th><th>Name</th><th>Class</th><th>Risk Level</th><th>Probability</th><th>Actions</th></tr></thead>

                            <tbody>

                            <?php if (empty($atRiskStudents)): ?>

                                <tr><td colspan="6" class="text-center py-4"><i class="fas fa-check-circle text-success fa-3x mb-3"></i><h5>No At-Risk Students Found</h5></td></tr>

                            <?php else: ?>

                                <?php foreach (array_slice($atRiskStudents, 0, 20) as $s): ?>

                                <tr>

                                    <td><code><?php echo htmlspecialchars($s['student']['student_id'] ?? ''); ?></code></td>

                                    <td><strong><?php echo htmlspecialchars(($s['student']['first_name'] ?? '') . ' ' . ($s['student']['last_name'] ?? '')); ?></strong></td>

                                    <td><?php echo htmlspecialchars($s['student']['class'] ?? ''); ?></td>

                                    <td><span class="risk-badge risk-<?php echo strtolower($s['risk_level'] ?? 'low'); ?>"><?php echo $s['risk_level'] ?? 'Low'; ?></span></td>

                                    <td><?php echo $s['probability'] ?? 0; ?>%</td>

                                    <td>

                                        <a href="students.php?action=view&id=<?php echo $s['student']['id'] ?? 0; ?>" class="btn btn-sm btn-info"><i class="fas fa-eye"></i></a>

                                    </td>

                                </tr>

                                <?php endforeach; ?>

                            <?php endif; ?>

                            </tbody>

                        </table>

                    </div></div>

                </div>

            </div>

        </main>

        <footer class="footer"><p>&copy; 2024 EduTrack PRO. All rights reserved.</p></footer>

    </div>

</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>

<script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>

<script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>

<script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap5.min.js"></script>

<script src="js/main.js"></script>

<script>

$(document).ready(function(){ $('#atRiskTable').DataTable({pageLength:10,order:[[3,'desc']]}); });

const ctx = document.getElementById('revenueChart').getContext('2d');

new Chart(ctx,{type:'line',data:{labels:['Month 1','Month 2','Month 3','Month 4','Month 5','Month 6'],

datasets:[{label:'Predicted Revenue',data:<?php echo json_encode($revenueForecast['forecast']); ?>,

borderColor:'#3498db',backgroundColor:'rgba(52,152,219,.1)',borderWidth:2,tension:.1,fill:true}]},

options:{responsive:true,maintainAspectRatio:false,plugins:{legend:{display:false}},

scales:{y:{beginAtZero:true,ticks:{callback:v=>'₵'+v.toLocaleString()}},x:{grid:{display:false}}}}});

</script>

</body>

</html>

