<?php
require_once '../../config/config.php';
require_once '../helper/audit_log.php';
header('Content-Type: application/json');

try {
    $id = (int)($_POST['id'] ?? 0);
    if ($id <= 0) { echo json_encode(['status'=>'error','message'=>'ID required']); exit; }

    $stmt = $pdo->prepare('SELECT * FROM pattern_questions WHERE id = ?');
    $stmt->execute([$id]);
    $before = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!$before) { echo json_encode(['status'=>'error','message'=>'Not found']); exit; }

    $updates = [];
    $params = [];
    foreach (['question_no','question_type','cognitive_level','question_text'] as $f) {
        if (isset($_POST[$f])) { $updates[] = "$f = ?"; $params[] = $_POST[$f]; }
    }

    if (array_key_exists('co_codes', $_POST)) {
        $co = $_POST['co_codes'];
        if (is_array($co)) {
            $co = array_values(array_filter(array_map('trim', $co))); 
            $co = json_encode($co, JSON_UNESCAPED_UNICODE);
        } else {
            $co = trim((string)$co);
            if ($co === '') {
                $co = json_encode([], JSON_UNESCAPED_UNICODE);
            } else if ($co[0] !== '[') {
                $co = json_encode(array_map('trim', explode(',', $co)), JSON_UNESCAPED_UNICODE);
            }
        }
        $updates[] = 'co_codes = ?'; $params[] = $co;
    }

    if (array_key_exists('po_codes', $_POST)) {
        $po = $_POST['po_codes'];
        if (is_array($po)) {
            $po = array_values(array_filter(array_map('trim', $po))); 
            if (empty($po)) { $po = ['NA']; }
            $po = json_encode($po, JSON_UNESCAPED_UNICODE);
        } else {
            $po = trim((string)$po);
            if ($po === '') {
                $po = json_encode(['NA'], JSON_UNESCAPED_UNICODE);
            } else if ($po[0] !== '[') {
                $po = json_encode(array_map('trim', explode(',', $po)), JSON_UNESCAPED_UNICODE);
            }
        }
        $updates[] = 'po_codes = ?'; $params[] = $po;
    }

    if (!$updates) { echo json_encode(['status'=>'error','message'=>'No fields to update']); exit; }
    $params[] = $id;
    $sql = 'UPDATE pattern_questions SET ' . implode(', ', $updates) . ' WHERE id = ?';
    $pdo->prepare($sql)->execute($params);

    $stmt = $pdo->prepare('SELECT * FROM pattern_questions WHERE id = ?');
    $stmt->execute([$id]);
    $after = $stmt->fetch(PDO::FETCH_ASSOC);

    write_audit_log($pdo, [
        'module' => 'Question Papers',
        'action' => 'update',
        'entity_table' => 'pattern_questions',
        'entity_id' => $id,
        'before_data' => $before,
        'after_data' => $after,
        'message' => 'Pattern question updated'
    ]);

    echo json_encode(['status'=>'success','message'=>'Question updated']);
} catch (Throwable $e) {
    http_response_code(500);
    echo json_encode(['status'=>'error','message'=>$e->getMessage()]);
}
?>


