<?php
include 'koneksi.php';
include 'auth.php';         // Mengecek login
include 'akses_ditolak.php'; // Tambahkan ini

// Ambil data absen untuk bulan ini (atau berdasarkan filter)
$filter_bulan = isset($_GET['bulan']) ? $_GET['bulan'] : date('m');
$filter_tahun = isset($_GET['tahun']) ? $_GET['tahun'] : date('Y');

// Hitung nilai absen per user
$nilaiQuery = "
  SELECT 
    nama_asli,
    SUM(CASE 
        WHEN status = 'S' THEN 1
        WHEN status = 'I' THEN 2
        WHEN status = 'A' THEN 5
        ELSE 0 END) AS total_nilai,
    COUNT(*) as total_hari
  FROM absensi
  WHERE MONTH(tanggal) = '$filter_bulan' AND YEAR(tanggal) = '$filter_tahun'
  GROUP BY nama_asli
  ORDER BY total_nilai DESC
  LIMIT 3
";

$nilaiResult = mysqli_query($koneksi, $nilaiQuery);

// Filter
$tanggal_hari_ini = date('Y-m-d');
$filter_nama = isset($_GET['nama']) ? $_GET['nama'] : '';
$filter_tanggal = isset($_GET['tanggal']) ? $_GET['tanggal'] : $tanggal_hari_ini;

// Ambil data user untuk dropdown
$users = mysqli_query($koneksi, "SELECT id, nama_asli FROM user ORDER BY nama_asli ASC");

// ======== PAGINATION SETUP ========
$limit = 100;
$page = isset($_GET['page']) ? (int) $_GET['page'] : 1;
$page = max($page, 1);
$offset = ($page - 1) * $limit;

// Hitung total data
$countQuery = "SELECT COUNT(*) as total FROM absensi WHERE MONTH(tanggal) = '$filter_bulan' AND YEAR(tanggal) = '$filter_tahun'";
if ($filter_nama != '') {
  $countQuery .= " AND nama_asli LIKE '%$filter_nama%'";
}
$countResult = mysqli_query($koneksi, $countQuery);
$countData = mysqli_fetch_assoc($countResult);
$totalData = $countData['total'];
$totalPages = ceil($totalData / $limit);

// Query utama
$query = "SELECT * FROM absensi WHERE MONTH(tanggal) = '$filter_bulan' AND YEAR(tanggal) = '$filter_tahun'";
if ($filter_nama != '') {
  $query .= " AND nama_asli LIKE '%$filter_nama%'";
}
$query .= " ORDER BY tanggal DESC LIMIT $limit OFFSET $offset";

$result = mysqli_query($koneksi, $query);
if (!$result) {
  echo "Query error: " . mysqli_error($koneksi);
  exit;
}
?>
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>Catat Absen</title>
  <link rel="stylesheet" href="css/navbar.css" />
  <link rel="stylesheet" href="css/admin.css" />
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
  <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
</head>
<style>
  #floatingButton {
    position: fixed;
    bottom: 70px;
    /* beri jarak agar tidak menutupi navbar */
    right: 20px;
    background: linear-gradient(#ffe680, #ffcc00);
    color: #1e1e1e;
    border: none;
    border-radius: 50%;
    width: 60px;
    height: 60px;
    font-size: 24px;
    font-weight: bold;
    box-shadow:
      0 2px 0 #d1a700,
      0 4px 10px rgba(0, 0, 0, 0.18),
      inset 0 2px 4px rgba(255, 255, 255, 0.45);
    cursor: pointer;
    z-index: 999;
    transition: background-color 0.2s;
  }

  #floatingButton:hover {
    background: linear-gradient(#ffe680, #ffcc00);
  }

  thead th {
    position: sticky;
    top: 0;
    background: #233a6a;
    color: #f5d216;
    z-index: 1;
  }
</style>

