<?php
// Notification System for AI Tools
class AINotificationSystem {
    
    public static function showMessage($type, $message, $title = '', $duration = 5000) {
        $icons = [
            'success' => 'fas fa-check-circle',
            'error' => 'fas fa-exclamation-circle',
            'warning' => 'fas fa-exclamation-triangle',
            'info' => 'fas fa-info-circle',
            'loading' => 'fas fa-spinner fa-spin'
        ];
        
        $colors = [
            'success' => '#28a745',
            'error' => '#dc3545',
            'warning' => '#ffc107',
            'info' => '#17a2b8',
            'loading' => '#007bff'
        ];
        
        $icon = $icons[$type] ?? $icons['info'];
        $color = $colors[$type] ?? $colors['info'];
        
        return [
            'type' => $type,
            'message' => $message,
            'title' => $title ?: self::getDefaultTitle($type),
            'icon' => $icon,
            'color' => $color,
            'duration' => $duration
        ];
    }
    
    private static function getDefaultTitle($type) {
        $titles = [
            'success' => 'Success!',
            'error' => 'Error Occurred',
            'warning' => 'Warning',
            'info' => 'Information',
            'loading' => 'Processing...'
        ];
        return $titles[$type] ?? 'Notification';
    }
    
    // Specific notification templates
    public static function setupSuccess() {
        return self::showMessage('success', 
            'AI Performance Analyzer tables created successfully! You can now generate predictions and recommendations.',
            'Setup Complete',
            7000
        );
    }
    
    public static function setupAlreadyExists() {
        return self::showMessage('info',
            'AI tables already exist. No setup needed.',
            'Already Configured'
        );
    }
    
    public static function setupFailed($errorMessage) {
        return self::showMessage('error',
            'Setup failed: ' . $errorMessage . '. Please check database permissions and try again.',
            'Setup Failed',
            8000
        );
    }
    
    public static function predictionsGenerated($count) {
        return self::showMessage('success',
            "Successfully generated {$count} AI predictions for your students!",
            'Predictions Ready',
            6000
        );
    }
    
    public static function predictionsFailed($reason) {
        return self::showMessage('error',
            'Prediction generation failed: ' . $reason,
            'Prediction Error',
            7000
        );
    }
    
    public static function recommendationsGenerated($count, $breakdown) {
        $details = "Study Tips: {$breakdown['study_tips']}, Focus Areas: {$breakdown['focus_areas']}, Strategies: {$breakdown['improvement_strategies']}, Warnings: {$breakdown['warnings']}";
        
        return self::showMessage('success',
            "Generated {$count} personalized recommendations! {$details}",
            'Recommendations Ready',
            7000
        );
    }
    
    public static function riskAssessmentComplete($total, $riskBreakdown) {
        $highRisk = $riskBreakdown['critical'] + $riskBreakdown['high'];
        return self::showMessage('warning',
            "Risk assessment complete for {$total} students. {$highRisk} students require immediate attention.",
            'Risk Assessment Complete',
            8000
        );
    }
    
    public static function insufficientData($current, $required) {
        return self::showMessage('warning',
            "Insufficient data for analysis. Found {$current} records, need at least {$required}. Please add more student results.",
            'Data Insufficient',
            10000
        );
    }
    
    public static function noActiveStudents() {
        return self::showMessage('warning',
            'No active students found with result data. Please ensure students are marked as active and have entered results.',
            'No Students Found'
        );
    }
    
    public static function noSessionData() {
        return self::showMessage('warning',
            'No session data available for analysis. Please ensure exam results are entered with proper session information.',
            'Missing Session Data'
        );
    }
    
    public static function authError() {
        return self::showMessage('error',
            'Authentication required. Please login to access AI tools.',
            'Access Denied'
        );
    }
    
    public static function invalidAction($action) {
        return self::showMessage('error',
            "Invalid action requested: {$action}. Please use valid AI tool functions.",
            'Invalid Request'
        );
    }
    
