File "create.php"
Full path: /home2/santhos2/public_html/bharath-coe.firstmatrix.in.net/api/question_patterns/create.php
File size: 2.43 KiB (2485 bytes)
MIME-type: text/x-php
Charset: utf-8
<?php
require_once '../../config/config.php';
require_once '../helper/audit_log.php';
header('Content-Type: application/json');
try {
$pattern_name = trim($_POST['pattern_name'] ?? '');
$total_marks = (int)($_POST['total_marks'] ?? 0);
$subject_id = (int)($_POST['subject_id'] ?? 0);
$template_id = (int)($_POST['template_id'] ?? 0); // optional
$errors = [];
if ($pattern_name === '') $errors[] = 'Pattern name is required';
if ($total_marks <= 0) $errors[] = 'Total marks must be greater than 0';
if ($subject_id <= 0) $errors[] = 'Subject is required';
if ($errors) { echo json_encode(['status'=>'error','message'=>implode(', ', $errors)]); exit; }
// Uniqueness guard
if ($template_id > 0) {
$chk = $pdo->prepare('SELECT pattern_id FROM question_patterns WHERE subject_id=? AND template_id=? LIMIT 1');
$chk->execute([$subject_id, $template_id]);
} else {
$chk = $pdo->prepare('SELECT pattern_id FROM question_patterns WHERE subject_id=? LIMIT 1');
$chk->execute([$subject_id]);
}
if ($row = $chk->fetch(PDO::FETCH_ASSOC)) {
echo json_encode([
'status'=>'error',
'message'=>'A question pattern already exists for this Subject' . ($template_id>0 ? ' and Template' : ''),
'existing_pattern_id' => $row['pattern_id']
]);
exit;
}
$stmt = $pdo->prepare('INSERT INTO question_patterns (pattern_name, total_marks, subject_id, template_id) VALUES (?,?,?,?)');
$stmt->execute([$pattern_name, $total_marks, $subject_id, $template_id]);
$pattern_id = (int)$pdo->lastInsertId();
write_audit_log($pdo, [
'module' => 'Question Papers',
'action' => 'create',
'entity_table' => 'question_patterns',
'entity_id' => $pattern_id,
'after_data' => compact('pattern_id','pattern_name','total_marks','subject_id','template_id'),
'message' => 'Question pattern created'
]);
echo json_encode(['status'=>'success','message'=>'Question pattern created','data'=>['pattern_id'=>$pattern_id]]);
} catch (PDOException $e) {
$msg = $e->getCode()==='23000' ? 'Pattern already exists for this subject/template' : 'Database error: '.$e->getMessage();
http_response_code(400);
echo json_encode(['status'=>'error','message'=>$msg]);
} catch (Throwable $e) {
http_response_code(500);
echo json_encode(['status'=>'error','message'=>$e->getMessage()]);
}
?>