<?php
/**
 * AJAX: Repertorization
 * Real-time repertorization for selected rubrics
 * Method: POST
 */

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

session_start();
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');

if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    http_response_code(200);
    exit;
}

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

if ($_SERVER['REQUEST_METHOD'] != 'POST') {
    echo json_encode(['success' => false, 'error' => 'Method not allowed']);
    exit;
}

$rubricIds = $_POST['rubric_ids'] ?? [];
if (is_string($rubricIds)) {
    $rubricIds = json_decode($rubricIds, true);
}

if (empty($rubricIds)) {
    echo json_encode(['success' => true, 'results' => []]);
    exit;
}

// Convert to associative array with weights
$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]);
?>