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

include 'config.php';

// Perbaiki struktur tabel guru jika belum ada
$sql = "CREATE TABLE IF NOT EXISTS guru (
  id INT AUTO_INCREMENT PRIMARY KEY,
  nip VARCHAR(20) NOT NULL UNIQUE,
  nama VARCHAR(100) NOT NULL,
  mapel VARCHAR(50) NOT NULL,
  no_wa VARCHAR(20),
  status ENUM('aktif','keluar') DEFAULT 'aktif'
)";

if (!mysqli_query($conn, $sql)) {
    die("Error creating table: " . mysqli_error($conn));
}

// Periksa dan tambahkan kolom jika belum ada
$check_columns = mysqli_query($conn, "DESCRIBE guru");
$columns = [];
while ($row = mysqli_fetch_assoc($check_columns)) {
    $columns[] = $row['Field'];
}

if (!in_array('no_wa', $columns)) {
    mysqli_query($conn, "ALTER TABLE guru ADD no_wa VARCHAR(20) AFTER mapel");
}

if (!in_array('status', $columns)) {
    mysqli_query($conn, "ALTER TABLE guru ADD status ENUM('aktif','keluar') DEFAULT 'aktif' AFTER no_wa");
}

// Buat tabel users_guru jika belum ada
$sql = "CREATE TABLE IF NOT EXISTS users_guru (
  id INT AUTO_INCREMENT PRIMARY KEY,
  username VARCHAR(50) NOT NULL UNIQUE,
  nama VARCHAR(100) NOT NULL,
  password VARCHAR(100) NOT NULL,
  role ENUM('admin','guru') DEFAULT 'guru'
)";

if (!mysqli_query($conn, $sql)) {
    die("Error creating table: " . mysqli_error($conn));
}

