<?php
include 'includes/config.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 = isset($_POST['id_event']) ? (int)$_POST['id_event'] : 0;
$nama_lengkap = isset($_POST['nama_lengkap']) ? sanitize($_POST['nama_lengkap']) : '';
$jabatan = isset($_POST['jabatan']) ? sanitize($_POST['jabatan']) : '';
$tanda_tangan = isset($_POST['tanda_tangan']) ? sanitize($_POST['tanda_tangan']) : '';

// Validasi data
if (empty($nama_lengkap)) {
    echo json_encode(['success' => false, 'message' => 'Nama lengkap harus diisi']);
    exit;
}

if (empty($tanda_tangan)) {
    echo json_encode(['success' => false, 'message' => 'Tanda tangan harus disediakan']);
    exit;
}

// Cek apakah event aktif
$event = $conn->query("SELECT * FROM dafdir_event WHERE id_event = $id_event AND status = 'aktif'")->fetch_assoc();
if (!$event) {
    echo json_encode(['success' => false, 'message' => 'Event tidak ditemukan atau tidak aktif']);
    exit;
}

// Dapatkan sequence terakhir untuk event ini
$lastSequence = $conn->query("SELECT MAX(sequence) as max_seq FROM dafdir_absensi WHERE id_event = $id_event")->fetch_assoc()['max_seq'];
$newSequence = ($lastSequence !== null) ? $lastSequence + 1 : 1;

// Simpan ke database
$stmt = $conn->prepare("INSERT INTO dafdir_absensi (id_event, nama_lengkap, jabatan, tanda_tangan, sequence) VALUES (?, ?, ?, ?, ?)");
$stmt->bind_param("isssi", $id_event, $nama_lengkap, $jabatan, $tanda_tangan, $newSequence);

if ($stmt->execute()) {
    echo json_encode(['success' => true, 'message' => 'Absensi berhasil disimpan']);
} else {
    echo json_encode(['success' => false, 'message' => 'Gagal menyimpan absensi: ' . $conn->error]);
}

$stmt->close();
$conn->close();
?>