<?php
include '../includes/auth.php';
include '../includes/functions.php';

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Metode request tidak valid']);
    exit;
}

$id_event = (int)$_POST['id_event'] ?? 0;
$pembuat = $_POST['pembuat'] ?? '';
$jabatan = $_POST['jabatan'] ?? '';
$nip = $_POST['nip'] ?? '';
$isi_notulen = $_POST['isi_notulen'] ?? '';

try {
    // Cek apakah notulen sudah ada
    $check = $conn->prepare("SELECT id_notulen FROM dafdir_event_notulen WHERE id_event = ?");
    $check->bind_param("i", $id_event);
    $check->execute();
    $check->store_result();
    
    if ($check->num_rows > 0) {
        // Update notulen yang sudah ada
        $stmt = $conn->prepare("UPDATE dafdir_event_notulen SET isi_notulen = ?, pembuat = ?, jabatan = ?, nip = ? WHERE id_event = ?");
        $stmt->bind_param("ssssi", $isi_notulen, $pembuat, $jabatan, $nip, $id_event);
    } else {
        // Buat notulen baru
        $stmt = $conn->prepare("INSERT INTO dafdir_event_notulen (id_event, isi_notulen, pembuat, jabatan, nip) VALUES (?, ?, ?, ?, ?)");
        $stmt->bind_param("issss", $id_event,  $isi_notulen, $pembuat, $jabatan, $nip);
    }
    
    if ($stmt->execute()) {
        echo json_encode(['success' => true]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Gagal menyimpan notulen']);
    }
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
?>