<?php
// sertakan file konfigurasi database
require_once 'config.php';

// Ambil dan sanitasi data dari form menggunakan filter_input
$nama   = filter_input(INPUT_POST, 'nama', FILTER_SANITIZE_STRING);
$alamat = filter_input(INPUT_POST, 'alamat', FILTER_SANITIZE_STRING);
$wa     = filter_input(INPUT_POST, 'wa', FILTER_SANITIZE_STRING);
$email  = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL);

// Pastikan data diperlukan tidak kosong setelah penyaringan
if (!$nama || !$alamat || !$wa || !$email) {
    die("Data yang dikirim tidak valid. Silakan periksa kembali input Anda.");
}

// Insert data awal ke tabel absensi dengan idsurat sementara (kosong)
$sql = "INSERT INTO absensi (nama, alamat, wa, email, idsurat) VALUES (:nama, :alamat, :wa, :email, '')";
$stmt = $pdo->prepare($sql);

try {
    $stmt->execute([
        ':nama'   => $nama,
        ':alamat' => $alamat,
        ':wa'     => $wa,
        ':email'  => $email
    ]);

    // Dapatkan ID (urutan) yang baru saja dihasilkan di database
    $lastId = $pdo->lastInsertId();

    // Buat format id surat sesuai ketentuan:
    // Format: [nomor urutan peserta].01 / KU/STTIKSMA/V/2025
    $formatted_idsurat = $lastId.".02/KU/STTIKSMSA/V/2025";

    // Update record yang baru saja masuk agar kolom idsurat berisi format yang benar
    $sqlUpdate = "UPDATE absensi SET idsurat = :idsurat WHERE id = :id";
    $stmtUpdate = $pdo->prepare($sqlUpdate);
    $stmtUpdate->execute([
        ':idsurat' => $formatted_idsurat,
        ':id'      => $lastId
    ]);

    $message = "Data absensi berhasil disimpan! <br>ID Surat Anda: <strong>" . $formatted_idsurat . "</strong>";
    $alertClass = "alert-success";
} catch (Exception $e) {
    $message = "Terjadi kesalahan: " . $e->getMessage();
    $alertClass = "alert-danger";
}
?>

<!DOCTYPE html>
<html lang="id">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Proses Absensi</title>
  <!-- Bootstrap CSS -->
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
  <style>
    body {
      background: #f7f7f7;
      display: flex;
      align-items: center;
      justify-content: center;
      min-height: 100vh;
    }
    .container {
      max-width: 600px;
    }
  </style>
</head>
<body>
  <div class="container text-center mt-5">
    <div class="alert <?php echo $alertClass; ?>" role="alert">
      <?php echo $message; ?>
    </div>
    <a href="index.php" class="btn btn-primary">Kembali ke Form Absensi</a>
  </div>
  <!-- Bootstrap Bundle with Popper -->
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
