<?php
/**
 * API Endpoint: generate_ai_report.php
 *
 * Generates AI-powered student performance rankings and recommendations.
 * Requires an active super_admin_session.
 *
 * Request:  POST
 * Params:   session, term, class, section, subject (same as generate_report.php)
 * Response: JSON { success: bool, data: { rankings, atRiskStudents, schoolInsights, classInsights, studentRecommendations } }
 */

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

// Session setup — must match reports.php
session_name('super_admin_session');
if (!is_dir(dirname(__DIR__, 2) . '/session_data/super')) {
    mkdir(dirname(__DIR__, 2) . '/session_data/super', 0700, true);
}
session_save_path(dirname(__DIR__, 2) . '/session_data/super');
session_set_cookie_params(['path' => '/', 'httponly' => true, 'samesite' => 'Strict']);
session_start();

// Auth check — same pattern as dashboard.php and reports.php
if (empty($_SESSION['sid']) || strlen($_SESSION['sid']) == 0) {
    http_response_code(403);
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

if (empty($_SESSION['permission']) || $_SESSION['permission'] !== 'Super User') {
    http_response_code(403);
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

error_reporting(E_ALL);
ini_set('display_errors', 0); // keep off for browser but log everything
set_time_limit(120); // allow up to 2 minutes for large datasets

include('../includes/dbconnection.php');
include('../includes/AIEngine.php');

try {
    $filters = [
        'session_id' => $_POST['session'] ?? '',
        'term_id' => $_POST['term'] ?? '',
        'class' => $_POST['class'] ?? '',
        'section' => $_POST['section'] ?? '',
        'subject' => $_POST['subject'] ?? '',
    ];

    if (empty($filters['session_id'])) {
        throw new \InvalidArgumentException('Academic session is required.');
    }

    $engine = new AIEngine($con);
    $data = $engine->processAll($filters);

    echo json_encode(['success' => true, 'data' => $data]);

} catch (\InvalidArgumentException $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
} catch (\Exception $e) {
    error_log('AI Report Error: ' . $e->getMessage() . ' in ' . $e->getFile() . ':' . $e->getLine());
    // If we have partial data, return it with a warning rather than failing completely
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
