<?php
require_once '../../config/config.php';
require_once '../helper/audit_log.php';
header('Content-Type: application/json');

try {
    $id        = (int)($_POST['id'] ?? 0);
    $exam_id   = isset($_POST['exam_id']) ? (int)$_POST['exam_id'] : null;
    $staff_id  = isset($_POST['staff_id']) ? (int)$_POST['staff_id'] : null;
    $start_date= isset($_POST['start_date']) ? trim((string)$_POST['start_date']) : null;
    $end_date  = isset($_POST['end_date']) ? trim((string)$_POST['end_date']) : null;
    $pattern_id= isset($_POST['pattern_id']) ? (($_POST['pattern_id'] === '' || $_POST['pattern_id'] === null) ? null : (int)$_POST['pattern_id']) : null; // legacy
    $exam_subject_id = isset($_POST['exam_subject_id']) ? (($_POST['exam_subject_id'] === '' || $_POST['exam_subject_id'] === null) ? null : (int)$_POST['exam_subject_id']) : null;
    $template_id = isset($_POST['template_id']) ? (($_POST['template_id'] === '' || $_POST['template_id'] === null) ? null : (int)$_POST['template_id']) : null;

    if ($id <= 0) { echo json_encode(['status'=>'error','message'=>'ID required']); exit; }

    $st = $pdo->prepare('SELECT * FROM qp_setter_assignments WHERE id=?');
    $st->execute([$id]);
    $before = $st->fetch(PDO::FETCH_ASSOC);
    if (!$before) { echo json_encode(['status'=>'error','message'=>'Not found']); exit; }

    $updates=[]; $params=[];
    if ($exam_id !== null)   { $updates[]='exam_id=?';    $params[]=$exam_id; }
    if ($staff_id !== null)  { $updates[]='staff_id=?';   $params[]=$staff_id; }
    if ($start_date !== null){ $updates[]='start_date=?'; $params[]=$start_date; }
    if ($end_date !== null)  { $updates[]='end_date=?';   $params[]=$end_date; }
    if ($pattern_id !== null){
        if ($pattern_id) {
            $chk = $pdo->prepare('SELECT COUNT(*) FROM question_patterns WHERE pattern_id = ?');
            $chk->execute([$pattern_id]);
            if ((int)$chk->fetchColumn() === 0) { throw new Exception('Invalid question pattern selected.'); }
        }
        // Only update if column exists
        try { $c=$pdo->query("SHOW COLUMNS FROM qp_setter_assignments LIKE 'pattern_id'"); if($c && $c->rowCount()>0){ $updates[]='pattern_id=?'; $params[]=$pattern_id; } } catch (Throwable $e) {}
    }

    if ($exam_subject_id !== null){
        if ($exam_subject_id) {
            $chk = $pdo->prepare('SELECT exam_id FROM exam_subjects WHERE exam_subject_id = ?');
            $chk->execute([$exam_subject_id]);
            $es = $chk->fetch(PDO::FETCH_ASSOC);
            if (!$es) { throw new Exception('Invalid exam subject selected.'); }
            // If exam_id provided in update, ensure match
            if ($exam_id !== null && (int)$es['exam_id'] !== (int)$exam_id) { throw new Exception('Selected subject does not belong to the chosen exam.'); }
        }
        try { $c=$pdo->query("SHOW COLUMNS FROM qp_setter_assignments LIKE 'exam_subject_id'"); if($c && $c->rowCount()>0){ $updates[]='exam_subject_id=?'; $params[]=$exam_subject_id; } } catch (Throwable $e) {}
    }

    if ($template_id !== null){
        if ($template_id) {
            $chk = $pdo->prepare('SELECT COUNT(*) FROM question_pattern_templates WHERE template_id = ?');
            $chk->execute([$template_id]);
            if ((int)$chk->fetchColumn() === 0) { throw new Exception('Invalid template selected.'); }
        }
        try { $c=$pdo->query("SHOW COLUMNS FROM qp_setter_assignments LIKE 'template_id'"); if($c && $c->rowCount()>0){ $updates[]='template_id=?'; $params[]=$template_id; } } catch (Throwable $e) {}
    }

    if (!$updates) { echo json_encode(['status'=>'error','message'=>'No fields to update']); exit; }
    $params[] = $id;
    $sql = 'UPDATE qp_setter_assignments SET '.implode(', ',$updates).' WHERE id=?';
    $pdo->prepare($sql)->execute($params);

    $st = $pdo->prepare('SELECT * FROM qp_setter_assignments WHERE id=?');
    $st->execute([$id]);
    $after = $st->fetch(PDO::FETCH_ASSOC);

    write_audit_log($pdo, [
        'module' => 'Question Papers',
        'action' => 'update',
        'entity_table' => 'qp_setter_assignments',
        'entity_id' => $id,
        'before_data' => $before,
        'after_data'  => $after,
        'message' => 'QP Setter assignment updated'
    ]);

    echo json_encode(['status'=>'success','message'=>'Assignment updated']);
} catch (Throwable $e) {
    http_response_code(500);
    echo json_encode(['status'=>'error','message'=>$e->getMessage()]);
}
?>


