<?php
// admin_guru.php — Admin Dashboard Guru (Bootstrap 5 + CRUD + Telegram Notifikasi)
require_once __DIR__.'/config.php';
session_start();
if(!isset($_SESSION['is_admin'])) $_SESSION['is_admin']=true;

function safe($v){ return htmlspecialchars((string)$v,ENT_QUOTES,'UTF-8'); }
$msg='';

// ================== TELEGRAM CONFIG ==================
$TELEGRAM_TOKEN = "bot8373117229:AAFcOyWXl7sPHUdEfPvonVOVenDRoupsWKE"; 
$CHAT_ID = "57398403"; // Chat ID anda

function hantarTelegram($text){
    global $TELEGRAM_TOKEN,$CHAT_ID;
    $url="https://api.telegram.org/$TELEGRAM_TOKEN/sendMessage";
    $data=['chat_id'=>$CHAT_ID,'text'=>$text];
    $options=[
        'http'=>[
            'header'=>"Content-Type: application/x-www-form-urlencoded\r\n",
            'method'=>'POST',
            'content'=>http_build_query($data)
        ]
    ];
    @file_get_contents($url,false,stream_context_create($options));
}

// ================== PROSES BORANG ==================
if($_SERVER['REQUEST_METHOD']==='POST'){
  // Tambah guru
  if(isset($_POST['tambah_guru'])){
    $stmt=$mysqli->prepare("INSERT INTO guru (nama,jawatan,no_tel) VALUES (?,?,?)");
    $stmt->bind_param('sss',$_POST['nama'],$_POST['jawatan'],$_POST['no_tel']);
    if($stmt->execute()){
        $msg="✅ Guru ditambah";
        hantarTelegram("👩‍🏫 Guru baru ditambah:\nNama: ".$_POST['nama']."\nJawatan: ".$_POST['jawatan']."\nNo Tel: ".$_POST['no_tel']);
    } else { $msg="❌ ".$stmt->error; }
    $stmt->close();
  }

  // Kemaskini guru
  if(isset($_POST['kemaskini_guru'])){
    $stmt=$mysqli->prepare("UPDATE guru SET nama=?,jawatan=?,no_tel=? WHERE id=?");
    $stmt->bind_param('sssi',$_POST['nama'],$_POST['jawatan'],$_POST['no_tel'],$_POST['id']);
    if($stmt->execute()){
        $msg="✅ Guru dikemaskini";
        hantarTelegram("✏️ Guru dikemaskini:\nNama: ".$_POST['nama']."\nJawatan: ".$_POST['jawatan']."\nNo Tel: ".$_POST['no_tel']);
    } else { $msg="❌ ".$stmt->error; }
    $stmt->close();
  }

  // Padam guru
  if(isset($_POST['padam_guru'])){
    $id=(int)$_POST['id'];
    $nama=$mysqli->query("SELECT nama FROM guru WHERE id=$id")->fetch_assoc()['nama']??"Guru-$id";
    $mysqli->query("DELETE FROM guru_keberadaan WHERE guru_id=$id");
    $mysqli->query("DELETE FROM guru_cuti WHERE guru_id=$id");
    $mysqli->query("DELETE FROM guru_tugas WHERE guru_id=$id");
    $stmt=$mysqli->prepare("DELETE FROM guru WHERE id=?");
    $stmt->bind_param('i',$id);
    if($stmt->execute()){
        $msg="🗑️ Guru dipadam";
        hantarTelegram("🗑️ Guru dipadam:\nNama: $nama");
    } else { $msg="❌ ".$stmt->error; }
    $stmt->close();
  }

  // Tambah keberadaan
  if(isset($_POST['tambah_keberadaan'])){
    $stmt=$mysqli->prepare("INSERT INTO guru_keberadaan (guru_id,status,sebab,tempoh) VALUES (?,?,?,?)");
    $stmt->bind_param('isss',$_POST['guru_id'],$_POST['status'],$_POST['sebab'],$_POST['tempoh']);
    if($stmt->execute()){
        $gid=(int)$_POST['guru_id'];
        $nama=$mysqli->query("SELECT nama FROM guru WHERE id=$gid")->fetch_assoc()['nama']??"Guru-$gid";
        $msg="✅ Keberadaan ditambah";
        hantarTelegram("📍 Keberadaan ditambah:\nNama: $nama\nStatus: ".$_POST['status']."\nSebab: ".$_POST['sebab']."\nTempoh: ".$_POST['tempoh']);
    } else { $msg="❌ ".$stmt->error; }
    $stmt->close();
  }

  // Kemaskini keberadaan
  if(isset($_POST['kemaskini_keberadaan'])){
    $stmt=$mysqli->prepare("UPDATE guru_keberadaan SET status=?,sebab=?,tempoh=? WHERE id=?");
    $stmt->bind_param('sssi',$_POST['status'],$_POST['sebab'],$_POST['tempoh'],$_POST['id']);
    if($stmt->execute()){
        $msg="✅ Keberadaan dikemaskini";
        hantarTelegram("✏️ Keberadaan dikemaskini:\nStatus: ".$_POST['status']."\nSebab: ".$_POST['sebab']."\nTempoh: ".$_POST['tempoh']);
    } else { $msg="❌ ".$stmt->error; }
    $stmt->close();
  }

  // Padam keberadaan
  if(isset($_POST['padam_keberadaan'])){
    $stmt=$mysqli->prepare("DELETE FROM guru_keberadaan WHERE id=?");
    $stmt->bind_param('i',$_POST['id']);
    if($stmt->execute()){
        $msg="🗑️ Keberadaan dipadam";
        hantarTelegram("🗑️ Rekod keberadaan dipadam (ID ".$_POST['id'].")");
    } else { $msg="❌ ".$stmt->error; }
    $stmt->close();
  }

  // Tambah cuti
  if(isset($_POST['tambah_cuti'])){
    $stmt=$mysqli->prepare("INSERT INTO guru_cuti (guru_id,tarikh_mula,tarikh_akhir,sebab) VALUES (?,?,?,?)");
    $stmt->bind_param('isss',$_POST['guru_id'],$_POST['tarikh_mula'],$_POST['tarikh_akhir'],$_POST['sebab']);
    if($stmt->execute()){
        $gid=(int)$_POST['guru_id'];
        $nama=$mysqli->query("SELECT nama FROM guru WHERE id=$gid")->fetch_assoc()['nama']??"Guru-$gid";
        $msg="✅ Cuti ditambah";
        hantarTelegram("🛑 Cuti ditambah:\nNama: $nama\nMula: ".$_POST['tarikh_mula']."\nAkhir: ".$_POST['tarikh_akhir']."\nSebab: ".$_POST['sebab']);
    } else { $msg="❌ ".$stmt->error; }
    $stmt->close();
  }

  // Kemaskini cuti
  if(isset($_POST['kemaskini_cuti'])){
    $stmt=$mysqli->prepare("UPDATE guru_cuti SET tarikh_mula=?,tarikh_akhir=?,sebab=? WHERE id=?");
    $stmt->bind_param('sssi',$_POST['tarikh_mula'],$_POST['tarikh_akhir'],$_POST['sebab'],$_POST['id']);
    if($stmt->execute()){
        $msg="✅ Cuti dikemaskini";
        hantarTelegram("✏️ Cuti dikemaskini:\nMula: ".$_POST['tarikh_mula']."\nAkhir: ".$_POST['tarikh_akhir']."\nSebab: ".$_POST['sebab']);
    } else { $msg="❌ ".$stmt->error; }
    $stmt->close();
  }

  // Padam cuti
  if(isset($_POST['padam_cuti'])){
    $stmt=$mysqli->prepare("DELETE FROM guru_cuti WHERE id=?");
    $stmt->bind_param('i',$_POST['id']);
    if($stmt->execute()){
        $msg="🗑️ Cuti dipadam";
        hantarTelegram("🗑️ Rekod cuti dipadam (ID ".$_POST['id'].")");
    } else { $msg="❌ ".$stmt->error; }
    $stmt->close();
  }

  // Tambah tugasan
  if(isset($_POST['tambah_tugas'])){
    $stmt=$mysqli->prepare("INSERT INTO guru_tugas (guru_id,jenis,keterangan,minggu) VALUES (?,?,?,?)");
    $stmt->bind_param('isss',$_POST['guru_id'],$_POST['jenis'],$_POST['keterangan'],$_POST['minggu']);
    if($stmt->execute()){
        $gid=(int)$_POST['guru_id'];
        $nama=$mysqli->query("SELECT nama FROM guru WHERE id=$gid")->fetch_assoc()['nama']??"Guru-$gid";
        $msg="✅ Tugasan ditambah";
        hantarTelegram("📝 Tugasan ditambah:\nNama: $nama\nJenis: ".$_POST['jenis']."\nKeterangan: ".$_POST['keterangan']."\nMinggu: ".$_POST['minggu']);
    } else { $msg="❌ ".$stmt->error; }
    $stmt->close();
  }

  // Kemaskini tugasan
  if(isset($_POST['kemaskini_tugas'])){
    $stmt=$mysqli->prepare("UPDATE guru_tugas SET jenis=?,keterangan=?,minggu=? WHERE id=?");
    $stmt->bind_param('sssi',$_POST['jenis'],$_POST['keterangan'],$_POST['minggu'],$_POST['id']);
    if($stmt->execute()){
        $msg="✅ Tugasan dikemaskini";
        hantarTelegram("✏️ Tugasan dikemaskini:\nJenis: ".$_POST['jenis']."\nKeterangan: ".$_POST['keterangan']."\nMinggu: ".$_POST['minggu']);
    } else { $msg="❌ ".$stmt->error; }
    $stmt->close();
  }

  // Padam tugasan
  if(isset($_POST['padam_tugas'])){
    $stmt=$mysqli->prepare("DELETE FROM guru_tugas WHERE id=?");
    $stmt->bind_param('i',$_POST['id']);
    if($stmt->execute()){
        $msg="🗑️ Tugasan dipadam";
        hantarTelegram("🗑️ Rekod tugasan dipadam (ID ".$_POST['id'].")");
    } else { $msg="❌ ".$stmt->error; }
    $stmt->close();
  }
}