// Proses simpan (tambah baru)
if (isset($_POST['simpan'])) {
    $nip   = mysqli_real_escape_string($conn, $_POST['nip']);
    $nama  = mysqli_real_escape_string($conn, $_POST['nama']);
    $mapel = mysqli_real_escape_string($conn, $_POST['mapel']);
    $no_wa = mysqli_real_escape_string($conn, $_POST['no_wa']);

    // Cek apakah NIP sudah ada
    $cek_nip = mysqli_query($conn, "SELECT id FROM guru WHERE nip='$nip' LIMIT 1");
    if (mysqli_num_rows($cek_nip) > 0) {
        $error = "Error: NIP sudah terdaftar!";
    } else {
        $result = mysqli_query($conn, "INSERT INTO guru (nip, nama, mapel, no_wa, status) 
                             VALUES ('$nip', '$nama', '$mapel', '$no_wa', 'aktif')");

        if ($result) {
            // Buat akun user untuk guru
            $username = $nip;
            $password = md5($nip);
            $role     = 'guru';

            $cek_user = mysqli_query($conn, "SELECT id FROM users_guru WHERE username='$username' LIMIT 1");
            if (mysqli_num_rows($cek_user) == 0) {
                mysqli_query($conn, "INSERT INTO users_guru (username, nama, password, role) 
                                 VALUES ('$username', '$nama', '$password', '$role')");
            }

            // Generate QR Code jika library tersedia
            if (file_exists('vendor/phpqrcode/qrlib.php')) {
                require 'vendor/phpqrcode/qrlib.php';
                $qr_dir = "assets/qr_guru/";
                if (!is_dir($qr_dir)) mkdir($qr_dir, 0777, true);
                QRcode::png($nip, $qr_dir . "$nip.png", QR_ECLEVEL_L, 4);
            }

            echo "<script>alert('Data guru berhasil disimpan!'); window.location='guru.php';</script>";
            exit;
        } else {
            $error = "Error: " . mysqli_error($conn);
        }
    }
}

// Proses update data (edit)
if (isset($_POST['update'])) {
    $id    = intval($_POST['id']);
    $nip   = mysqli_real_escape_string($conn, $_POST['nip']);
    $nama  = mysqli_real_escape_string($conn, $_POST['nama']);
    $mapel = mysqli_real_escape_string($conn, $_POST['mapel']);
    $no_wa = mysqli_real_escape_string($conn, $_POST['no_wa']);

    $res_old = mysqli_query($conn, "SELECT nip FROM guru WHERE id=$id LIMIT 1");
    if ($res_old && mysqli_num_rows($res_old) > 0) {
        $old = mysqli_fetch_assoc($res_old);
        $old_nip = $old['nip'];

        // Cek apakah NIP baru sudah ada (kecuali untuk dirinya sendiri)
        $cek_nip = mysqli_query($conn, "SELECT id FROM guru WHERE nip='$nip' AND id != $id LIMIT 1");
        if (mysqli_num_rows($cek_nip) > 0) {
            $error = "Error: NIP sudah terdaftar!";
        } else {
            $result = mysqli_query($conn, "UPDATE guru 
                             SET nip='$nip', nama='$nama', mapel='$mapel', no_wa='$no_wa' 
                             WHERE id=$id");

            if ($result) {
                mysqli_query($conn, "UPDATE users_guru 
                             SET username='$nip', nama='$nama', password=md5('$nip') 
                             WHERE username='$old_nip' AND role='guru'");

                // Generate QR Code jika library tersedia
                if (file_exists('vendor/phpqrcode/qrlib.php')) {
                    require 'vendor/phpqrcode/qrlib.php';
                    $qr_dir = "assets/qr_guru/";
                    if (!is_dir($qr_dir)) mkdir($qr_dir, 0777, true);
                    QRcode::png($nip, $qr_dir . "$nip.png", QR_ECLEVEL_L, 4);
                }

                echo "<script>alert('Data guru berhasil diupdate!'); window.location='guru.php';</script>";
                exit;
            } else {
                $error = "Error: " . mysqli_error($conn);
            }
        }
    }
}

// Tandai guru keluar
if (isset($_GET['keluar'])) {
    $id = intval($_GET['keluar']);
    $res = mysqli_query($conn, "SELECT nip FROM guru WHERE id=$id LIMIT 1");
    if ($res && mysqli_num_rows($res) > 0) {
        $data = mysqli_fetch_assoc($res);
        $nip_keluar = $data['nip'];

        mysqli_query($conn, "UPDATE guru SET status='keluar' WHERE id=$id");
        mysqli_query($conn, "DELETE FROM users_guru WHERE username='$nip_keluar' AND role='guru'");

        echo "<script>alert('Data guru berhasil ditandai keluar!'); window.location='guru.php';</script>";
        exit;
    }
}

// Generate akun massal
if (isset($_POST['generate_akun'])) {
    $q_guru = mysqli_query($conn, "SELECT nip, nama FROM guru WHERE status='aktif'");
    if ($q_guru) {
        $count = 0;
        while ($g = mysqli_fetch_assoc($q_guru)) {
            $username = $g['nip'];
            $nama     = $g['nama'];
            $password = md5($g['nip']);
            $role     = 'guru';

            $cek = mysqli_query($conn, "SELECT id FROM users_guru WHERE username='$username' LIMIT 1");
            if (mysqli_num_rows($cek) == 0) {
                mysqli_query($conn, "INSERT INTO users_guru (username, nama, password, role) 
                                 VALUES ('$username', '$nama', '$password', '$role')");
                $count++;
            }
        }
        echo "<script>alert('Generate akun selesai. $count akun baru dibuat.');window.location='guru.php';</script>";
        exit;
    }
}

// Ambil data untuk edit jika ada
$edit_data = null;
if (isset($_GET['edit'])) {
    $id = intval($_GET['edit']);
    $res = mysqli_query($conn, "SELECT * FROM guru WHERE id=$id LIMIT 1");
    if ($res && mysqli_num_rows($res) > 0) {
        $edit_data = mysqli_fetch_assoc($res);
    }
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
  <meta charset="UTF-8">
  <title>Data Guru</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>
    .barcode-download {
      display: block;
      margin-top: 5px;
      font-size: 12px;
    }
    .table-responsive {
      max-height: 70vh;
      overflow-y: auto;
    }
    .alert {
      padding: 10px;
      margin-bottom: 15px;
      border-radius: 5px;
    }
    .alert-danger {
      background-color: #f8d7da;
      color: #721c24;
      border: 1px solid #f5c6cb;
    }
    .alert-success {
      background-color: #d4edda;
      color: #155724;
      border: 1px solid #c3e6cb;
    }
  </style>
</head>
<body class="container py-4">

  <h2 class="text-center mb-4">Data Guru</h2>

  <a href="dashboard.php" class="btn btn-secondary mb-3">← Kembali</a>

  <?php if (isset($error)): ?>
    <div class="alert alert-danger">
      <i class="fas fa-exclamation-triangle"></i> <?php echo $error; ?>
    </div>
  <?php endif; ?>

  <!-- Form Input / Edit -->
  <form method="post" class="row g-2 mb-4">
    <input type="hidden" name="id" value="<?= isset($edit_data['id']) ? $edit_data['id'] : '' ?>">
    <div class="col-6 col-md-3">
      <input type="text" name="nip" class="form-control" placeholder="NIP" required value="<?= isset($edit_data['nip']) ? $edit_data['nip'] : '' ?>">
    </div>
    <div class="col-12 col-md-4">
      <input type="text" name="nama" class="form-control" placeholder="Nama Lengkap" required value="<?= isset($edit_data['nama']) ? $edit_data['nama'] : '' ?>">
    </div>
    <div class="col-6 col-md-3">
      <input type="text" name="mapel" class="form-control" placeholder="Mata Pelajaran" required value="<?= isset($edit_data['mapel']) ? $edit_data['mapel'] : '' ?>">
    </div>
    <div class="col-6 col-md-2">
      <input type="text" name="no_wa" class="form-control" placeholder="Nomor WhatsApp (6285xxxx)" value="<?= isset($edit_data['no_wa']) ? $edit_data['no_wa'] : '' ?>">
    </div>
    <div class="col-12 col-md-2">
      <?php if (isset($edit_data)): ?>
        <button type="submit" name="update" class="btn btn-warning w-100">Update</button>
        <a href="guru.php" class="btn btn-secondary w-100 mt-2">Batal</a>
      <?php else: ?>
        <button type="submit" name="simpan" class="btn btn-primary w-100">Simpan</button>
      <?php endif; ?>
    </div>
  </form>

  <form method="post" class="mb-3">
    <button type="submit" name="generate_akun" class="btn btn-dark">⚡ Generate Akun Guru</button>
  </form>

  <a href="cetak_kartu_guru.php" class="btn btn-success mb-3" target="_blank">Cetak Semua Kartu Guru</a>
  <a href="import_guru.php" class="btn btn-success mb-3">📥 Import dari Excel</a>

  <!-- Tabel Data Guru -->
  <div class="table-responsive">
    <table class="table table-bordered table-striped align-middle">
      <thead class="table-light text-center">
        <tr>
          <th>NIP</th>
          <th>Nama</th>
          <th>Mata Pelajaran</th>
          <th>No. WhatsApp</th>
          <th>QR Code</th>
          <th>Aksi</th>
        </tr>
      </thead>
      <tbody>
        <?php
        $q = mysqli_query($conn, "SELECT * FROM guru WHERE status='aktif' ORDER BY nama ASC");
        if ($q && mysqli_num_rows($q) > 0) {
          while ($row = mysqli_fetch_assoc($q)) {
            $qr_file = "assets/qr_guru/{$row['nip']}.png";
            echo "<tr>
              <td>{$row['nip']}</td>
              <td>{$row['nama']}</td>
              <td>{$row['mapel']}</td>
              <td>{$row['no_wa']}</td>
              <td class='text-center'>";
            
            if (file_exists($qr_file)) {
              echo "<a href='$qr_file' target='_blank'>
                <img src='$qr_file' width='50'>
              </a>
              <a href='$qr_file' download='barcode_guru_{$row['nip']}.png' class='barcode-download'>
                <small>Download</small>
              </a>";
            } else {
              echo "<small>QR Code belum dibuat</small>";
            }
            
            echo "</td>
              <td class='text-center'>
                <a href='guru.php?edit={$row['id']}' class='btn btn-info btn-sm'>Edit</a>
                <a href='guru.php?keluar={$row['id']}' class='btn btn-warning btn-sm' onclick='return confirm(\"Yakin guru ini keluar?\")'>Keluar</a>
              </td>
            </tr>";
          }
        } else {
          echo "<tr><td colspan='6' class='text-center'>Tidak ada data guru</td></tr>";
        }
        ?>
      </tbody>
    </table>
  </div>

  <script src="https://kit.fontawesome.com/a076d05399.js" crossorigin="anonymous"></script>
</body>
</html>