<?php
/**
 * AJAX Repertorization Endpoint
 * Real-time repertorization for case creation
 */

require_once '../../config/config.php';
require_once '../../includes/repertory-engine.php';

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

if (!isLoggedIn()) {
    echo json_encode(['success' => false, 'error' => 'Unauthorized']);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $rubricIds = $_POST['rubric_ids'] ?? [];
    
    if (empty($rubricIds)) {
        echo json_encode(['success' => true, 'results' => []]);
        exit;
    }
    
    $rubricsWithWeights = [];
    foreach ($rubricIds as $id) {
        $rubricsWithWeights[$id] = ['weight' => 1];
    }
    
    $scores = repertorize($rubricsWithWeights);
    
    $results = [];
    foreach ($scores as $remedyId => $data) {
        $results[] = [
            'id' => $remedyId,
            'name' => $data['name'],
            'score' => $data['score'],
            'grades' => $data['grades']
        ];
    }
    
    echo json_encode(['success' => true, 'results' => $results]);
}
?>