// ================== AMBIL DATA ==================
$guru=$mysqli->query("SELECT * FROM guru ORDER BY nama");
$keberadaan=$mysqli->query("SELECT k.id,g.nama,k.status,k.sebab,k.tempoh FROM guru_keberadaan k JOIN guru g ON g.id=k.guru_id ORDER BY k.id DESC");
$cuti=$mysqli->query("SELECT c.id,g.nama,c.tarikh_mula,c.tarikh_akhir,c.sebab FROM guru_cuti c JOIN guru g ON g.id=c.guru_id ORDER BY c.id DESC");
$tugas=$mysqli->query("SELECT t.id,g.nama,t.jenis,t.keterangan,t.minggu FROM guru_tugas t JOIN guru g ON g.id=t.guru_id ORDER BY t.id DESC");
?>
<!DOCTYPE html>
<html lang="ms">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Admin Guru</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">

<style>
/* Remove default bootstrap tab styling */
.nav-tabs {
    border-bottom: none !important;
}

.nav-tabs .nav-link {
    background: linear-gradient(45deg, #FFE259, #FFA751) !important;
    color: #000 !important;
    border: none !important;
    border-radius: 8px !important;
    margin-right: 6px;
    padding: 10px 18px;
    font-weight: 600;
}

/* Active tab */
.nav-tabs .nav-link.active {
    background: linear-gradient(45deg, #FFD200, #FFB300) !important;
    color: #000 !important;
    box-shadow: 0 4px 10px rgba(255,193,7,0.4);
}

/* Hover */
.nav-tabs .nav-link:hover {
    filter: brightness(1.12);
}
</style>

</head>
<body>
<div class="container-fluid p-3 bg-primary text-white d-flex justify-content-between align-items-center">
  <h2>👩‍🏫 Admin Guru</h2>
</div>
<?php if($msg): ?><div class="alert alert-info"><?=safe($msg)?></div><?php endif; ?>

<ul class="nav nav-tabs">
  <li class="nav-item"><a class="nav-link active" data-bs-toggle="tab" href="#guru">Guru</a></li>
  <li class="nav-item"><a class="nav-link" data-bs-toggle="tab" href="#keberadaan">Keberadaan</a></li>
  <li class="nav-item"><a class="nav-link" data-bs-toggle="tab" href="#cuti">Cuti</a></li>
  <li class="nav-item"><a class="nav-link" data-bs-toggle="tab" href="#tugas">Tugasan</a></li>
</ul>

<div class="tab-content p-3 border border-top-0">
  <!-- Tab Guru -->
  <div id="guru" class="tab-pane fade show active">
    <h4>📋 Senarai Guru</h4>
    <form class="row g-2" method="post">
      <div class="col"><input class="form-control" name="nama" placeholder="Nama" required></div>
      <div class="col"><input class="form-control" name="jawatan" placeholder="Jawatan"></div>
      <div class="col"><input class="form-control" name="no_tel" placeholder="No Tel"></div>
      <div class="col-auto"><button class="btn btn-success" name="tambah_guru">Tambah</button></div>
    </form>
    <table class="table table-striped mt-3">
      <thead><tr><th>Nama</th><th>Jawatan</th><th>No Tel</th><th>Kemaskini</th><th>Padam</th></tr></thead>
      <tbody>
      <?php while($g=$guru->fetch_assoc()): ?>
        <tr>
          <form method="post">
            <td><input class="form-control" name="nama" value="<?=safe($g['nama'])?>"></td>
            <td><input class="form-control" name="jawatan" value="<?=safe($g['jawatan'])?>"></td>
            <td><input class="form-control" name="no_tel" value="<?=safe($g['no_tel'])?>"></td>
            <td>
              <input type="hidden" name="id" value="<?=$g['id']?>">
              <button class="btn btn-primary btn-sm" name="kemaskini_guru">Simpan</button>
            </td>
          </form>
          <td>
            <form method="post" onsubmit="return confirm('Padam guru ini?');">
              <input type="hidden" name="id" value="<?=$g['id']?>">
              <button class="btn btn-danger btn-sm" name="padam_guru">Padam</button>
            </form>
          </td>
        </tr>
      <?php endwhile; ?>
      </tbody>
    </table>
  </div>

  <!-- Tab Keberadaan -->
  <div id="keberadaan" class="tab-pane fade">
    <h4>📍 Keberadaan Guru</h4>
    <form class="row g-2" method="post">
      <div class="col">
        <select class="form-select" name="guru_id" required>
          <option value="">--Pilih Guru--</option>
          <?php $res=$mysqli->query("SELECT id,nama FROM guru ORDER BY nama");
          while($r=$res->fetch_assoc()): ?>
            <option value="<?=$r['id']?>"><?=$r['nama']?></option>
          <?php endwhile; ?>
        </select>
      </div>
      <div class="col"><input class="form-control" name="status" placeholder="Status"></div>
      <div class="col"><input class="form-control" name="sebab" placeholder="Sebab"></div>
      <div class="col"><input class="form-control" name="tempoh" placeholder="Tempoh"></div>
      <div class="col-auto"><button class="btn btn-success" name="tambah_keberadaan">Tambah</button></div>
    </form>
    <table class="table table-striped mt-3">
      <thead><tr><th>Nama</th><th>Status</th><th>Sebab</th><th>Tempoh</th><th>Kemaskini</th><th>Padam</th></tr></thead>
      <tbody>
      <?php while($k=$keberadaan->fetch_assoc()): ?>
        <tr>
          <form method="post">
            <td><?=$k['nama']?></td>
            <td><input class="form-control" name="status" value="<?=safe($k['status'])?>"></td>
            <td><input class="form-control" name="sebab" value="<?=safe($k['sebab'])?>"></td>
            <td><input class="form-control" name="tempoh" value="<?=safe($k['tempoh'])?>"></td>
            <td>
              <input type="hidden" name="id" value="<?=$k['id']?>">
              <button class="btn btn-primary btn-sm" name="kemaskini_keberadaan">Simpan</button>
            </td>
          </form>
          <td>
            <form method="post" onsubmit="return confirm('Padam keberadaan ini?');">
              <input type="hidden" name="id" value="<?=$k['id']?>">
              <button class="btn btn-danger btn-sm" name="padam_keberadaan">Padam</button>
            </form>
          </td>
        </tr>
      <?php endwhile; ?>
      </tbody>
    </table>
  </div>

  <!-- Tab Cuti -->
  <div id="cuti" class="tab-pane fade">
    <h4>🛑 Cuti Guru</h4>
    <form class="row g-2" method="post">
      <div class="col">
        <select class="form-select" name="guru_id" required>
          <option value="">--Pilih Guru--</option>
          <?php $res=$mysqli->query("SELECT id,nama FROM guru ORDER BY nama");
          while($r=$res->fetch_assoc()): ?>
            <option value="<?=$r['id']?>"><?=$r['nama']?></option>
          <?php endwhile; ?>
        </select>
      </div>
      <div class="col"><input type="date" class="form-control" name="tarikh_mula"></div>
      <div class="col"><input type="date" class="form-control" name="tarikh_akhir"></div>
      <div class="col"><input class="form-control" name="sebab" placeholder="Sebab"></div>
      <div class="col-auto"><button class="btn btn-success" name="tambah_cuti">Tambah</button></div>
    </form>
    <table class="table table-striped mt-3">
      <thead><tr><th>Nama</th><th>Mula</th><th>Akhir</th><th>Sebab</th><th>Kemaskini</th><th>Padam</th></tr></thead>
      <tbody>
      <?php while($c=$cuti->fetch_assoc()): ?>
        <tr>
          <form method="post">
            <td><?=$c['nama']?></td>
            <td><input type="date" class="form-control" name="tarikh_mula" value="<?=$c['tarikh_mula']?>"></td>
            <td><input type="date" class="form-control" name="tarikh_akhir" value="<?=$c['tarikh_akhir']?>"></td>
            <td><input class="form-control" name="sebab" value="<?=safe($c['sebab'])?>"></td>
            <td>
              <input type="hidden" name="id" value="<?=$c['id']?>">
              <button class="btn btn-primary btn-sm" name="kemaskini_cuti">Simpan</button>
            </td>
          </form>
          <td>
            <form method="post" onsubmit="return confirm('Padam cuti ini?');">
              <input type="hidden" name="id" value="<?=$c['id']?>">
              <button class="btn btn-danger btn-sm" name="padam_cuti">Padam</button>
            </form>
          </td>
        </tr>
      <?php endwhile; ?>
      </tbody>
    </table>
  </div>

  <!-- Tab Tugasan -->
  <div id="tugas" class="tab-pane fade">
    <h4>📝 Tugasan Guru</h4>
    <form class="row g-2" method="post">
      <div class="col">
        <select class="form-select" name="guru_id" required>
          <option value="">--Pilih Guru--</option>
          <?php $res=$mysqli->query("SELECT id,nama FROM guru ORDER BY nama");
          while($r=$res->fetch_assoc()): ?>
            <option value="<?=$r['id']?>"><?=$r['nama']?></option>
          <?php endwhile; ?>
        </select>
      </div>
      <div class="col"><input class="form-control" name="jenis" placeholder="Jenis"></div>
      <div class="col"><input class="form-control" name="keterangan" placeholder="Keterangan"></div>
      <div class="col"><input class="form-control" name="minggu" placeholder="Minggu"></div>
      <div class="col-auto"><button class="btn btn-success" name="tambah_tugas">Tambah</button></div>
    </form>
    <table class="table table-striped mt-3">
      <thead><tr><th>Nama</th><th>Jenis</th><th>Keterangan</th><th>Minggu</th><th>Kemaskini</th><th>Padam</th></tr></thead>
      <tbody>
      <?php while($t=$tugas->fetch_assoc()): ?>
        <tr>
          <form method="post">
            <td><?=$t['nama']?></td>
            <td><input class="form-control" name="jenis" value="<?=safe($t['jenis'])?>"></td>
            <td><input class="form-control" name="keterangan" value="<?=safe($t['keterangan'])?>"></td>
            <td><input class="form-control" name="minggu" value="<?=safe($t['minggu'])?>"></td>
            <td>
              <input type="hidden" name="id" value="<?=$t['id']?>">
              <button class="btn btn-primary btn-sm" name="kemaskini_tugas">Simpan</button>
            </td>
          </form>
          <td>
            <form method="post" onsubmit="return confirm('Padam tugasan ini?');">
              <input type="hidden" name="id" value="<?=$t['id']?>">
              <button class="btn btn-danger btn-sm" name="padam_tugas">Padam</button>
            </form>
          </td>
        </tr>
      <?php endwhile; ?>
      </tbody>
    </table>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
