<?= $this->include('/Styles/header'); ?>

<main class="p-6">
  <div class="bg-white shadow rounded-lg p-6">
    <div class="flex justify-between mb-4">
      <h2 class="text-2xl font-bold">Apartment List</h2>
      <a href="<?= site_url('apartment/add') ?>" class="bg-blue-600 text-white px-4 py-2 rounded">+ Add Apartment</a>
    </div>

    <?php if(session()->getFlashdata('success')): ?>
      <script>
        Swal.fire({
          icon: 'success',
          title: 'Success',
          text: '<?= session()->getFlashdata('success') ?>',
          showConfirmButton: false,
          timer: 2000
        });
      </script>
    <?php endif; ?>

    <?php if(session()->getFlashdata('error')): ?>
      <script>
        Swal.fire({
          icon: 'error',
          title: 'Error',
          text: '<?= session()->getFlashdata('error') ?>',
          showConfirmButton: false,
          timer: 2000
        });
      </script>
    <?php endif; ?>

    <table class="w-full border-collapse border">
      <thead>
        <tr class="bg-gray-100">
          <th class="border p-2">ID</th>
          <th class="border p-2">Name</th>
          <th class="border p-2">Address</th>
          <th class="border p-2">Created By</th>
          <th class="border p-2">Created At</th>
          <th class="border p-2">Actions</th>
        </tr>
      </thead>
      <tbody>
        <?php foreach($apartments as $apt): ?>
          <tr>
            <td class="border p-2"><?= $apt['id'] ?></td>
            <td class="border p-2"><?= $apt['apartName'] ?></td>
            <td class="border p-2"><?= $apt['apartAddress'] ?></td>
            <td class="border p-2"><?= $apt['createdby'] ?></td>
            <td class="border p-2"><?= $apt['createdAt'] ?></td>
            <td class="border p-2 flex gap-2">
              <a href="<?= site_url('apartment/edit/'.$apt['id']) ?>" class="bg-green-500 text-white px-2 py-1 rounded">Edit</a>
              <a href="javascript:void(0)" onclick="confirmDelete(<?= $apt['id'] ?>)" class="bg-red-500 text-white px-2 py-1 rounded">Delete</a>
            </td>
          </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  </div>
</main>

<script>
function confirmDelete(id) {
  Swal.fire({
    title: "Are you sure?",
    text: "This action cannot be undone!",
    icon: "warning",
    showCancelButton: true,
    confirmButtonColor: "#d33",
    cancelButtonColor: "#3085d6",
    confirmButtonText: "Yes, delete it!"
  }).then((result) => {
    if (result.isConfirmed) {
      window.location.href = "<?= site_url('apartment/delete/') ?>" + id;
    }
  });
}
</script>

<?= $this->include('/Styles/footer'); ?>
