<?php
declare(strict_types=1);
session_start();
require_once '../../config.php';
if (!isset($_SESSION['user_id'])) { http_response_code(401); echo json_encode(['success'=>false]); exit; }
header('Content-Type: application/json');
$conn = getDBConnection();
if (!$conn instanceof mysqli) { echo json_encode(['success'=>false,'questions'=>[]]); exit; }
$subjectId = (int) ($_POST['subject_id'] ?? 0);
$className = trim((string) ($_POST['class_name'] ?? ''));
$counts = ['mcq'=>(int)($_POST['mcq_count'] ?? 0),'theory'=>(int)($_POST['theory_count'] ?? 0),'fill_blank'=>(int)($_POST['fill_blank_count'] ?? 0)];
$easyPct = max(0, (int) ($_POST['easy_pct'] ?? 0));
$mediumPct = max(0, (int) ($_POST['medium_pct'] ?? 0));
$hardPct = max(0, (int) ($_POST['hard_pct'] ?? 0));
if ($subjectId <= 0 || $className === '' || ($easyPct + $mediumPct + $hardPct) !== 100) { echo json_encode(['success'=>false,'message'=>'Invalid auto-generate settings','questions'=>[]]); exit; }
$questions = [];
$selectedIds = [];
foreach ($counts as $type => $count) {
    if ($count <= 0) { continue; }
    $distribution = ['easy'=>(int) round($count * $easyPct / 100),'medium'=>(int) round($count * $mediumPct / 100)];
    $distribution['hard'] = $count - $distribution['easy'] - $distribution['medium'];
    foreach ($distribution as $difficulty => $need) {
        if ($need <= 0) { continue; }
        $excludeSql = '';
        if ($selectedIds) {
            $excludeSql = ' AND id NOT IN (' . implode(',', array_map('intval', $selectedIds)) . ')';
        }
        $sql = "SELECT * FROM exam_questions WHERE subject_id = ? AND class_name = ? AND question_type = ? AND difficulty = ?{$excludeSql} ORDER BY ai_generated DESC, RAND() LIMIT {$need}";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param('isss', $subjectId, $className, $type, $difficulty);
        $stmt->execute();
        $result = $stmt->get_result();
        while ($row = $result->fetch_assoc()) {
            $questions[] = $row;
            $selectedIds[] = (int) $row['id'];
        }
        $stmt->close();
    }
}
echo json_encode(['success'=>true,'questions'=>$questions]);