    public static function loadingMessage($process) {
        $messages = [
            'setup' => 'Setting up AI database tables...',
            'predictions' => 'Generating AI performance predictions...',
            'recommendations' => 'Creating personalized recommendations...',
            'risk_assessment' => 'Running student risk assessment...',
            'analytics' => 'Loading performance analytics...'
        ];
        
        return self::showMessage('loading',
            $messages[$process] ?? 'Processing request...',
            'Please Wait'
        );
    }
    
    public static function dataQualityWarning($issue) {
        return self::showMessage('warning',
            "Data quality issue detected: {$issue}. Results may be less accurate than expected.",
            'Data Quality Warning',
            8000
        );
    }
    
    public static function systemMaintenance() {
        return self::showMessage('info',
            'AI system is currently being updated. Some features may be temporarily unavailable.',
            'Maintenance Notice',
            10000
        );
    }
}

// Error Handler for AI Operations
class AIErrorHandler {
    
    public static function handleError($exception) {
        $errorType = $exception->getCode();
        $errorMessage = $exception->getMessage();
        
        error_log("AI Error [{$errorType}]: {$errorMessage}");
        
        switch ($errorType) {
            case 'auth_error':
                return AINotificationSystem::authError();
                
            case 'validation_error':
                return AINotificationSystem::showMessage('error', $errorMessage, 'Validation Error');
                
            case 'database_error':
                return AINotificationSystem::showMessage('error', 
                    'Database error occurred. Please contact administrator.', 
                    'Database Error', 
                    8000
                );
                
            case 'insufficient_data':
                return AINotificationSystem::insufficientData(
                    self::extractNumber($errorMessage, 0),
                    self::extractNumber($errorMessage, 10)
                );
                
            case 'no_students_found':
                return AINotificationSystem::noActiveStudents();
                
            case 'no_session_data':
                return AINotificationSystem::noSessionData();
                
            case 'prediction_error':
                return AINotificationSystem::predictionsFailed($errorMessage);
                
            case 'recommendation_error':
                return AINotificationSystem::showMessage('error', 
                    'Failed to generate recommendations: ' . $errorMessage,
                    'Recommendation Error'
                );
                
            case 'risk_assessment_error':
                return AINotificationSystem::showMessage('error',
                    'Risk assessment failed: ' . $errorMessage,
                    'Assessment Error'
                );
                
            case 'analytics_error':
                return AINotificationSystem::showMessage('error',
                    'Unable to load analytics: ' . $errorMessage,
                    'Analytics Error'
                );
                
            default:
                return AINotificationSystem::showMessage('error',
                    'An unexpected error occurred: ' . $errorMessage,
                    'System Error',
                    8000
                );
        }
    }
    
    private static function extractNumber($message, $default) {
        preg_match('/(\d+)/', $message, $matches);
        return isset($matches[1]) ? (int)$matches[1] : $default;
    }
}

// Success Handler for AI Operations
class AISuccessHandler {
    
    public static function handleSuccess($action, $data) {
        switch ($action) {
            case 'setup_database':
                if ($data['tables_created'] > 0) {
                    return AINotificationSystem::setupSuccess();
                } else {
                    return AINotificationSystem::setupAlreadyExists();
                }
                
            case 'generate_predictions':
                return AINotificationSystem::predictionsGenerated($data['predictions_count']);
                
            case 'generate_recommendations':
                return AINotificationSystem::recommendationsGenerated(
                    $data['total_generated'],
                    $data['breakdown']
                );
                
            case 'assess_risk':
                return AINotificationSystem::riskAssessmentComplete(
                    $data['assessments_count'],
                    $data['risk_breakdown']
                );
                
            case 'load_analytics':
                return AINotificationSystem::showMessage('success',
                    'Analytics data loaded successfully',
                    'Data Ready'
                );
                
            default:
                return AINotificationSystem::showMessage('success',
                    'Operation completed successfully',
                    'Success'
                );
        }
    }
}
?>