<?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 {
    // Get recent recommendations (last 30 days)
    $recommendations_sql = "
        SELECT 
            ar.id,
            ar.student_id,
            ar.subject_id,
            ar.recommendation_type,
            ar.priority,
            ar.title,
            ar.description,
            ar.suggested_action,
            ar.generated_date,
            ar.status,
            s.first_name,
            s.last_name,
            s.student_id as student_code,
            sub.name as subject_name,
            sub.code as subject_code
        FROM ai_recommendations ar
        JOIN students s ON ar.student_id = s.id
        LEFT JOIN subjects sub ON ar.subject_id = sub.id
        WHERE ar.generated_date >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)
        ORDER BY 
            CASE ar.priority 
                WHEN 'high' THEN 1
                WHEN 'medium' THEN 2
                WHEN 'low' THEN 3
            END,
            ar.generated_date DESC
        LIMIT 20
    ";
    
    $stmt = $pdo->query($recommendations_sql);
    $recommendations = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Format the recommendations
    $formatted_recommendations = [];
    
    foreach ($recommendations as $rec) {
        $formatted_recommendations[] = [
            'id' => $rec['id'],
            'student_name' => $rec['first_name'] . ' ' . $rec['last_name'],
            'student_code' => $rec['student_code'],
            'subject' => $rec['subject_name'] ? $rec['subject_name'] . ' (' . $rec['subject_code'] . ')' : 'All Subjects',
            'type' => formatRecommendationType($rec['recommendation_type']),
            'priority' => $rec['priority'],
            'title' => $rec['title'],
            'description' => $rec['description'],
            'suggested_action' => $rec['suggested_action'],
            'generated_date' => date('M j, Y', strtotime($rec['generated_date'])),
            'status' => ucfirst($rec['status'])
        ];
    }
    
    if (empty($formatted_recommendations)) {
        echo json_encode([
            'success' => false,
            'message' => 'No recent recommendations found. Generate recommendations first.'
        ]);
    } else {
        echo json_encode([
            'success' => true,
            'recommendations' => $formatted_recommendations,
            'total_count' => count($formatted_recommendations)
        ]);
    }

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

/**
 * Format recommendation type for display
 */
function formatRecommendationType($type) {
    switch ($type) {
        case 'study_tips':
            return 'Study Tips';
        case 'focus_areas':
            return 'Focus Areas';
        case 'improvement_strategies':
            return 'Improvement Strategies';
        case 'warning':
            return 'Warning';
        default:
            return ucfirst(str_replace('_', ' ', $type));
    }
}
?>