<?php
// ajax/add_options_to_question.php
require '../config.php';
header('Content-Type: application/json');
$input = json_decode(file_get_contents('php://input'), true);
$id = intval($input['id'] ?? 0);
$options_raw = trim($input['options'] ?? '');
if (!$id || !$options_raw){ echo json_encode(['success'=>false,'message'=>'Missing data']); exit; }

try {
  $stmt = $dbh->prepare("SELECT options, type FROM questions WHERE id = :id LIMIT 1");
  $stmt->execute([':id'=>$id]);
  $row = $stmt->fetch(PDO::FETCH_ASSOC);
  if (!$row) { echo json_encode(['success'=>false,'message'=>'Question not found']); exit; }
  if ($row['type'] !== 'objective'){ echo json_encode(['success'=>false,'message'=>'Question is not objective']); exit; }

  $existing = [];
  if (!empty($row['options'])){
    $decoded = json_decode($row['options'], true);
    if (is_array($decoded)) $existing = $decoded;
  }
  $new = array_filter(array_map('trim', explode(',', $options_raw)));
  $merged = array_values(array_unique(array_merge($existing, $new)));
  $stmt2 = $dbh->prepare("UPDATE questions SET options = :opts WHERE id = :id");
  $stmt2->execute([':opts'=>json_encode($merged), ':id'=>$id]);
  echo json_encode(['success'=>true, 'options'=>$merged]);
} catch(Exception $e){
  echo json_encode(['success'=>false,'message'=>$e->getMessage()]);
}
