<?php
// AI Control Panel - Auto-opening dashboard widget
require_once '../config/database.php';
require_once '../includes/auth.php';

// Check authentication
if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit();
}

try {
    // Get AI system status
    $status = [
        'tables_exist' => false,
        'data_available' => false,
        'predictions_count' => 0,
        'recommendations_count' => 0,
        'risk_assessments_count' => 0,
        'last_update' => null
    ];
    
    // Check if AI tables exist
    $stmt = $pdo->query("SHOW TABLES LIKE 'ai_%'");
    $tables = $stmt->fetchAll();
    $status['tables_exist'] = count($tables) >= 5;
    
    if ($status['tables_exist']) {
        // Check data availability
        $stmt = $pdo->query("SELECT COUNT(*) FROM results WHERE marks_obtained IS NOT NULL");
        $result_count = $stmt->fetchColumn();
        $status['data_available'] = $result_count > 10;
        
        // Get counts
        $stmt = $pdo->query("SELECT COUNT(*) FROM ai_performance_predictions");
        $status['predictions_count'] = $stmt->fetchColumn();
        
        $stmt = $pdo->query("SELECT COUNT(*) FROM ai_recommendations WHERE status = 'pending'");
        $status['recommendations_count'] = $stmt->fetchColumn();
        
        $stmt = $pdo->query("SELECT COUNT(*) FROM ai_risk_assessments WHERE assessment_date = CURDATE()");
        $status['risk_assessments_count'] = $stmt->fetchColumn();
        
        // Get last update time
        $stmt = $pdo->query("SELECT MAX(created_at) FROM ai_performance_predictions");
        $status['last_update'] = $stmt->fetchColumn();
    }
    
    echo json_encode([
        'success' => true,
        'status' => $status,
        'system_ready' => $status['tables_exist'] && $status['data_available']
    ]);
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Error loading AI control panel: ' . $e->getMessage()
    ]);
}
?>