// Fix 1: FIB (type_id=2) questions that have NO input box and NO [?] marker —
// append one [?] per non-null answer so blank-count == answer-count.
// Fix 2: MCQ (type_id=1) questions with a stray [?] in the stem — remove it.
$base = DB::table('questions')->where('qa_status','ai_generated');
$fibFixed=0; $mcqFixed=0; $bk=[];
foreach ((clone $base)->where('type_id',2)->orderBy('id')->cursor() as $r) {
$q=(string)$r->question;
if (strpos($q,'$c!==null && trim((string)$r->$c)!=='') $na++; }
if ($na<1) $na=1;
if ($na==1) { $append='
Answer: [?]'; }
else { $p=[]; for($i=0;$i<$na;$i++) $p[]='('.chr(97+$i).') [?]'; $append='
'.implode(' ',$p); }
$bk[]=['id'=>$r->id,'question'=>$q];
DB::table('questions')->where('id',$r->id)->update(['question'=>$q.$append,'updated_at'=>now()]);
$fibFixed++;
}
foreach ((clone $base)->where('type_id',1)->where('question','like','%[?]%')->orderBy('id')->cursor() as $r) {
$q=(string)$r->question;
$nq=trim(preg_replace('/\s*\[\?\]\s*/',' ',$q));
if ($nq!==$q){ $bk[]=['id'=>$r->id,'question'=>$q]; DB::table('questions')->where('id',$r->id)->update(['question'=>$nq,'updated_at'=>now()]); $mcqFixed++; }
}
file_put_contents(storage_path('app/fibfix_backup_'.date('Ymd_His').'.json'), json_encode($bk, JSON_UNESCAPED_UNICODE));
echo "fib_missing_input_fixed=$fibFixed mcq_stray_blank_fixed=$mcqFixed\n";