<?php
require_once '../includes/auth.php';
require_once '../includes/db_connection.php';

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

// Hanya penguji yang bisa akses
if (!isPenguji()) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

// Ambil input dari POST (JSON atau form)
$input = [];
$contentType = $_SERVER['CONTENT_TYPE'] ?? '';
if (strpos($contentType, 'application/json') !== false) {
    $input = json_decode(file_get_contents('php://input'), true);
} else {
    $input = $_POST;
}

$ujian_id = $input['ujian_id'] ?? null;
$station_id = $input['station_id'] ?? null;
$peserta_id = $input['peserta_id'] ?? null;
$status = $input['status'] ?? null;

if (!$ujian_id || !$station_id || !$peserta_id || !$status) {
    echo json_encode(['success' => false, 'message' => 'Parameter tidak lengkap']);
    exit;
}

$penguji_id = $_SESSION['user_id'];

try {
    // Cek apakah sudah ada record penilaian
    $stmt = $pdo->prepare("
        SELECT id FROM penilaian 
        WHERE ujian_id = ? AND station_id = ? AND peserta_id = ? AND penguji_id = ?
        LIMIT 1
    ");
    $stmt->execute([$ujian_id, $station_id, $peserta_id, $penguji_id]);
    $existing = $stmt->fetch();
    
    if ($existing) {
        // Update status
        $stmt = $pdo->prepare("
            UPDATE penilaian 
            SET status_penilaian = ? 
            WHERE ujian_id = ? AND station_id = ? AND peserta_id = ? AND penguji_id = ?
        ");
        $result = $stmt->execute([$status, $ujian_id, $station_id, $peserta_id, $penguji_id]);
    } else {
        // Insert record awal dengan status
        $stmt = $pdo->prepare("
            INSERT INTO penilaian (ujian_id, station_id, peserta_id, penguji_id, status_penilaian, created_at)
            VALUES (?, ?, ?, ?, ?, NOW())
        ");
        $result = $stmt->execute([$ujian_id, $station_id, $peserta_id, $penguji_id, $status]);
    }
    
    if ($result) {
        echo json_encode(['success' => true]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Gagal menyimpan status']);
    }
    
} catch (PDOException $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
?>