<?php
include '../../koneksi.php';

if (!isset($_GET['id'])) {
  die("ID tidak ditemukan");
}

$id = $_GET['id'];
$data = mysqli_fetch_assoc(
  mysqli_query($koneksi,"SELECT * FROM absensi WHERE id='$id'")
);

$success = false;

if (isset($_POST['update'])) {

  mysqli_query($koneksi,"UPDATE absensi SET 
    jam_masuk   = '$_POST[jam_masuk]',
    jam_pulang  = '$_POST[jam_pulang]',
    status      = '$_POST[status]'
    WHERE id    = '$id'
  ");

  $success = true;
}
?>

<!DOCTYPE html>
<html lang="id">
<head>
<meta charset="UTF-8">
<title>Edit Absensi</title>

<link href="../../bootstrap-5.3.8-dist/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<style>
body { background:#f4f6f9; }
.card {
  border-radius:18px;
  box-shadow:0 12px 35px rgba(0,0,0,.12);
}
</style>
</head>

<body>

<div class="container mt-4">
<div class="card p-4">

<h4 class="fw-bold mb-4">
  <i class="bi bi-pencil-square"></i> Edit Absensi
</h4>

<form method="post">

  <div class="mb-3">
    <label class="form-label">Jam Masuk</label>
    <input type="time"
      name="jam_masuk"
      value="<?= $data['jam_masuk']; ?>"
      class="form-control"
      required>
  </div>

  <div class="mb-3">
    <label class="form-label">Jam Pulang</label>
    <input type="time"
      name="jam_pulang"
      value="<?= $data['jam_pulang']; ?>"
      class="form-control">
  </div>

  <div class="mb-4">
    <label class="form-label">Status</label>
    <select name="status" class="form-select">
      <?php foreach (['Hadir','Izin','Sakit','Alpa'] as $s): ?>
        <option <?= $data['status']==$s?'selected':'' ?>>
          <?= $s ?>
        </option>
      <?php endforeach; ?>
    </select>
  </div>

  <div class="d-flex gap-2">
    <button name="update"
      class="btn btn-primary rounded-pill px-4">
      <i class="bi bi-save"></i> Simpan
    </button>

    <button type="button"
      onclick="kembali()"
      class="btn btn-secondary rounded-pill px-4">
      Kembali
    </button>
  </div>

</form>

</div>
</div>

<?php if ($success): ?>
<script>
Swal.fire({
  icon: 'success',
  title: 'Berhasil',
  text: 'Data absensi berhasil diperbarui',
  timer: 1500,
  showConfirmButton: false
}).then(() => {
  try {
    parent.document.getElementById('iframeContent').src = 'kelola_absen/absen.php';
  } catch {
    window.location.href = 'absen.php';
  }
});
</script>
<?php endif; ?>

<script>
function kembali() {
  try {
    parent.document.getElementById('iframeContent').src = 'kelola_absen/absen.php';
  } catch {
    window.location.href = 'absen.php';
  }
}
</script>

</body>
</html>
