<?php
// auto_save_checklist.php
require_once '../includes/auth.php';
require_once '../includes/db.php'; // Sesuaikan dengan file koneksi database Anda

header('Content-Type: application/json');

if (!isPenguji()) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

$penguji_id = $_SESSION['user_id'];
$ujian_id = $_POST['ujian_id'] ?? null;
$peserta_id = $_POST['peserta_id'] ?? null;
$station_id = $_POST['station_id'] ?? null;
$aspek_id = $_POST['aspek_id'] ?? null;
$checklist_item = $_POST['checklist_item'] ?? null;
$status = $_POST['status'] ?? 'belum';
$catatan = $_POST['catatan'] ?? '';

// Validasi
if (!$ujian_id || !$peserta_id || !$station_id || !$penguji_id || !$checklist_item) {
    echo json_encode(['success' => false, 'message' => 'Data tidak lengkap']);
    exit;
}

try {
    // Cek apakah sudah ada
    $stmt = $pdo->prepare("
        SELECT id FROM checklist_verifikasi 
        WHERE ujian_id = ? AND peserta_id = ? AND station_id = ? 
        AND penguji_id = ? AND checklist_item = ?
    ");
    $stmt->execute([$ujian_id, $peserta_id, $station_id, $penguji_id, $checklist_item]);
    
    if ($stmt->rowCount() > 0) {
        // Update existing
        $stmt = $pdo->prepare("
            UPDATE checklist_verifikasi 
            SET status = ?, catatan = ?, updated_at = CURRENT_TIMESTAMP 
            WHERE ujian_id = ? AND peserta_id = ? AND station_id = ? 
            AND penguji_id = ? AND checklist_item = ?
        ");
        $result = $stmt->execute([$status, $catatan, $ujian_id, $peserta_id, $station_id, $penguji_id, $checklist_item]);
    } else {
        // Insert new
        $stmt = $pdo->prepare("
            INSERT INTO checklist_verifikasi 
            (ujian_id, peserta_id, station_id, penguji_id, aspek_id, checklist_item, status, catatan) 
            VALUES (?, ?, ?, ?, ?, ?, ?, ?)
        ");
        $result = $stmt->execute([$ujian_id, $peserta_id, $station_id, $penguji_id, $aspek_id, $checklist_item, $status, $catatan]);
    }
    
    if ($result) {
        echo json_encode(['success' => true, 'message' => 'Checklist tersimpan']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Gagal menyimpan']);
    }
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
?>