<?php
session_start();
if (!isset($_SESSION['username']) || !in_array($_SESSION['role'], ['admin', 'guru'])) {
    header("Location: index.php");
    exit;
}

include 'config.php';
date_default_timezone_set("Asia/Jakarta");

$tanggal = $_GET['tanggal'] ?? date('Y-m-d');
$kelas   = $_GET['kelas'] ?? '';

// Proses update status absensi
if (isset($_POST['update_status'])) {
    $siswa_id = (int)$_POST['siswa_id'];
    $status = $_POST['status'];
    $keterangan = mysqli_real_escape_string($conn, $_POST['keterangan'] ?? '');
    $tanggal_absen = $_POST['tanggal_absen'];
    
    // Cek apakah sudah ada record absensi
    $check = mysqli_query($conn, "SELECT id, jam FROM absensi WHERE siswa_id = $siswa_id AND tanggal = '$tanggal_absen'");
    
    if (mysqli_num_rows($check) > 0) {
        // Jika status bukan Hadir (H), set jam menjadi NULL
        if ($status != 'H') {
            $query = "UPDATE absensi SET status = '$status', keterangan = '$keterangan', jam = NULL WHERE siswa_id = $siswa_id AND tanggal = '$tanggal_absen'";
        } else {
            $query = "UPDATE absensi SET status = '$status', keterangan = '$keterangan' WHERE siswa_id = $siswa_id AND tanggal = '$tanggal_absen'";
        }
    } else {
        // Insert new
        if ($status == 'H') {
            // Jika Hadir, gunakan jam sekarang
            $jam_sekarang = date('H:i:s');
            $query = "INSERT INTO absensi (siswa_id, tanggal, jam, status, keterangan) VALUES ($siswa_id, '$tanggal_absen', '$jam_sekarang', '$status', '$keterangan')";
        } else {
            // Jika Izin/Sakit/Alpa, jam diisi NULL
            $query = "INSERT INTO absensi (siswa_id, tanggal, jam, status, keterangan) VALUES ($siswa_id, '$tanggal_absen', NULL, '$status', '$keterangan')";
        }
    }
    
    if (mysqli_query($conn, $query)) {
        echo "<script>
            alert('Status absensi berhasil diperbarui!');
            window.location.href = 'belum_absensi.php?tanggal=$tanggal_absen&kelas=" . urlencode($kelas) . "';
        </script>";
        exit;
    } else {
        echo "<script>alert('Gagal memperbarui status: " . mysqli_error($conn) . "');</script>";
    }
}
?>
<!DOCTYPE html>
<html>
<head>
  <title>Daftar Siswa Belum Ada Record Absensi</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css">
  <style>
    .no-wa-missing { color: #dc3545; font-weight: bold; }
    .no-wa-available { color: #28a745; }
    .btn-send-wa { background-color: #25D366; color: white; }
    .btn-send-wa:hover { background-color: #1da851; color: white; }
    .badge-status { font-size: 0.75em; padding: 3px 8px; border-radius: 12px; }
    .status-hadir { background-color: #d4edda; color: #155724; }
    .status-izin { background-color: #cce5ff; color: #004085; }
    .status-sakit { background-color: #f8d7da; color: #721c24; }
    .status-alpa { background-color: #fff3cd; color: #856404; }
    .btn-edit-status { background-color: #ffc107; color: #212529; }
    .btn-edit-status:hover { background-color: #e0a800; color: #212529; }
  </style>
</head>
<body class="container mt-4">
  <div class="d-flex justify-content-between align-items-center mb-4">
    <h2><i class="bi bi-person-x"></i> Daftar Siswa Belum Absensi</h2>
    <a href="dashboard.php" class="btn btn-secondary"><i class="bi bi-arrow-left"></i> Kembali</a>
  </div>

  <div class="card mb-4">
    <div class="card-body">
      <form method="get" class="row g-3 align-items-end">
        <div class="col-md-4">
          <label for="tanggal" class="form-label"><strong>Tanggal</strong></label>
          <input type="date" name="tanggal" value="<?= $tanggal ?>" class="form-control">
        </div>
        <div class="col-md-4">
          <label for="kelas" class="form-label"><strong>Kelas</strong></label>
          <select name="kelas" class="form-select">
            <option value="">Semua Kelas</option>
            <?php
            $qkelas = mysqli_query($conn, "SELECT DISTINCT kelas FROM siswa WHERE status='aktif' ORDER BY kelas");
            while ($k = mysqli_fetch_assoc($qkelas)) {
              $selected = $k['kelas'] == $kelas ? 'selected' : '';
              echo "<option value='{$k['kelas']}' $selected>{$k['kelas']}</option>";
            }
            ?>
          </select>
        </div>
        <div class="col-md-4 d-flex gap-2">
          <button class="btn btn-primary"><i class="bi bi-search"></i> Tampilkan</button>
          <a href="belum_absensi.php" class="btn btn-outline-secondary">Reset</a>
        </div>
      </form>
    </div>
  </div>

  <div class="card">
    <div class="card-header d-flex justify-content-between align-items-center">
      <h5 class="mb-0"><i class="bi bi-list-check"></i> Hasil Pencarian</h5>
      <?php
      // Hitung total siswa yang belum absen
      $filterKelasCount = $kelas ? "AND s.kelas = '$kelas'" : '';
      $countQuery = mysqli_query($conn, "
        SELECT COUNT(*) as total 
        FROM siswa s 
        WHERE s.status='aktif' $filterKelasCount 
          AND NOT EXISTS (
            SELECT 1 FROM absensi a 
            WHERE a.siswa_id = s.id AND a.tanggal = '$tanggal'
          )
      ");
      $totalData = mysqli_fetch_assoc($countQuery)['total'] ?? 0;
      ?>
      <span class="badge bg-primary">Total: <?= $totalData ?> Siswa</span>
    </div>
    <div class="card-body">
      <div class="table-responsive">
        <table class="table table-bordered table-striped table-hover">
          <thead class="table-light">
            <tr>
              <th>No</th>
              <th>NIS</th>
              <th>Nama</th>
              <th>Kelas</th>
              <th>Nomor WhatsApp</th>
              <th>Status WA</th>
              <th>Aksi</th>
            </tr>
          </thead>
          <tbody>
            <?php
            $filterKelas = $kelas ? "AND s.kelas = '$kelas'" : '';

            $q = mysqli_query($conn, "
              SELECT s.id, s.nis, s.nama, s.kelas, s.no_wa
              FROM siswa s
              WHERE s.status='aktif' $filterKelas
                AND NOT EXISTS (
                  SELECT 1 FROM absensi a
                  WHERE a.siswa_id = s.id
                    AND a.tanggal = '$tanggal'
                )
              ORDER BY s.kelas, s.nama
            ");

            if (mysqli_num_rows($q) > 0) {
              $no = 1;
              $kelas_sebelum = '';
              while ($d = mysqli_fetch_assoc($q)) {
                // Tampilkan header kelas jika berbeda
                if ($kelas_sebelum != $d['kelas'] && empty($kelas)) {
                  if ($kelas_sebelum != '') {
                    echo "<tr><td colspan='7' class='bg-light fw-bold text-primary'>KELAS {$d['kelas']}</td></tr>";
                  } else {
                    echo "<tr><td colspan='7' class='bg-light fw-bold text-primary'>KELAS {$d['kelas']}</td></tr>";
                  }
                  $kelas_sebelum = $d['kelas'];
                  $no = 1;
                } elseif (!empty($kelas) && $kelas_sebelum == '') {
                  $kelas_sebelum = $d['kelas'];
                }

                // Cek nomor WA
                $no_wa = !empty($d['no_wa']) ? $d['no_wa'] : '';
                
                // Format nomor WA untuk link
                $no_wa_formatted = '';
                $status_wa = '';
                $status_class = '';
                if (!empty($no_wa)) {
                  $clean_no = preg_replace('/[^0-9]/', '', $no_wa);
                  if (substr($clean_no, 0, 1) == '0') {
                    $clean_no = '62' . substr($clean_no, 1);
                  }
                  if (substr($clean_no, 0, 1) == '8') {
                    $clean_no = '62' . $clean_no;
                  }
                  $no_wa_formatted = $clean_no;
                  $status_wa = 'Tersedia';
                  $status_class = 'no-wa-available';
                } else {
                  $status_wa = 'Tidak Tersedia';
                  $status_class = 'no-wa-missing';
                }

                // Pesan untuk dibagikan ke WhatsApp
                $tanggal_indo = date('d/m/Y', strtotime($tanggal));
                $pesan  = "Assalamu'alaikum Wr. Wb.\n\n";
                $pesan .= "Kami informasikan bahwa ananda *{$d['nama']}* \n";
                $pesan .= "(NIS: {$d['nis']}, Kelas: {$d['kelas']}) \n";
                $pesan .= "belum tercatat hadir pada tanggal *{$tanggal_indo}*.\n\n";
                $pesan .= "Mohon perhatian dan konfirmasi dari Bapak/Ibu. 🙏\n\n";
                $pesan .= "Terima kasih.";

                $urlPesan = "https://wa.me/{$no_wa_formatted}?text=" . urlencode($pesan);

                echo "<tr>
                  <td>{$no}</td>
                  <td>{$d['nis']}</td>
                  <td><strong>{$d['nama']}</strong></td>
                  <td>{$d['kelas']}</td>
                  <td>
                    " . (!empty($no_wa) ? htmlspecialchars($no_wa) : '<span class="text-danger">-</span>') . "
                  </td>
                  <td>
                    <span class='badge badge-status $status_class'>
                      " . ($status_wa == 'Tersedia' ? '✅' : '❌') . " $status_wa
                    </span>
                  </td>
                  <td>
                    <div class='btn-group' role='group'>
                      <button type='button' class='btn btn-edit-status btn-sm' data-bs-toggle='modal' data-bs-target='#editStatusModal' 
                              data-id='{$d['id']}' data-nama='{$d['nama']}' data-nis='{$d['nis']}' data-kelas='{$d['kelas']}' 
                              data-tanggal='{$tanggal}' title='Edit Status Absensi'>
                        <i class='bi bi-pencil-square'></i> Status
                      </button>
                      " . (!empty($no_wa_formatted) ? "
                      <a href='$urlPesan' target='_blank' class='btn btn-send-wa btn-sm' title='Kirim WA'>
                        <i class='bi bi-whatsapp'></i>
                      </a>
                      " : "
                      <button class='btn btn-secondary btn-sm' disabled title='Nomor WA tidak tersedia'>
                        <i class='bi bi-whatsapp'></i>
                      </button>
                      ") . "
                    </div>
                  </td>
                </tr>";
                $no++;
              }
            } else {
              echo "<tr><td colspan='7' class='text-center py-4'>
                <i class='bi bi-check-circle text-success display-4 d-block mb-2'></i>
                <strong>Semua siswa sudah ada record absensi pada tanggal ini</strong>
              </td></tr>";
            }
            ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>

  <!-- Modal Edit Status Absensi -->
  <div class="modal fade" id="editStatusModal" tabindex="-1" aria-labelledby="editStatusModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-sm">
      <div class="modal-content">
        <div class="modal-header">
          <h6 class="modal-title" id="editStatusModalLabel">
            <i class="bi bi-pencil-square"></i> Edit Status
          </h6>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <form method="POST">
          <div class="modal-body">
            <input type="hidden" name="siswa_id" id="edit_siswa_id">
            <input type="hidden" name="tanggal_absen" id="edit_tanggal_absen">
            
            <div class="mb-2">
              <small class="text-muted">Nama</small>
              <div class="fw-bold" id="edit_nama">-</div>
            </div>
            
            <div class="row mb-2">
              <div class="col-6">
                <small class="text-muted">NIS</small>
                <div id="edit_nis">-</div>
              </div>
              <div class="col-6">
                <small class="text-muted">Kelas</small>
                <div id="edit_kelas">-</div>
              </div>
            </div>

            <div class="mb-2">
              <label class="form-label"><strong>Status</strong></label>
              <select name="status" class="form-select" id="edit_status" required>
                <option value="">-- Pilih Status --</option>
                <option value="H">✅ Hadir</option>
                <option value="I">📝 Izin</option>
                <option value="S">🏥 Sakit</option>
                <option value="A">❌ Alpa</option>
              </select>
              <small class="text-muted">
                <i class="bi bi-info-circle"></i> 
                <span id="status_info">Pilih status untuk mengisi absensi</span>
              </small>
            </div>

            <div class="mb-2">
              <label class="form-label"><strong>Keterangan</strong></label>
              <input type="text" name="keterangan" class="form-control form-control-sm" placeholder="Opsional..." id="edit_keterangan">
            </div>

            <div class="alert alert-info py-1 px-2 mb-0">
              <small><i class="bi bi-info-circle"></i> Tanggal: <span id="edit_tanggal_display"></span></small>
            </div>
          </div>
          <div class="modal-footer py-2">
            <button type="button" class="btn btn-secondary btn-sm" data-bs-dismiss="modal">Batal</button>
            <button type="submit" name="update_status" class="btn btn-primary btn-sm">
              <i class="bi bi-save"></i> Simpan
            </button>
          </div>
        </form>
      </div>
    </div>
  </div>

  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
  <script>
    // Event untuk modal edit status
    var editStatusModal = document.getElementById('editStatusModal');
    editStatusModal.addEventListener('show.bs.modal', function (event) {
      var button = event.relatedTarget;
      var siswaId = button.getAttribute('data-id');
      var nama = button.getAttribute('data-nama');
      var nis = button.getAttribute('data-nis');
      var kelas = button.getAttribute('data-kelas');
      var tanggal = button.getAttribute('data-tanggal');
      
      // Isi data ke modal
      document.getElementById('edit_siswa_id').value = siswaId;
      document.getElementById('edit_tanggal_absen').value = tanggal;
      document.getElementById('edit_nis').textContent = nis;
      document.getElementById('edit_nama').textContent = nama;
      document.getElementById('edit_kelas').textContent = kelas;
      document.getElementById('edit_tanggal_display').textContent = formatTanggal(tanggal);
      
      // Reset form
      document.getElementById('edit_status').value = '';
      document.getElementById('edit_keterangan').value = '';
      document.getElementById('status_info').textContent = 'Pilih status untuk mengisi absensi';
    });

    // Event ketika status berubah
    document.getElementById('edit_status').addEventListener('change', function() {
      var status = this.value;
      var info = document.getElementById('status_info');
      switch(status) {
        case 'H':
          info.innerHTML = '✅ Siswa akan dicatat HADIR dengan jam sekarang';
          break;
        case 'I':
          info.innerHTML = '📝 Siswa akan dicatat IZIN (tanpa jam masuk)';
          break;
        case 'S':
          info.innerHTML = '🏥 Siswa akan dicatat SAKIT (tanpa jam masuk)';
          break;
        case 'A':
          info.innerHTML = '❌ Siswa akan dicatat ALPA (tanpa jam masuk)';
          break;
        default:
          info.innerHTML = 'Pilih status untuk mengisi absensi';
      }
    });

    // Fungsi format tanggal
    function formatTanggal(dateString) {
      var parts = dateString.split('-');
      var bulan = {
        '01': 'Januari', '02': 'Februari', '03': 'Maret', '04': 'April',
        '05': 'Mei', '06': 'Juni', '07': 'Juli', '08': 'Agustus',
        '09': 'September', '10': 'Oktober', '11': 'November', '12': 'Desember'
      };
      return parts[2] + ' ' + bulan[parts[1]] + ' ' + parts[0];
    }
  </script>
</body>
</html>