<body>

  <h4>CATAT ABSEN</h4>

  <!-- Filter -->
  <form method="GET" style="margin-bottom: 5px;">

    <div style="display: flex; gap: 10px; margin-top: 8px;">
      <select name="bulan" onchange="this.form.submit()"
        style="padding: 6px 8px; border-radius: 6px;   border: 3px solid rgba(255, 255, 255, 0.35); background: rgba(255, 255, 255, 0.2); color: #fed054;">
        <?php
        $bulanList = [
          '01' => 'Januari',
          '02' => 'Februari',
          '03' => 'Maret',
          '04' => 'April',
          '05' => 'Mei',
          '06' => 'Juni',
          '07' => 'Juli',
          '08' => 'Agustus',
          '09' => 'September',
          '10' => 'Oktober',
          '11' => 'November',
          '12' => 'Desember'
        ];
        foreach ($bulanList as $val => $label) {
          $selected = $val == $filter_bulan ? 'selected' : '';
          echo "<option value='$val' $selected>$label</option>";
        }
        ?>
      </select>

      <select name="tahun" onchange="this.form.submit()"
        style="padding: 6px 8px; border-radius: 6px; border: 3px solid rgba(255, 255, 255, 0.35); background: rgba(255, 255, 255, 0.2); color: #fed054;">
        <?php
        $tahun_sekarang = date('Y');
        for ($i = $tahun_sekarang; $i >= $tahun_sekarang - 5; $i--) {
          $selected = $i == $filter_tahun ? 'selected' : '';
          echo "<option value='$i' $selected>$i</option>";
        }
        ?>
      </select>
    </div>

    <div style="position: relative;">
      <input type="text" id="filter_nama" name="nama" placeholder="Ketik nama..."
        value="<?= htmlspecialchars($filter_nama) ?>" autocomplete="off"
        style="width: 100%; padding: 6px 8px; border-radius: 6px; border: 3px solid rgba(255, 255, 255, 0.35); background: rgba(255, 255, 255, 0.2); color: #fed054;">
      <div id="filter_suggestions" style="
          position: absolute;
          z-index: 99;
          background: #233a6a;
          border: 1px solid #444;
          border-radius: 6px;
          max-height: 150px;
          overflow-y: auto;
          display: none;
          width: 100%;
          color: #fed054;
          font-size: 14px;"></div>
    </div>
  </form>

  <?php if (mysqli_num_rows($nilaiResult) > 0): ?>
    <div style="margin-bottom: 10px; padding:10px; background: #2e2e2e; border:1px solid #fed054; color:#fed054; border-radius:8px;">
      <strong>Absensi Terburuk <?= date('F Y', mktime(0, 0, 0, $filter_bulan, 1, $filter_tahun)) ?> :</strong><br>
      <ol style="margin-top:5px;">
        <?php while ($row = mysqli_fetch_assoc($nilaiResult)): ?>
          <li><?= htmlspecialchars($row['nama_asli']) ?> - <?= $row['total_nilai'] ?> poin (<?= $row['total_hari'] ?> hari)</li>
        <?php endwhile; ?>
      </ol>
    </div>
  <?php endif; ?>

  <!-- Tabel -->
  <div class="table-container" style="font-size:14px; max-height: 45vh; min-height: 45vh;">
    <table>
      <thead>
        <tr>
          <th>Tanggal</th>
          <th>Nama</th>
          <th>S</th>
          <th>I</th>
          <th>C</th>
          <th>A</th>
          <th>🗑</th>
        </tr>
      </thead>
      <tbody id="tabelBody">
        <?php if (mysqli_num_rows($result) > 0): ?>
          <?php while ($r = mysqli_fetch_assoc($result)):
            $S = $r['status'] == 'S' ? '🔵' : '';
            $I = $r['status'] == 'I' ? '🟡' : '';
            $C = $r['status'] == 'C' ? '🟢' : '';
            $A = $r['status'] == 'A' ? '🔴' : '';
          ?>
            <tr>
              <?php
              $bulanIndo = ['Jan', 'Feb', 'Mar', 'Apr', 'Mei', 'Jun', 'Jul', 'Agu', 'Sep', 'Okt', 'Nov', 'Des'];
              $time = strtotime($r['tanggal']);
              $bulan = $bulanIndo[date('n', $time) - 1];
              $hari = date('d', $time);
              $tampil_tanggal = $bulan . ' ' . $hari;
              $namaLengkap = htmlspecialchars($r['nama_asli']);
              $namaTampil = $r['nama_asli'];
              if (mb_strlen($namaTampil) > 10) {
                $namaTampil = mb_substr($namaTampil, 0, 10) . '...';
              }
              ?>
              <td><?= $tampil_tanggal ?></td>
              <td
                style="max-width: 120px; text-align:left; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">
                <span style="cursor: pointer; display: inline-block; width: 100%;"
                  onclick="tampilkanNamaLengkap('<?= $namaLengkap ?>')">
                  <?= htmlspecialchars($namaTampil) ?>
                </span>
              </td>
              <td><?= $S ?></td>
              <td><?= $I ?></td>
              <td><?= $C ?></td>
              <td><?= $A ?></td>
              <td><button
                  style="background-color:red; width:50%; height:10px; font-size:20px; padding:10px; text-align:center;"
                  class="btn-hapus" data-id="<?= $r['id'] ?>"></button></td>
            </tr>
          <?php endwhile; ?>
        <?php else: ?>
          <tr>
            <td colspan="7" style="text-align:center; color:red;">Tidak ada data</td>
          </tr>
        <?php endif; ?>
      </tbody>
    </table>
  </div>

  <div style="text-align: center;">
    <?php if ($totalPages > 1): ?>
      <div style="display: inline-block; padding: 10px;">
        <?php if ($page > 1): ?>
          <a href="?bulan=<?= $filter_bulan ?>&tahun=<?= $filter_tahun ?>&nama=<?= urlencode($filter_nama) ?>&page=<?= $page - 1 ?>"
            style="margin-right: 10px;">⬅️</a>
        <?php endif; ?>

        <span>Page <?= $page ?> dari <?= $totalPages ?></span>

        <?php if ($page < $totalPages): ?>
          <a href="?bulan=<?= $filter_bulan ?>&tahun=<?= $filter_tahun ?>&nama=<?= urlencode($filter_nama) ?>&page=<?= $page + 1 ?>"
            style="margin-left: 10px;">➡️</a>
        <?php endif; ?>
      </div>
    <?php endif; ?>
  </div>

  <button onclick="tambahAbsen()" id="floatingButton">
    <i class="fas fa-plus"></i>
  </button>


  <?php include 'navbar4.php'; ?>
  <script>
    const dataNamaFilter = [
      <?php
      mysqli_data_seek($users, 0);
      while ($u = mysqli_fetch_assoc($users)) {
        echo "'" . htmlspecialchars($u['nama_asli'], ENT_QUOTES) . "',";
      }
      ?>
    ];

    const filterInput = document.getElementById('filter_nama');
    const suggestionBox = document.getElementById('filter_suggestions');

    filterInput.addEventListener('input', () => {
      const keyword = filterInput.value.toLowerCase();
      const matches = dataNamaFilter.filter(nama => nama.toLowerCase().includes(keyword));
      suggestionBox.innerHTML = '';
      if (matches.length > 0 && keyword.length > 0) {
        suggestionBox.style.display = 'block';
        matches.forEach(nama => {
          const div = document.createElement('div');
          div.textContent = nama;
          div.style.padding = '8px';
          div.style.cursor = 'pointer';
          div.style.borderBottom = '1px solid #444';
          div.style.color = '#ffd700';
          div.addEventListener('click', () => {
            filterInput.value = nama;
            suggestionBox.style.display = 'none';
            filterInput.form.submit();
          });
          suggestionBox.appendChild(div);
        });
      } else {
        suggestionBox.style.display = 'none';
      }
    });

    document.addEventListener('click', function(e) {
      if (!filterInput.contains(e.target) && !suggestionBox.contains(e.target)) {
        suggestionBox.style.display = 'none';
      }
    });

    // ✅ DIPINDAH KE LUAR $(document).ready)
    function tambahAbsen() {
      Swal.fire({
        title: 'Tambah Absen',
        html: `
        <input type="date" id="tanggal_input" class="swal2-input" value="<?= date('Y-m-d') ?>">
        <input type="text" id="nama_input" class="swal2-input" placeholder="Ketik nama..." autocomplete="off">
        <div id="suggestions" style="max-height:150px; overflow-y:auto; background:#222; color:#ffd700; border-radius:6px; display:none; text-align:left; padding:4px 0;"></div>

        <select id="status" class="swal2-input">
          <option value="">Pilih Status</option>
          <option value="S">Sakit</option>
          <option value="I">Izin</option>
          <option value="C">Cuti</option>
          <option value="A">Mangkir</option>
        </select>
      `,
        didOpen: () => {
          const input = document.getElementById('nama_input');
          const suggestions = document.getElementById('suggestions');

          const dataNama = [
            <?php mysqli_data_seek($users, 0);
            while ($u = mysqli_fetch_assoc($users)) {
              echo "{ id: '{$u['id']}', nama: '" . htmlspecialchars($u['nama_asli'], ENT_QUOTES) . "' },";
            } ?>
          ];

          input.addEventListener('input', () => {
            const keyword = input.value.toLowerCase();
            const matches = dataNama.filter(n => n.nama.toLowerCase().includes(keyword));
            suggestions.innerHTML = '';
            if (matches.length > 0 && keyword.length > 0) {
              suggestions.style.display = 'block';
              matches.forEach(item => {
                const div = document.createElement('div');
                div.textContent = item.nama;
                div.style.padding = '8px 12px';
                div.style.cursor = 'pointer';
                div.style.borderBottom = '1px solid #333';
                div.style.backgroundColor = '#1e1e1e';
                div.style.color = '#ffd700';
                div.addEventListener('click', () => {
                  input.value = item.nama;
                  input.setAttribute('data-id', item.id);
                  suggestions.style.display = 'none';
                });
                div.addEventListener('mouseover', () => {
                  div.style.backgroundColor = '#333';
                });
                div.addEventListener('mouseout', () => {
                  div.style.backgroundColor = '#1e1e1e';
                });
                suggestions.appendChild(div);
              });
            } else {
              suggestions.style.display = 'none';
            }
          });
        },
        showCancelButton: true,
        confirmButtonText: 'Simpan',
        preConfirm: () => {
          const tanggal = document.getElementById('tanggal_input').value;
          const nama = document.getElementById('nama_input').value;
          const id = document.getElementById('nama_input').getAttribute('data-id');
          const status = document.getElementById('status').value;

          if (!tanggal || !nama || !status) {
            Swal.showValidationMessage('Semua harus diisi');
          }

          return {
            user_id: id,
            status,
            tanggal
          };
        }
      }).then(result => {
        if (result.isConfirmed) {
          $.post('simpan_absen.php', {
            user_id: result.value.user_id,
            status: result.value.status,
            tanggal: result.value.tanggal
          }, function(res) {
            Swal.fire('Tersimpan!', '', 'success').then(() => location.reload());
          }).fail(() => {
            Swal.fire('Gagal menyimpan', '', 'error');
          });
        }
      });
    }

    // ✅ Tetap di dalam $(document).ready)
    $(document).ready(function() {
      $('.btn-hapus').click(function() {
        const id = $(this).data('id');

        Swal.fire({
          title: 'Yakin ingin menghapus?',
          icon: 'warning',
          showCancelButton: true,
          confirmButtonColor: '#d33',
          cancelButtonColor: '#3085d6',
          confirmButtonText: 'Hapus',
          cancelButtonText: 'Batal'
        }).then((result) => {
          if (result.isConfirmed) {
            $.post('hapus_absen.php', {
              id: id
            }, function(response) {
              let res = {};
              try {
                res = JSON.parse(response);
              } catch {
                res = {
                  success: false,
                  message: 'Response tidak valid'
                };
              }

              if (res.success) {
                Swal.fire('Terhapus!', '', 'success').then(() => location.reload());
              } else {
                Swal.fire('Gagal menghapus', res.message || '', 'error');
              }
            });
          }
        });
      });
    });

    function tampilkanNamaLengkap(nama) {
      Swal.fire({
        title: 'Nama Lengkap',
        text: nama,
        imageWidth: 150,
        imageHeight: 150,
        imageUrl: 'img/head.png',
      });
    }
  </script>
</body>

</html>