<?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']);
    exit();
}

try {
    // Clear existing pending recommendations
    $pdo->exec("DELETE FROM ai_recommendations WHERE status = 'pending'");
    
    $recommendations_generated = 0;
    
    // Generate study tips recommendations
    $study_tips = generateStudyTipsRecommendations();
    $recommendations_generated += count($study_tips);
    
    // Generate focus area recommendations
    $focus_areas = generateFocusAreaRecommendations();
    $recommendations_generated += count($focus_areas);
    
    // Generate improvement strategy recommendations
    $improvement_strategies = generateImprovementStrategyRecommendations();
    $recommendations_generated += count($improvement_strategies);
    
    // Generate warning recommendations
    $warnings = generateWarningRecommendations();
    $recommendations_generated += 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);
    
    // 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']
        ]);
    }
    
    // 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']
        ]);
    }
    
    // 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']
        ]);
    }
    
    // Insert warnings
    foreach ($warnings as $rec) {
        $stmt->execute([
            $rec['student_id'],
            $rec['subject_id'],
            'warning',
            $rec['priority'],
            $rec['title'],
            $rec['description'],
            $rec['suggested_action']
        ]);
    }

    echo json_encode([
        'success' => true,
        'message' => "Generated {$recommendations_generated} AI recommendations successfully",
        'recommendations_count' => $recommendations_generated
    ]);

} catch (Exception $e) {
    error_log("AI Recommendation Error: " . $e->getMessage());
    echo json_encode([
        'success' => false,
        'message' => 'Error generating recommendations: ' . $e->getMessage()
    ]);
}

/**
 * Generate study tips recommendations
 */
function generateStudyTipsRecommendations() {
    global $pdo;
    
    $recommendations = [];
    
    // Get students who are performing moderately (need study tips)
    $students_sql = "
        SELECT 
            s.id as student_id,
            s.first_name,
            s.last_name,
            r.subject_id,
            sub.name as subject_name,
            AVG(r.marks_obtained) as avg_marks
        FROM students s
        JOIN results r ON s.id = r.student_id
        JOIN subjects sub ON r.subject_id = sub.id
        WHERE s.status = 'active'
        AND r.marks_obtained BETWEEN 40 AND 70
        GROUP BY s.id, r.subject_id
        HAVING COUNT(r.id) >= 2
    ";
    
    $stmt = $pdo->query($students_sql);
    $students = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    foreach ($students as $student) {
        $tips = getSubjectSpecificStudyTips($student['subject_name']);
        
        $recommendations[] = [
            'student_id' => $student['student_id'],
            'subject_id' => $student['subject_id'],
            'priority' => 'medium',
            'title' => "Study Tips for " . $student['subject_name'],
            'description' => "Based on your current performance ({$student['avg_marks']}%), here are targeted study strategies to improve your results in {$student['subject_name']}.",
            'suggested_action' => implode('; ', $tips)
        ];
    }
    
    return $recommendations;
}

/**
 * Generate focus area recommendations
 */
function generateFocusAreaRecommendations() {
    global $pdo;
    
    $recommendations = [];
    
    // Get students with weak performance in specific areas
    $weak_areas_sql = "
        SELECT 
            s.id as student_id,
            s.first_name,
            s.last_name,
            r.subject_id,
            sub.name as subject_name,
            AVG(r.marks_obtained) as avg_marks,
            AVG(r.cq_marks) as avg_cq,
            AVG(r.mcq_marks) as avg_mcq,
            AVG(r.practical_marks) as avg_practical
        FROM students s
        JOIN results r ON s.id = r.student_id
        JOIN subjects sub ON r.subject_id = sub.id
        WHERE s.status = 'active'
        AND r.marks_obtained < 50
        GROUP BY s.id, r.subject_id
        HAVING COUNT(r.id) >= 2
    ";
    
    $stmt = $pdo->query($weak_areas_sql);
    $weak_areas = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    foreach ($weak_areas as $area) {
        $focus_areas = identifyWeakAreas($area);
        
        if (!empty($focus_areas)) {
            $recommendations[] = [
                'student_id' => $area['student_id'],
                'subject_id' => $area['subject_id'],
                'priority' => 'high',
                'title' => "Focus Areas: " . $area['subject_name'],
                'description' => "You need to strengthen these areas in {$area['subject_name']} to improve your overall performance.",
                'suggested_action' => "Focus on: " . implode(', ', $focus_areas)
            ];
        }
    }
    
    return $recommendations;
}

/**
 * Generate improvement strategy recommendations
 */
function generateImprovementStrategyRecommendations() {
    global $pdo;
    
    $recommendations = [];
    
    // Get students showing declining trends
    $declining_students_sql = "
        SELECT 
            lp.student_id,
            s.first_name,
            s.last_name,
            lp.subject_id,
            sub.name as subject_name,
            lp.trend_slope
        FROM ai_learning_patterns lp
        JOIN students s ON lp.student_id = s.id
        JOIN subjects sub ON lp.subject_id = sub.id
        WHERE lp.pattern_type = 'decline'
        AND s.status = 'active'
    ";
    
    $stmt = $pdo->query($declining_students_sql);
    $declining_students = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    foreach ($declining_students as $student) {
        $strategies = getImprovementStrategies($student['subject_name'], $student['trend_slope']);
        
        $recommendations[] = [
            'student_id' => $student['student_id'],
            'subject_id' => $student['subject_id'],
            'priority' => 'high',
            'title' => "Improvement Strategy for " . $student['subject_name'],
            'description' => "Your performance in {$student['subject_name']} is declining. Here's a targeted improvement plan.",
            'suggested_action' => implode('; ', $strategies)
        ];
    }
    
    return $recommendations;
}

