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

header('Content-Type: application/json');

// Check authentication
if (!isset($_SESSION['user_id'])) {
    echo json_encode([
        'success' => false, 
        'message' => 'Unauthorized access. Please login first.',
        'error_type' => 'auth_error'
    ]);
    exit();
}

$response = [
    'success' => false,
    'message' => '',
    'error_type' => 'unknown',
    'timestamp' => date('Y-m-d H:i:s')
];

try {
    // Validate required parameters
    if (!isset($_POST['action'])) {
        throw new Exception('No action specified', 'validation_error');
    }

    $action = $_POST['action'];
    
    switch ($action) {
        case 'setup_database':
            $response = setupDatabaseTables();
            break;
            
        case 'generate_predictions':
            $response = generatePredictions();
            break;
            
        case 'generate_recommendations':
            $response = generateRecommendations();
            break;
            
        case 'assess_risk':
            $response = assessRisk();
            break;
            
        case 'load_analytics':
            $response = loadAnalytics();
            break;
            
        default:
            throw new Exception('Invalid action specified: ' . $action, 'invalid_action');
    }

} catch (Exception $e) {
    $response = [
        'success' => false,
        'message' => $e->getMessage(),
        'error_type' => $e->getCode() ?: 'general_error',
        'timestamp' => date('Y-m-d H:i:s')
    ];
    
    // Log the error
    error_log("AI Tools Error: " . $e->getMessage() . " | Type: " . $response['error_type']);
}

echo json_encode($response);

