<?php

/**

 * AI Helpers - Safely load AI features with error handling

 */



function initAIFeatures() {

    static $initialized = false;

    

    if ($initialized) return true;

    

    // Check if AI files exist

    $requiredFiles = [

        'ai_config.php',

        'ai_model.php',

        'ai_predictor.php',

        'ai_recommendations.php'

    ];

    

    foreach ($requiredFiles as $file) {

        if (!file_exists(__DIR__ . '/' . $file)) {

            error_log("AI file missing: $file");

            return false;

        }

        require_once __DIR__ . '/' . $file;

    }

    

    $initialized = true;

    return true;

}



function getAIPredictor() {

    if (!initAIFeatures()) return null;

    

    try {

        return new AIPaymentPredictor();

    } catch (Exception $e) {

        error_log("Failed to initialize AI Predictor: " . $e->getMessage());

        return null;

    }

}



function getAIRecommendations() {

    if (!initAIFeatures()) return null;

    

    try {

        return new AIRecommendations();

    } catch (Exception $e) {

        error_log("Failed to initialize AI Recommendations: " . $e->getMessage());

        return null;

    }

}



function getAITrainer() {

    if (!initAIFeatures()) return null;

    

    try {

        return new AITrainer();

    } catch (Exception $e) {

        error_log("Failed to initialize AI Trainer: " . $e->getMessage());

        return null;

    }

}



// Safe wrapper for at-risk students

function getAtRiskStudentsSafe($limit = 5) {

    $predictor = getAIPredictor();

    if (!$predictor) return [];

    

    try {

        $atRisk = $predictor->identifyAtRiskStudents();

        return array_slice($atRisk, 0, $limit);

    } catch (Exception $e) {

        error_log("Failed to get at-risk students: " . $e->getMessage());

        return [];

    }

}



// Safe wrapper for revenue forecast

function getRevenueForecastSafe($months = 3) {

    $predictor = getAIPredictor();

    if (!$predictor) return null;

    

    try {

        return $predictor->predictMonthlyRevenue($months);

    } catch (Exception $e) {

        error_log("Failed to get revenue forecast: " . $e->getMessage());

        return null;

    }

}



// Safe wrapper for dashboard recommendations

function getDashboardRecommendationsSafe() {

    $recommendations = getAIRecommendations();

    if (!$recommendations) return [];

    

    try {

        return $recommendations->getDashboardRecommendations();

    } catch (Exception $e) {

        error_log("Failed to get dashboard recommendations: " . $e->getMessage());

        return [];

    }

}



// Safe wrapper for getting reminders count

function getTodayRemindersCount() {

    $conn = getDBConnection();

    if (!$conn) return 0;

    

    $query = "SELECT COUNT(*) as count 

              FROM fee_structures fs

              JOIN students s ON s.class = fs.class_name

              WHERE fs.due_date = CURDATE()

              AND s.status = 'active'

              AND NOT EXISTS (

                  SELECT 1 FROM payments p 

                  WHERE p.student_id = s.id 

                  AND p.fee_structure_id = fs.id

              )";

    

    $result = $conn->query($query);

    if ($result && $row = $result->fetch_assoc()) {

        return $row['count'];

    }

    

    return 0;

}