/**
 * Generate warning recommendations
 */
function generateWarningRecommendations() {
    global $pdo;
    
    $recommendations = [];
    
    // Get students at high risk of failure
    $at_risk_sql = "
        SELECT 
            s.id as student_id,
            s.first_name,
            s.last_name,
            r.subject_id,
            sub.name as subject_name,
            AVG(r.marks_obtained) as avg_marks
        FROM students s
        JOIN results r ON s.id = r.student_id
        JOIN subjects sub ON r.subject_id = sub.id
        WHERE s.status = 'active'
        AND r.marks_obtained < 40
        GROUP BY s.id, r.subject_id
        HAVING COUNT(r.id) >= 2
        AND AVG(r.marks_obtained) < 35
    ";
    
    $stmt = $pdo->query($at_risk_sql);
    $at_risk_students = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    foreach ($at_risk_students as $student) {
        $recommendations[] = [
            'student_id' => $student['student_id'],
            'subject_id' => $student['subject_id'],
            'priority' => 'high',
            'title' => "⚠️ Critical Warning: " . $student['subject_name'],
            'description' => "You are at HIGH RISK of failing {$student['subject_name']}. Immediate action is required to avoid academic consequences.",
            'suggested_action' => "Seek immediate help from your teacher; attend extra classes; focus intensively on this subject; consider tutoring"
        ];
    }
    
    // Get students with inconsistent performance
    $inconsistent_sql = "
        SELECT 
            lp.student_id,
            s.first_name,
            s.last_name,
            lp.subject_id,
            sub.name as subject_name
        FROM ai_learning_patterns lp
        JOIN students s ON lp.student_id = s.id
        JOIN subjects sub ON lp.subject_id = sub.id
        WHERE lp.pattern_type = 'volatile'
        AND lp.consistency_score < 0.4
        AND s.status = 'active'
    ";
    
    $stmt = $pdo->query($inconsistent_sql);
    $inconsistent_students = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    foreach ($inconsistent_students as $student) {
        $recommendations[] = [
            'student_id' => $student['student_id'],
            'subject_id' => $student['subject_id'],
            'priority' => 'medium',
            'title' => "Performance Alert: " . $student['subject_name'],
            'description' => "Your performance in {$student['subject_name']} is highly inconsistent. This unpredictability could affect your final results.",
            'suggested_action' => "Establish a regular study routine; practice consistently; seek clarification on unclear topics"
        ];
    }
    
    return $recommendations;
}

/**
 * Get subject-specific study tips
 */
function getSubjectSpecificStudyTips($subject_name) {
    $tips = [];
    
    switch (strtolower($subject_name)) {
        case 'বাংলা':
        case 'bangla':
            $tips = [
                "Practice writing essays daily",
                "Read Bengali literature regularly",
                "Memorize important grammar rules",
                "Practice creative writing exercises"
            ];
            break;
        case 'ইংরেজি':
        case 'english':
            $tips = [
                "Read English newspapers and books daily",
                "Practice grammar exercises regularly",
                "Listen to English podcasts or videos",
                "Write diary entries in English"
            ];
            break;
        case 'গণিত':
        case 'mathematics':
        case 'math':
            $tips = [
                "Practice 10-15 math problems daily",
                "Understand concepts before memorizing formulas",
                "Work on weak areas identified in previous tests",
                "Join study groups for problem-solving"
            ];
            break;
        case 'বিজ্ঞান':
        case 'science':
            $tips = [
                "Conduct simple experiments at home",
                "Draw diagrams and charts to understand concepts",
                "Watch educational science videos",
                "Practice numerical problems regularly"
            ];
            break;
        case 'সমাজবিজ্ঞান':
        case 'social science':
            $tips = [
                "Create mind maps for historical events",
                "Discuss current affairs with friends",
                "Use flashcards for important dates and facts",
                "Relate textbook concepts to real-world examples"
            ];
            break;
        default:
            $tips = [
                "Review notes daily for 15-20 minutes",
                "Ask questions when concepts are unclear",
                "Form study groups with classmates",
                "Practice past exam papers"
            ];
    }
    
    return $tips;
}

/**
 * Identify weak areas based on component scores
 */
function identifyWeakAreas($performance_data) {
    $weak_areas = [];
    
    if ($performance_data['avg_cq'] < 20) {
        $weak_areas[] = "Creative Questions (Writing)";
    }
    
    if ($performance_data['avg_mcq'] < 15) {
        $weak_areas[] = "Multiple Choice Questions";
    }
    
    if ($performance_data['avg_practical'] < 15) {
        $weak_areas[] = "Practical/Application Skills";
    }
    
    return $weak_areas;
}

/**
 * Get improvement strategies based on subject and trend
 */
function getImprovementStrategies($subject_name, $trend_slope) {
    $strategies = [
        "Schedule dedicated study time for this subject (minimum 1 hour daily)",
        "Identify and focus on your weakest topics first",
        "Seek extra help from your subject teacher",
        "Form a study group with high-performing classmates"
    ];
    
    // Add subject-specific strategies
    $subject_strategies = [];
    switch (strtolower($subject_name)) {
        case 'mathematics':
        case 'গণিত':
            $subject_strategies = [
                "Practice additional problems from reference books",
                "Focus on understanding problem-solving techniques",
                "Review mistakes from previous exams thoroughly"
            ];
            break;
        case 'english':
        case 'ইংরেজি':
            $subject_strategies = [
                "Increase reading time to improve comprehension",
                "Practice writing paragraphs daily",
                "Focus on grammar rules and vocabulary building"
            ];
            break;
    }
    
    return array_merge($strategies, $subject_strategies);
}
?>