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

// Fungsi untuk generate username dari NIP/NIPK
function generateUsername($nip) {
    return $nip; // Menggunakan NIP/NIPK sebagai username
}

// Tambah wali kelas (hanya admin)
if (isset($_POST['tambah_wali']) && $_SESSION['role'] === 'admin') {
    $kelas = mysqli_real_escape_string($conn, $_POST['kelas']);
    $nama_wali = mysqli_real_escape_string($conn, $_POST['nama_wali']);
    $nip_wali = mysqli_real_escape_string($conn, $_POST['nip_wali']);
    $password = mysqli_real_escape_string($conn, md5($_POST['password']));
    
    // Cek apakah NIP sudah terdaftar di tabel users
    $check = mysqli_query($conn, "SELECT id FROM users WHERE username='$nip_wali'");
    if (mysqli_num_rows($check) > 0) {
        $error = "NIP sudah terdaftar sebagai user!";
    } else {
        // Insert ke tabel wali_kelas
        mysqli_query($conn, "INSERT INTO wali_kelas (kelas, nama_wali, nip_wali, password) 
                             VALUES ('$kelas', '$nama_wali', '$nip_wali', '$password')");
        
        // Insert ke tabel users
        mysqli_query($conn, "INSERT INTO users (username, password, nama, role) 
                             VALUES ('$nip_wali', '$password', '$nama_wali', 'wali_kelas')");
        
        header("Location: wali_kelas.php");
        exit;
    }
}

// Tambah guru piket (hanya admin)
if (isset($_POST['tambah_guru']) && $_SESSION['role'] === 'admin') {
    $nipk = mysqli_real_escape_string($conn, $_POST['nipk']);
    $nama_guru = mysqli_real_escape_string($conn, $_POST['nama_guru']);
    $password = mysqli_real_escape_string($conn, md5($_POST['password']));
    
    // Cek apakah NIPK sudah terdaftar di tabel users
    $check = mysqli_query($conn, "SELECT id FROM users WHERE username='$nipk'");
    if (mysqli_num_rows($check) > 0) {
        $error_guru = "NIPK sudah terdaftar sebagai user!";
    } else {
        // Insert ke tabel guru
        mysqli_query($conn, "INSERT INTO guru (nip, nama, mapel, status) 
                             VALUES ('$nipk', '$nama_guru', 'Guru Piket', 'aktif')");
        
        // Insert ke tabel users_guru
        mysqli_query($conn, "INSERT INTO users_guru (username, nama, password, role) 
                             VALUES ('$nipk', '$nama_guru', '$password', 'guru')");
        
        // Insert ke tabel users
        mysqli_query($conn, "INSERT INTO users (username, password, nama, role) 
                             VALUES ('$nipk', '$password', '$nama_guru', 'guru')");
        
        header("Location: wali_kelas.php");
        exit;
    }
}

// Edit wali kelas
if (isset($_POST['edit_wali'])) {
    $id = intval($_POST['id']);
    $kelas = mysqli_real_escape_string($conn, $_POST['kelas']);
    $nama_wali = mysqli_real_escape_string($conn, $_POST['nama_wali']);
    $nip_wali = mysqli_real_escape_string($conn, $_POST['nip_wali']);
    $password = !empty($_POST['password']) ? mysqli_real_escape_string($conn, md5($_POST['password'])) : null;
    
    if ($_SESSION['role'] === 'admin') {
        // Update tabel wali_kelas
        if ($password) {
            mysqli_query($conn, "UPDATE wali_kelas SET kelas='$kelas', nama_wali='$nama_wali', nip_wali='$nip_wali', password='$password' WHERE id=$id");
            mysqli_query($conn, "UPDATE users SET username='$nip_wali', password='$password', nama='$nama_wali' WHERE username='$nip_wali'");
        } else {
            mysqli_query($conn, "UPDATE wali_kelas SET kelas='$kelas', nama_wali='$nama_wali', nip_wali='$nip_wali' WHERE id=$id");
            mysqli_query($conn, "UPDATE users SET username='$nip_wali', nama='$nama_wali' WHERE username='$nip_wali'");
        }
    }
    header("Location: wali_kelas.php");
    exit;
}

// Edit guru piket
if (isset($_POST['edit_guru'])) {
    $id = intval($_POST['id']);
    $nipk = mysqli_real_escape_string($conn, $_POST['nipk']);
    $nama_guru = mysqli_real_escape_string($conn, $_POST['nama_guru']);
    $status = mysqli_real_escape_string($conn, $_POST['status']);
    $password = !empty($_POST['password']) ? mysqli_real_escape_string($conn, md5($_POST['password'])) : null;
    
    if ($_SESSION['role'] === 'admin') {
        // Update tabel guru
        if ($password) {
            mysqli_query($conn, "UPDATE guru SET nip='$nipk', nama='$nama_guru', status='$status' WHERE id=$id");
            mysqli_query($conn, "UPDATE users_guru SET username='$nipk', nama='$nama_guru', password='$password' WHERE username='$nipk'");
            mysqli_query($conn, "UPDATE users SET username='$nipk', password='$password', nama='$nama_guru' WHERE username='$nipk'");
        } else {
            mysqli_query($conn, "UPDATE guru SET nip='$nipk', nama='$nama_guru', status='$status' WHERE id=$id");
            mysqli_query($conn, "UPDATE users_guru SET username='$nipk', nama='$nama_guru' WHERE username='$nipk'");
            mysqli_query($conn, "UPDATE users SET username='$nipk', nama='$nama_guru' WHERE username='$nipk'");
        }
    }
    header("Location: wali_kelas.php");
    exit;
}

// Hapus wali kelas (hanya admin)
if (isset($_GET['hapus_wali']) && $_SESSION['role'] === 'admin') {
    $id = intval($_GET['hapus_wali']);
    // Ambil nip_wali sebelum hapus
    $get_nip = mysqli_query($conn, "SELECT nip_wali FROM wali_kelas WHERE id=$id");
    $data = mysqli_fetch_assoc($get_nip);
    $nip = $data['nip_wali'];
    
    mysqli_query($conn, "DELETE FROM wali_kelas WHERE id=$id");
    mysqli_query($conn, "DELETE FROM users WHERE username='$nip'");
    
    header("Location: wali_kelas.php");
    exit;
}

// Hapus guru piket (hanya admin)
if (isset($_GET['hapus_guru']) && $_SESSION['role'] === 'admin') {
    $id = intval($_GET['hapus_guru']);
    // Ambil nip sebelum hapus
    $get_nip = mysqli_query($conn, "SELECT nip FROM guru WHERE id=$id");
    $data = mysqli_fetch_assoc($get_nip);
    $nip = $data['nip'];
    
    mysqli_query($conn, "DELETE FROM guru WHERE id=$id");
    mysqli_query($conn, "DELETE FROM users_guru WHERE username='$nip'");
    mysqli_query($conn, "DELETE FROM users WHERE username='$nip'");
    
    header("Location: wali_kelas.php");
    exit;
}

// Ambil data wali kelas dengan menambahkan kolom tipe
$waliList = mysqli_query($conn, "SELECT *, 'wali_kelas' as tipe_akun, kelas as identitas FROM wali_kelas");

// Ambil data guru piket dengan menambahkan kolom tipe
$guruList = mysqli_query($conn, "SELECT id, nip, nama, status, 'guru_piket' as tipe_akun, '-' as identitas FROM guru ORDER BY nama");

// Gabungkan kedua data
$allData = array();

while ($row = mysqli_fetch_assoc($waliList)) {
    $allData[] = $row;
}

while ($row = mysqli_fetch_assoc($guruList)) {
    $allData[] = $row;
}

// Urutkan berdasarkan nama
usort($allData, function($a, $b) {
    return strcmp($a['nama_wali'] ?? $a['nama'], $b['nama_wali'] ?? $b['nama']);
});
?>

<!DOCTYPE html>
<html lang="id">
<head>
  <meta charset="UTF-8">
  <title>Kelola Akun Wali Kelas & Guru Piket</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <!-- Bootstrap -->
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
  <!-- Font Awesome -->
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css">
  <style>
    .badge-wali {
      background-color: #4e73df;
      color: white;
      padding: 5px 10px;
      border-radius: 20px;
      font-size: 12px;
      font-weight: 500;
    }
    .badge-guru {
      background-color: #1cc88a;
      color: white;
      padding: 5px 10px;
      border-radius: 20px;
      font-size: 12px;
      font-weight: 500;
    }
    .btn-float {
      position: fixed;
      bottom: 30px;
      right: 30px;
      z-index: 999;
      border-radius: 50px;
      padding: 12px 25px;
      box-shadow: 0 4px 15px rgba(0,0,0,0.2);
    }
    .table th {
      background-color: #343a40;
      color: white;
      font-weight: 500;
    }
    .action-btn {
      margin: 0 2px;
    }
    .search-box {
      max-width: 300px;
    }
  </style>
</head>
<body class="bg-light">
<div class="container py-4">
  <!-- Header dengan Judul dan Tombol Kembali -->
  <div class="d-flex justify-content-between align-items-center mb-4">
    <div>
      <h2 class="mb-1"><i class="fas fa-users-cog me-2"></i>Kelola Akun</h2>
      <p class="text-muted">Manajemen akun wali kelas dan guru piket</p>
    </div>
    <div>
      <?php if ($_SESSION['role'] === 'admin'): ?>
        <a href="dashboard.php" class="btn btn-outline-secondary me-2">
          <i class="fas fa-arrow-left me-2"></i>Dashboard
        </a>
      <?php else: ?>
        <a href="dashboard_wali_kelas.php" class="btn btn-outline-secondary">
          <i class="fas fa-arrow-left me-2"></i>Dashboard
        </a>
      <?php endif; ?>
    </div>
  </div>

  <!-- Tombol Tambah di Pojok Kanan (Hanya Admin) -->
  <?php if ($_SESSION['role'] === 'admin'): ?>
  <div class="row mb-4">
    <div class="col-md-12">
      <div class="d-flex justify-content-end gap-2">
        <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#modalTambahWali">
          <i class="fas fa-chalkboard-teacher me-2"></i>Tambah Wali Kelas
        </button>
        <button type="button" class="btn btn-info text-white" data-bs-toggle="modal" data-bs-target="#modalTambahGuru">
          <i class="fas fa-user-clock me-2"></i>Tambah Guru Piket
        </button>
      </div>
    </div>
  </div>
  <?php endif; ?>

  <!-- Card Utama -->
  <div class="card shadow">
    <div class="card-header bg-white py-3">
      <div class="row align-items-center">
        <div class="col-md-6">
          <h5 class="mb-0"><i class="fas fa-list me-2"></i>Daftar Wali Kelas & Guru Piket</h5>
        </div>
        <div class="col-md-6">
          <div class="input-group search-box float-end">
            <span class="input-group-text bg-white"><i class="fas fa-search text-muted"></i></span>
            <input type="text" id="searchInput" class="form-control" placeholder="Cari nama atau NIP..." onkeyup="searchTable()">
          </div>
        </div>
      </div>
    </div>
    <div class="card-body table-responsive">
      <table class="table table-hover align-middle" id="dataTable">
        <thead>
          <tr>
            <th width="5%">No</th>
            <th width="12%">Tipe Akun</th>
            <th>Nama</th>
            <th>NIP / NIPK</th>
            <th>Kelas</th>
            <th>Status</th>
            <th width="15%">Aksi</th>
          </tr>
        </thead>
        <tbody>
        <?php
        $no = 1;
        foreach ($allData as $row) {
            if ($row['tipe_akun'] == 'wali_kelas') {
                // Data Wali Kelas
                $tipe = 'wali_kelas';
                $nama = $row['nama_wali'];
                $nip = $row['nip_wali'];
                $kelas = $row['kelas'];
                $status = '<span class="badge bg-success">Aktif</span>';
                $id = $row['id'];
                
                echo "<tr>";
                echo "<td>{$no}</td>";
                echo "<td><span class='badge-wali'><i class='fas fa-chalkboard-teacher me-1'></i>Wali Kelas</span></td>";
                echo "<td><strong>{$nama}</strong></td>";
                echo "<td>{$nip}</td>";
                echo "<td>{$kelas}</td>";
                echo "<td>{$status}</td>";
                echo "<td>";
                
                if ($_SESSION['role'] === 'admin') {
                    echo "<button class='btn btn-warning btn-sm action-btn' data-bs-toggle='modal' data-bs-target='#editWaliModal{$id}' title='Edit'>
                            <i class='fas fa-edit'></i>
                          </button>";
                    echo "<a href='wali_kelas.php?hapus_wali={$id}' class='btn btn-danger btn-sm action-btn' onclick=\"return confirm('Yakin hapus data wali kelas ini?')\" title='Hapus'>
                            <i class='fas fa-trash'></i>
                          </a>";
                } else {
                    echo "<span class='text-muted'>-</span>";
                }
                
                echo "</td>";
                echo "</tr>";
            } else {
                // Data Guru Piket
                $tipe = 'guru_piket';
                $nama = $row['nama'];
                $nip = $row['nip'];
                $kelas = '-';
                $status_badge = ($row['status'] == 'aktif') ? 'bg-success' : 'bg-danger';
                $status_text = ($row['status'] == 'aktif') ? 'Aktif' : 'Keluar';
                $status = "<span class='badge {$status_badge}'>{$status_text}</span>";
                $id = $row['id'];
                
                echo "<tr>";
                echo "<td>{$no}</td>";
                echo "<td><span class='badge-guru'><i class='fas fa-user-clock me-1'></i>Guru Piket</span></td>";
                echo "<td><strong>{$nama}</strong></td>";
                echo "<td>{$nip}</td>";
                echo "<td>{$kelas}</td>";
                echo "<td>{$status}</td>";
                echo "<td>";
                
                if ($_SESSION['role'] === 'admin') {
                    echo "<button class='btn btn-warning btn-sm action-btn' data-bs-toggle='modal' data-bs-target='#editGuruModal{$id}' title='Edit'>
                            <i class='fas fa-edit'></i>
                          </button>";
                    echo "<a href='wali_kelas.php?hapus_guru={$id}' class='btn btn-danger btn-sm action-btn' onclick=\"return confirm('Yakin hapus data guru piket ini?')\" title='Hapus'>
                            <i class='fas fa-trash'></i>
                          </a>";
                } else {
                    echo "<span class='text-muted'>-</span>";
                }
                
                echo "</td>";
                echo "</tr>";
            }
            $no++;
        }
        
        if (empty($allData)) {
            echo "<tr><td colspan='7' class='text-center py-4'>Belum ada data wali kelas atau guru piket</td></tr>";
        }
        ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

<!-- Modal Tambah Wali Kelas -->
<div class="modal fade" id="modalTambahWali" tabindex="-1">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header bg-primary text-white">
        <h5 class="modal-title"><i class="fas fa-chalkboard-teacher me-2"></i>Tambah Wali Kelas</h5>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
      </div>
      <form method="post">
        <div class="modal-body">
          <?php if (isset($error)): ?>
            <div class="alert alert-danger"><?= $error ?></div>
          <?php endif; ?>
          <div class="mb-3">
            <label class="form-label">Kelas <span class="text-danger">*</span></label>
            <input type="text" name="kelas" class="form-control" placeholder="Contoh: 7A, 8B, 9C" required>
            <small class="text-muted">Masukkan kelas yang akan diampu</small>
          </div>
          <div class="mb-3">
            <label class="form-label">Nama Lengkap <span class="text-danger">*</span></label>
            <input type="text" name="nama_wali" class="form-control" placeholder="Nama lengkap wali kelas" required>
          </div>
          <div class="mb-3">
            <label class="form-label">NIP <span class="text-danger">*</span></label>
            <input type="text" name="nip_wali" class="form-control" placeholder="Nomor Induk Pegawai" required>
            <small class="text-muted">NIP akan digunakan sebagai username login</small>
          </div>
          <div class="mb-3">
            <label class="form-label">Password <span class="text-danger">*</span></label>
            <input type="password" name="password" class="form-control" placeholder="Password" required>
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
          <button type="submit" name="tambah_wali" class="btn btn-primary">
            <i class="fas fa-save me-2"></i>Simpan
          </button>
        </div>
      </form>
    </div>
  </div>
</div>

<!-- Modal Tambah Guru Piket -->
<div class="modal fade" id="modalTambahGuru" tabindex="-1">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header bg-info text-white">
        <h5 class="modal-title"><i class="fas fa-user-clock me-2"></i>Tambah Guru Piket</h5>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
      </div>
      <form method="post">
        <div class="modal-body">
          <?php if (isset($error_guru)): ?>
            <div class="alert alert-danger"><?= $error_guru ?></div>
          <?php endif; ?>
          <div class="mb-3">
            <label class="form-label">NIPK <span class="text-danger">*</span></label>
            <input type="text" name="nipk" class="form-control" placeholder="Nomor Induk Pegawai Khusus" required>
            <small class="text-muted">NIPK akan digunakan sebagai username login</small>
          </div>
          <div class="mb-3">
            <label class="form-label">Nama Lengkap <span class="text-danger">*</span></label>
            <input type="text" name="nama_guru" class="form-control" placeholder="Nama lengkap guru piket" required>
          </div>
          <div class="mb-3">
            <label class="form-label">Password <span class="text-danger">*</span></label>
            <input type="password" name="password" class="form-control" placeholder="Password" required>
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
          <button type="submit" name="tambah_guru" class="btn btn-primary">
            <i class="fas fa-save me-2"></i>Simpan
          </button>
        </div>
      </form>
    </div>
  </div>
</div>

<!-- Modal Edit Wali Kelas -->
<?php
// Reset pointer data untuk modal edit
$waliList = mysqli_query($conn, "SELECT * FROM wali_kelas");
while ($row = mysqli_fetch_assoc($waliList)) {
    if ($_SESSION['role'] === 'admin') {
?>
<div class="modal fade" id="editWaliModal<?= $row['id'] ?>" tabindex="-1">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header bg-warning">
        <h5 class="modal-title"><i class="fas fa-edit me-2"></i>Edit Wali Kelas</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <form method="post">
        <div class="modal-body">
          <input type="hidden" name="id" value="<?= $row['id'] ?>">
          <div class="mb-3">
            <label class="form-label">Kelas</label>
            <input type="text" name="kelas" class="form-control" value="<?= $row['kelas'] ?>" required>
          </div>
          <div class="mb-3">
            <label class="form-label">Nama Lengkap</label>
            <input type="text" name="nama_wali" class="form-control" value="<?= $row['nama_wali'] ?>" required>
          </div>
          <div class="mb-3">
            <label class="form-label">NIP (Username)</label>
            <input type="text" name="nip_wali" class="form-control" value="<?= $row['nip_wali'] ?>" required>
          </div>
          <div class="mb-3">
            <label class="form-label">Password Baru</label>
            <input type="password" name="password" class="form-control" placeholder="Kosongkan jika tidak diubah">
            <small class="text-muted">Isi hanya jika ingin mengganti password</small>
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
          <button type="submit" name="edit_wali" class="btn btn-primary">Simpan Perubahan</button>
        </div>
      </form>
    </div>
  </div>
</div>
<?php
    }
}
?>

<!-- Modal Edit Guru Piket -->
<?php
// Reset pointer data untuk modal edit guru
$guruList = mysqli_query($conn, "SELECT * FROM guru");
while ($row = mysqli_fetch_assoc($guruList)) {
    if ($_SESSION['role'] === 'admin') {
?>
<div class="modal fade" id="editGuruModal<?= $row['id'] ?>" tabindex="-1">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header bg-warning">
        <h5 class="modal-title"><i class="fas fa-edit me-2"></i>Edit Guru Piket</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <form method="post">
        <div class="modal-body">
          <input type="hidden" name="id" value="<?= $row['id'] ?>">
          <div class="mb-3">
            <label class="form-label">NIPK (Username)</label>
            <input type="text" name="nipk" class="form-control" value="<?= $row['nip'] ?>" required>
          </div>
          <div class="mb-3">
            <label class="form-label">Nama Lengkap</label>
            <input type="text" name="nama_guru" class="form-control" value="<?= $row['nama'] ?>" required>
          </div>
          <div class="mb-3">
            <label class="form-label">Status</label>
            <select name="status" class="form-select">
              <option value="aktif" <?= ($row['status'] == 'aktif') ? 'selected' : '' ?>>Aktif</option>
              <option value="keluar" <?= ($row['status'] == 'keluar') ? 'selected' : '' ?>>Keluar</option>
            </select>
          </div>
          <div class="mb-3">
            <label class="form-label">Password Baru</label>
            <input type="password" name="password" class="form-control" placeholder="Kosongkan jika tidak diubah">
            <small class="text-muted">Isi hanya jika ingin mengganti password</small>
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
          <button type="submit" name="edit_guru" class="btn btn-primary">Simpan Perubahan</button>
        </div>
      </form>
    </div>
  </div>
</div>
<?php
    }
}
?>

<!-- Script -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
<script>
function searchTable() {
    var input, filter, table, tr, td, i, txtValue;
    input = document.getElementById("searchInput");
    filter = input.value.toUpperCase();
    table = document.getElementById("dataTable");
    tr = table.getElementsByTagName("tr");

    for (i = 0; i < tr.length; i++) {
        // Cari di kolom nama (index 2) dan NIP (index 3)
        var namaCol = tr[i].getElementsByTagName("td")[2];
        var nipCol = tr[i].getElementsByTagName("td")[3];
        
        if (namaCol || nipCol) {
            var namaValue = namaCol.textContent || namaCol.innerText;
            var nipValue = nipCol.textContent || nipCol.innerText;
            
            if (namaValue.toUpperCase().indexOf(filter) > -1 || nipValue.toUpperCase().indexOf(filter) > -1) {
                tr[i].style.display = "";
            } else {
                tr[i].style.display = "none";
            }
        }
    }
}
</script>
</body>
</html>