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

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

// Ambil kelas yang diampu oleh wali kelas
$username = $_SESSION['username'];
$wali_kelas = mysqli_fetch_assoc(mysqli_query($conn, "SELECT kelas FROM wali_kelas WHERE nip_wali='$username' LIMIT 1"));
$kelas_diampu = $wali_kelas['kelas'] ?? '';

if (empty($kelas_diampu)) {
    die("<script>alert('Anda tidak memiliki kelas yang diampu!'); window.location='dashboard_wali_kelas.php';</script>");
}

$tanggal = $_GET['tanggal'] ?? date('Y-m-d');
?>
<!DOCTYPE html>
<html>
<head>
  <title>Siswa Belum Absen - <?php echo $kelas_diampu; ?></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">
  <style>
    .btn-wa {
        background: #25D366;
        border-color: #25D366;
        color: white;
    }
    .btn-wa:hover {
        background: #128C7E;
        border-color: #128C7E;
        color: white;
    }
    .table-responsive {
        max-height: 600px;
        overflow-y: auto;
    }
  </style>
</head>
<body class="container mt-4">
  <h2>📊 Siswa Belum Absen - Kelas <?php echo $kelas_diampu; ?></h2>
  <a href="dashboard_wali_kelas.php" class="btn btn-secondary mb-3">← Kembali</a>

  <form method="get" class="mb-3 row g-2 align-items-center">
    <div class="col-auto">
      <label for="tanggal" class="form-label mb-0">Tanggal:</label>
      <input type="date" name="tanggal" value="<?= $tanggal ?>" class="form-control">
    </div>
    <div class="col-auto">
      <button class="btn btn-primary">🔍 Tampilkan</button>
    </div>
    <div class="col-auto">
      <span class="badge bg-info">Format: YYYY-MM-DD</span>
    </div>
  </form>

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

  $total_belum_absen = mysqli_num_rows($q);
  ?>

  <div class="alert alert-info">
    <strong>📅 Tanggal: <?= $tanggal ?></strong> | 
    <strong>👥 Total Siswa Belum Absen: <?= $total_belum_absen ?> orang</strong>
  </div>

  <div class="table-responsive">
    <table class="table table-bordered table-hover table-sm">
      <thead class="table-light">
        <tr>
          <th width="5%">No</th>
          <th width="15%">NIS</th>
          <th>Nama Siswa</th>
          <th width="10%">Kelas</th>
          <th width="15%">No WhatsApp</th>
          <th width="20%">Aksi</th>
        </tr>
      </thead>
      <tbody>
        <?php
        if ($total_belum_absen > 0) {
          $no = 1;
          while ($d = mysqli_fetch_assoc($q)) {
            // Format pesan WhatsApp
            $pesan = "Assalamu'alaikum Bapak/Ibu Wali Murid,\n\n"
                    . "Bersama ini kami sampaikan bahwa:\n\n"
                    . "📌 *INFORMASI KEHADIRAN SISWA*\n"
                    . "👤 Nama: *{$d['nama']}*\n"
                    . "🎒 Kelas: *{$d['kelas']}*\n"
                    . "🔢 NIS: *{$d['nis']}*\n"
                    . "📅 Tanggal: *" . date('d/m/Y', strtotime($tanggal)) . "*\n\n"
                    . "📝 *STATUS: BELUM MELAKUKAN ABSENSI*\n\n"
                    . "Mohon perhatian dan konfirmasi Bapak/Ibu mengenai ketidakhadiran ananda.\n\n"
                    . "Terima kasih atas perhatiannya.\n\n"
                    . "Salam,\nWali Kelas {$kelas_diampu}";

            $urlPesan = "https://wa.me/" . $d['no_wa'] . "?text=" . urlencode($pesan);
            
            // Tombol untuk satu per satu
            $urlSingle = "https://wa.me/" . $d['no_wa'] . "?text=" . urlencode($pesan);
            
            echo "<tr>";
            echo "<td class='text-center'>{$no}</td>";
            echo "<td>{$d['nis']}</td>";
            echo "<td>{$d['nama']}</td>";
            echo "<td class='text-center'>{$d['kelas']}</td>";
            echo "<td>" . ($d['no_wa'] ? $d['no_wa'] : '<span class="text-muted">Tidak ada</span>') . "</td>";
            echo "<td class='text-center'>";
            
            if ($d['no_wa']) {
                echo "<a href='$urlSingle' target='_blank' class='btn btn-wa btn-sm'>";
                echo "📲 Kirim WA";
                echo "</a>";
            } else {
                echo "<span class='badge bg-secondary'>No WA tidak ada</span>";
            }
            
            echo "</td>";
            echo "</tr>";
            $no++;
          }
        } else {
          echo "<tr><td colspan='6' class='text-center text-success py-3'>";
          echo "<i class='fas fa-check-circle fa-2x mb-2'></i><br>";
          echo "<strong>Selamat! Semua siswa di kelas $kelas_diampu sudah absen pada tanggal ini.</strong>";
          echo "</td></tr>";
        }
        ?>
      </tbody>
    </table>
  </div>

  <?php if ($total_belum_absen > 0): ?>
  <div class="card mt-4">
    <div class="card-header bg-warning text-dark">
      <strong>🚀 Aksi Cepat</strong>
    </div>
    <div class="card-body">
      <p class="card-text">Anda dapat mengirim pesan ke semua orang tua sekaligus:</p>
      
      <?php
      // Buat pesan untuk semua
      mysqli_data_seek($q, 0);
      $all_numbers = [];
      $all_names = [];
      
      while ($d = mysqli_fetch_assoc($q)) {
          if ($d['no_wa']) {
              $all_numbers[] = $d['no_wa'];
              $all_names[] = $d['nama'];
          }
      }
      
      if (!empty($all_numbers)) {
          $pesan_group = "Assalamu'alaikum Bapak/Ibu Wali Murid,\n\n"
                        . "Bersama ini kami sampaikan informasi kehadiran siswa Kelas {$kelas_diampu}:\n\n"
                        . "📅 Tanggal: *" . date('d/m/Y', strtotime($tanggal)) . "*\n"
                        . "📝 *SISWA YANG BELUM ABSEN:*\n\n";
          
          $no_list = 1;
          mysqli_data_seek($q, 0);
          while ($d = mysqli_fetch_assoc($q)) {
              if ($d['no_wa']) {
                  $pesan_group .= "{$no_list}. {$d['nama']} (NIS: {$d['nis']})\n";
                  $no_list++;
              }
          }
          
          $pesan_group .= "\nMohon konfirmasi mengenai ketidakhadiran ananda.\n\n"
                         . "Terima kasih atas perhatiannya.\n\n"
                         . "Salam,\nWali Kelas {$kelas_diampu}";
          
          $first_number = $all_numbers[0];
          $url_group = "https://wa.me/$first_number?text=" . urlencode($pesan_group);
      ?>
      
      <div class="d-grid gap-2">
        <a href="<?= $url_group ?>" target="_blank" class="btn btn-wa btn-lg">
          📨 Kirim ke Semua Orang Tua
        </a>
        <small class="text-muted">* Pesan akan dikirim ke nomor pertama, lalu bisa diteruskan ke grup WA</small>
      </div>
      <?php } ?>
    </div>
  </div>
  <?php endif; ?>

  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/js/all.min.js"></script>
</body>
</html>