// Setup database tables
function setupDatabaseTables() {
    global $pdo;
    
    try {
        // Check if tables already exist
        $stmt = $pdo->query("SHOW TABLES LIKE 'ai_%'");
        $existing_tables = $stmt->fetchAll();
        
        if (count($existing_tables) >= 5) {
            return [
                'success' => true,
                'message' => 'AI tables already exist. Setup not needed.',
                'action_required' => false,
                'tables_count' => count($existing_tables)
            ];
        }
        
        // Create tables (same as setup_ai_tables.php)
        $tables_created = 0;
        
        // AI performance predictions table
        $pdo->exec("
            CREATE TABLE IF NOT EXISTS ai_performance_predictions (
                id INT AUTO_INCREMENT PRIMARY KEY,
                student_id INT NOT NULL,
                subject_id INT NOT NULL,
                exam_type ENUM('midterm', 'final', 'test') NOT NULL,
                session VARCHAR(20) NOT NULL,
                predicted_grade VARCHAR(5),
                predicted_marks DECIMAL(5,2),
                confidence_score DECIMAL(3,2),
                analysis_date DATE NOT NULL,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                FOREIGN KEY (student_id) REFERENCES students(id) ON DELETE CASCADE,
                FOREIGN KEY (subject_id) REFERENCES subjects(id) ON DELETE CASCADE,
                INDEX idx_student_subject (student_id, subject_id),
                INDEX idx_session_exam (session, exam_type)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
        ");
        $tables_created++;
        
        // AI learning patterns table
        $pdo->exec("
            CREATE TABLE IF NOT EXISTS ai_learning_patterns (
                id INT AUTO_INCREMENT PRIMARY KEY,
                student_id INT NOT NULL,
                subject_id INT NOT NULL,
                pattern_type ENUM('improvement', 'decline', 'stable', 'volatile') NOT NULL,
                trend_slope DECIMAL(5,2),
                consistency_score DECIMAL(3,2),
                last_updated DATE NOT NULL,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                FOREIGN KEY (student_id) REFERENCES students(id) ON DELETE CASCADE,
                FOREIGN KEY (subject_id) REFERENCES subjects(id) ON DELETE CASCADE,
                INDEX idx_student_pattern (student_id, pattern_type)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
        ");
        $tables_created++;
        
        // AI recommendations table
        $pdo->exec("
            CREATE TABLE IF NOT EXISTS ai_recommendations (
                id INT AUTO_INCREMENT PRIMARY KEY,
                student_id INT NOT NULL,
                subject_id INT,
                recommendation_type ENUM('study_tips', 'focus_areas', 'improvement_strategies', 'warning') NOT NULL,
                priority ENUM('high', 'medium', 'low') DEFAULT 'medium',
                title VARCHAR(200) NOT NULL,
                description TEXT NOT NULL,
                suggested_action TEXT,
                generated_date DATE NOT NULL,
                status ENUM('pending', 'implemented', 'dismissed') DEFAULT 'pending',
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                FOREIGN KEY (student_id) REFERENCES students(id) ON DELETE CASCADE,
                FOREIGN KEY (subject_id) REFERENCES subjects(id) ON DELETE CASCADE,
                INDEX idx_student_rec (student_id, recommendation_type),
                INDEX idx_priority_status (priority, status)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
        ");
        $tables_created++;
        
        // AI dashboard analytics table
        $pdo->exec("
            CREATE TABLE IF NOT EXISTS ai_dashboard_analytics (
                id INT AUTO_INCREMENT PRIMARY KEY,
                class_id INT NOT NULL,
                session VARCHAR(20) NOT NULL,
                subject_id INT,
                metric_type ENUM('average_performance', 'pass_rate', 'top_performers', 'at_risk_students') NOT NULL,
                value DECIMAL(5,2),
                comparison_value DECIMAL(5,2),
                trend_direction ENUM('up', 'down', 'stable') DEFAULT 'stable',
                analysis_period DATE NOT NULL,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                FOREIGN KEY (class_id) REFERENCES classes(id) ON DELETE CASCADE,
                FOREIGN KEY (subject_id) REFERENCES subjects(id) ON DELETE CASCADE,
                INDEX idx_class_session (class_id, session),
                INDEX idx_metric_type (metric_type)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
        ");
        $tables_created++;
        
        // AI risk assessments table
        $pdo->exec("
            CREATE TABLE IF NOT EXISTS ai_risk_assessments (
                id INT AUTO_INCREMENT PRIMARY KEY,
                student_id INT NOT NULL,
                risk_level ENUM('low', 'medium', 'high', 'critical') NOT NULL,
                risk_factors JSON,
                overall_score DECIMAL(3,2),
                assessment_date DATE NOT NULL,
                next_review_date DATE,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                FOREIGN KEY (student_id) REFERENCES students(id) ON DELETE CASCADE,
                INDEX idx_student_risk (student_id, risk_level),
                INDEX idx_assessment_date (assessment_date)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
        ");
        $tables_created++;
        
        return [
            'success' => true,
            'message' => "Successfully created {$tables_created} AI database tables!",
            'action_required' => true,
            'next_steps' => [
                'Generate predictions for your students',
                'Create personalized recommendations',
                'Run risk assessments'
            ],
            'tables_created' => $tables_created
        ];
        
    } catch (Exception $e) {
        throw new Exception("Database setup failed: " . $e->getMessage(), 'database_error');
    }
}

// Generate predictions
function generatePredictions() {
    global $pdo;
    
    try {
        // Check if required data exists
        $stmt = $pdo->query("SELECT COUNT(*) FROM results WHERE marks_obtained IS NOT NULL");
        $data_count = $stmt->fetchColumn();
        
        if ($data_count < 10) {
            throw new Exception("Insufficient data for predictions. Need at least 10 result records, found {$data_count}.", 'insufficient_data');
        }
        
        // Get current session
        $stmt = $pdo->query("SELECT DISTINCT session FROM results ORDER BY session DESC LIMIT 1");
        $current_session = $stmt->fetchColumn();
        
        if (!$current_session) {
            throw new Exception("No session data found for predictions", 'no_session_data');
        }
        
        // Get students with recent results
        $stmt = $pdo->prepare("
            SELECT DISTINCT s.id, s.student_id, s.first_name, s.last_name
            FROM students s
            JOIN results r ON s.id = r.student_id
            WHERE s.status = 'active'
            ORDER BY s.id
            LIMIT 50
        ");
        $stmt->execute();
        $students = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        if (empty($students)) {
            throw new Exception("No active students found with result data", 'no_students_found');
        }
        
        $predictions_generated = 0;
        
        foreach ($students as $student) {
            // Get student's performance history
            $history_sql = "
                SELECT r.subject_id, r.marks_obtained, r.session
                FROM results r
                WHERE r.student_id = ? AND r.session <= ?
                ORDER BY r.session DESC
                LIMIT 8
            ";
            
            $stmt = $pdo->prepare($history_sql);
            $stmt->execute([$student['id'], $current_session]);
            $performance_history = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            if (count($performance_history) < 2) continue;
            
            // Get unique subjects
            $subjects = array_unique(array_column($performance_history, 'subject_id'));
            
            foreach ($subjects as $subject_id) {
                $subject_history = array_filter($performance_history, function($item) use ($subject_id) {
                    return $item['subject_id'] == $subject_id;
                });
                
                if (count($subject_history) < 2) continue;
                
                // Simple prediction algorithm
                $marks = array_column($subject_history, 'marks_obtained');
                $recent_marks = array_slice($marks, 0, 3);
                
                // Weighted average (more recent = higher weight)
                if (count($recent_marks) >= 3) {
                    $prediction = ($recent_marks[0] * 0.5) + ($recent_marks[1] * 0.3) + ($recent_marks[2] * 0.2);
                } elseif (count($recent_marks) == 2) {
                    $prediction = ($recent_marks[0] * 0.6) + ($recent_marks[1] * 0.4);
                } else {
                    $prediction = $recent_marks[0];
                }
                
                // Add realistic variance
                $variance = (mt_rand(-100, 100) / 100) * 5;
                $predicted_marks = max(0, min(100, round($prediction + $variance, 1)));
                
                // Calculate grade
                $predicted_grade = calculateGrade($predicted_marks);
                
                // Calculate confidence
                $confidence_score = calculateConfidence($subject_history);
                
                // Save prediction
                $insert_sql = "
                    INSERT INTO ai_performance_predictions 
                    (student_id, subject_id, exam_type, session, predicted_grade, predicted_marks, confidence_score, analysis_date)
                    VALUES (?, ?, 'final', ?, ?, ?, ?, CURDATE())
                    ON DUPLICATE KEY UPDATE 
                    predicted_grade = VALUES(predicted_grade),
                    predicted_marks = VALUES(predicted_marks),
                    confidence_score = VALUES(confidence_score),
                    analysis_date = CURDATE()
                ";
                
                $stmt = $pdo->prepare($insert_sql);
                $stmt->execute([
                    $student['id'], 
                    $subject_id, 
                    $current_session,
                    $predicted_grade, 
                    $predicted_marks, 
                    $confidence_score
                ]);
                
                $predictions_generated++;
            }
        }
        
        if ($predictions_generated == 0) {
            throw new Exception("No predictions could be generated. Check data quality.", 'prediction_failed');
        }
        
        return [
            'success' => true,
            'message' => "Successfully generated {$predictions_generated} AI predictions!",
            'predictions_count' => $predictions_generated,
            'session' => $current_session,
            'coverage' => round(($predictions_generated / (count($students) * count($subjects))) * 100, 1) . '%'
        ];
        
    } catch (Exception $e) {
        throw new Exception("Prediction generation failed: " . $e->getMessage(), 'prediction_error');
    }
}

// Generate recommendations
function generateRecommendations() {
    global $pdo;
    
    try {
        // Clear existing pending recommendations
        $deleted = $pdo->exec("DELETE FROM ai_recommendations WHERE status = 'pending'");
        
        // Generate different types of recommendations
        $study_tips = generateStudyTips();
        $focus_areas = generateFocusAreas();
        $improvement_strategies = generateImprovementStrategies();
        $warnings = generateWarnings();
        
        $total_recommendations = count($study_tips) + count($focus_areas) + count($improvement_strategies) + count($warnings);
        
        // Insert all recommendations
        $insert_sql = "
            INSERT INTO ai_recommendations 
            (student_id, subject_id, recommendation_type, priority, title, description, suggested_action, generated_date)
            VALUES (?, ?, ?, ?, ?, ?, ?, CURDATE())
        ";
        
        $stmt = $pdo->prepare($insert_sql);
        
        $inserted = 0;
        
        // Insert study tips
        foreach ($study_tips as $rec) {
            $stmt->execute([
                $rec['student_id'], $rec['subject_id'], 'study_tips', 
                $rec['priority'], $rec['title'], $rec['description'], $rec['suggested_action']
            ]);
            $inserted++;
        }
        
        // Insert focus areas
        foreach ($focus_areas as $rec) {
            $stmt->execute([
                $rec['student_id'], $rec['subject_id'], 'focus_areas',
                $rec['priority'], $rec['title'], $rec['description'], $rec['suggested_action']
            ]);
            $inserted++;
        }
        
        // Insert improvement strategies
        foreach ($improvement_strategies as $rec) {
            $stmt->execute([
                $rec['student_id'], $rec['subject_id'], 'improvement_strategies',
                $rec['priority'], $rec['title'], $rec['description'], $rec['suggested_action']
            ]);
            $inserted++;
        }
        
        // Insert warnings
        foreach ($warnings as $rec) {
            $stmt->execute([
                $rec['student_id'], $rec['subject_id'], 'warning',
                $rec['priority'], $rec['title'], $rec['description'], $rec['suggested_action']
            ]);
            $inserted++;
        }
        
        return [
            'success' => true,
            'message' => "Successfully generated {$inserted} personalized recommendations!",
            'breakdown' => [
                'study_tips' => count($study_tips),
                'focus_areas' => count($focus_areas),
                'improvement_strategies' => count($improvement_strategies),
                'warnings' => count($warnings)
            ],
            'total_generated' => $inserted
        ];
        
    } catch (Exception $e) {
        throw new Exception("Recommendation generation failed: " . $e->getMessage(), 'recommendation_error');
    }
}

// Risk assessment
function assessRisk() {
    global $pdo;
    
    try {
        // Clear today's assessments
        $deleted = $pdo->exec("DELETE FROM ai_risk_assessments WHERE assessment_date = CURDATE()");
        
        // Get all active students
        $stmt = $pdo->query("
            SELECT s.id, s.student_id, s.first_name, s.last_name
            FROM students s
            WHERE s.status = 'active'
            ORDER BY s.id
        ");
        $students = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        if (empty($students)) {
            throw new Exception("No active students found for risk assessment", 'no_students');
        }
        
        $assessments_completed = 0;
        
        foreach ($students as $student) {
            $risk_data = calculateStudentRisk($student['id']);
            
            if ($risk_data) {
                $insert_sql = "
                    INSERT INTO ai_risk_assessments 
                    (student_id, risk_level, risk_factors, overall_score, assessment_date, next_review_date)
                    VALUES (?, ?, ?, ?, CURDATE(), DATE_ADD(CURDATE(), INTERVAL 30 DAY))
                ";
                
                $stmt = $pdo->prepare($insert_sql);
                $stmt->execute([
                    $student['id'],
                    $risk_data['risk_level'],
                    json_encode($risk_data['risk_factors']),
                    $risk_data['overall_score']
                ]);
                
                $assessments_completed++;
            }
        }
        
        $risk_levels = [
            'critical' => 0,
            'high' => 0,
            'medium' => 0,
            'low' => 0
        ];
        
        // Count risk levels
        $stmt = $pdo->query("
            SELECT risk_level, COUNT(*) as count
            FROM ai_risk_assessments
            WHERE assessment_date = CURDATE()
            GROUP BY risk_level
        ");
        $risk_counts = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);
        
        foreach ($risk_counts as $level => $count) {
            $risk_levels[$level] = $count;
        }
        
        return [
            'success' => true,
            'message' => "Completed risk assessment for {$assessments_completed} students",
            'assessments_count' => $assessments_completed,
            'risk_breakdown' => $risk_levels,
            'high_risk_students' => $risk_levels['critical'] + $risk_levels['high']
        ];
        
    } catch (Exception $e) {
        throw new Exception("Risk assessment failed: " . $e->getMessage(), 'risk_assessment_error');
    }
}

// Load analytics
function loadAnalytics() {
    global $pdo;
    
    try {
        // Get filter parameters
        $session = isset($_POST['session']) ? trim($_POST['session']) : '';
        $class_id = isset($_POST['class_id']) ? (int)$_POST['class_id'] : 0;
        $subject_id = isset($_POST['subject_id']) ? (int)$_POST['subject_id'] : 0;
        
        // Build WHERE clause
        $where_conditions = [];
        $params = [];
        
        if (!empty($session)) {
            $where_conditions[] = "s.session = ?";
            $params[] = $session;
        }
        
        if ($class_id > 0) {
            $where_conditions[] = "s.class_id = ?";
            $params[] = $class_id;
        }
        
        if ($subject_id > 0) {
            $where_conditions[] = "r.subject_id = ?";
            $params[] = $subject_id;
        }
        
        $where_clause = !empty($where_conditions) ? 'WHERE ' . implode(' AND ', $where_conditions) : '';
        
        // Get analytics data
        $analytics_sql = "
            SELECT 
                AVG(r.marks_obtained) as average_performance,
                COUNT(CASE WHEN r.grade != 'F' THEN 1 END) * 100.0 / COUNT(*) as pass_rate,
                COUNT(CASE WHEN r.marks_obtained < 40 THEN 1 END) as at_risk_count,
                COUNT(CASE WHEN r.marks_obtained >= 80 THEN 1 END) as top_performers,
                COUNT(*) as total_students
            FROM results r
            JOIN students s ON r.student_id = s.id
            $where_clause
        ";
        
        $stmt = $pdo->prepare($analytics_sql);
        $stmt->execute($params);
        $analytics = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$analytics || $analytics['total_students'] == 0) {
            throw new Exception("No data found for the selected filters", 'no_data_found');
        }
        
        // Format results
        $analytics['average_performance'] = round($analytics['average_performance'] ?? 0, 1);
        $analytics['pass_rate'] = round($analytics['pass_rate'] ?? 0, 1);
        $analytics['at_risk_count'] = (int)($analytics['at_risk_count'] ?? 0);
        $analytics['top_performers'] = (int)($analytics['top_performers'] ?? 0);
        $analytics['total_students'] = (int)($analytics['total_students'] ?? 0);
        $analytics['trend_direction'] = 'stable';
        
        return [
            'success' => true,
            'message' => 'Analytics data loaded successfully',
            'analytics' => $analytics,
            'filters_applied' => [
                'session' => $session,
                'class_id' => $class_id,
                'subject_id' => $subject_id
            ]
        ];
        
    } catch (Exception $e) {
        throw new Exception("Analytics loading failed: " . $e->getMessage(), 'analytics_error');
    }
}

// Helper functions
function calculateGrade($marks) {
    if ($marks >= 80) return 'A+';
    if ($marks >= 70) return 'A';
    if ($marks >= 60) return 'A-';
    if ($marks >= 50) return 'B';
    if ($marks >= 40) return 'C';
    if ($marks >= 33) return 'D';
    return 'F';
}

function calculateConfidence($history) {
    $count = count($history);
    if ($count < 2) return 0.3;
    if ($count < 4) return 0.6;
    
    $marks = array_column($history, 'marks_obtained');
    $mean = array_sum($marks) / count($marks);
    $variance = array_sum(array_map(function($mark) use ($mean) {
        return pow($mark - $mean, 2);
    }, $marks)) / count($marks);
    $std_dev = sqrt($variance);
    
    $consistency_factor = max(0.1, 1 - ($std_dev / 50));
    return min(0.95, 0.7 + ($consistency_factor * 0.25));
}

function calculateStudentRisk($student_id) {
    // Simplified risk calculation
    global $pdo;
    
    $sql = "
        SELECT AVG(r.marks_obtained) as avg_marks,
               COUNT(CASE WHEN r.marks_obtained < 40 THEN 1 END) as fail_count
        FROM results r
        WHERE r.student_id = ?
    ";
    
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$student_id]);
    $data = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$data || !$data['avg_marks']) {
        return null;
    }
    
    $score = 0;
    $avg_marks = $data['avg_marks'];
    
    if ($avg_marks < 33) {
        $score += 1.0;
    } elseif ($avg_marks < 40) {
        $score += 0.8;
    } elseif ($avg_marks < 50) {
        $score += 0.6;
    } elseif ($avg_marks < 60) {
        $score += 0.4;
    } elseif ($avg_marks < 70) {
        $score += 0.2;
    }
    
    if ($data['fail_count'] > 0) {
        $score += min(0.5, $data['fail_count'] * 0.2);
    }
    
    $normalized_score = $score;
    $risk_level = determineRiskLevel($normalized_score);
    
    return [
        'risk_level' => $risk_level,
        'overall_score' => round($normalized_score, 2),
        'risk_factors' => [
            'academic_performance' => ['score' => $normalized_score]
        ]
    ];
}

function determineRiskLevel($score) {
    if ($score >= 0.8) return 'critical';
    if ($score >= 0.6) return 'high';
    if ($score >= 0.4) return 'medium';
    return 'low';
}

// Placeholder functions for recommendation generation
function generateStudyTips() { return []; }
function generateFocusAreas() { return []; }
function generateImprovementStrategies() { return []; }
function generateWarnings() { return []; }
?>