<?php
// guru.php — Panel Guru (Self Service, hanya data sendiri)
require_once __DIR__.'/config.php';
session_start();

if (isset($_POST['logout'])) {
  session_destroy();
  header("Location: login_guru.php");
  exit;
}
if (!isset($_SESSION['guru_id'])) {
  die("❌ Sila login sebagai guru dahulu. <a href='login_guru.php'>Login di sini</a>");
}
$guru_id = (int) $_SESSION['guru_id'];
$msg='';

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

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

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' && !isset($_POST['logout'])) {
  // Kemaskini maklumat diri
  if(isset($_POST['kemaskini_diri'])){
    $stmt=$mysqli->prepare("UPDATE guru SET nama=?, jawatan=?, no_tel=? WHERE id=?");
    $stmt->bind_param('sssi',$_POST['nama'],$_POST['jawatan'],$_POST['no_tel'],$guru_id);
    if($stmt->execute()){
      $msg="✅ Maklumat diri dikemaskini";
      hantarTelegram("✏️ Guru kemaskini maklumat diri:\nNama: ".$_POST['nama']."\nJawatan: ".$_POST['jawatan']."\nNo Tel: ".$_POST['no_tel']);
      $_SESSION['guru_nama'] = $_POST['nama']; // update session
    } else { $msg="❌ ".$stmt->error; }
    $stmt->close();
  }
  // Keberadaan
  if(isset($_POST['tambah_keberadaan'])){
    $stmt=$mysqli->prepare("INSERT INTO guru_keberadaan (guru_id,status,sebab,tempoh) VALUES (?,?,?,?)");
    $stmt->bind_param('isss',$guru_id,$_POST['status'],$_POST['sebab'],$_POST['tempoh']);
    if($stmt->execute()){
      $msg="✅ Keberadaan ditambah";
      hantarTelegram("📍 Keberadaan baru:\nGuru: ".$_SESSION['guru_nama']."\nStatus: ".$_POST['status']."\nSebab: ".$_POST['sebab']."\nTempoh: ".$_POST['tempoh']);
    } else { $msg="❌ ".$stmt->error; }
    $stmt->close();
  }
  if(isset($_POST['padam_keberadaan'])){
    $stmt=$mysqli->prepare("DELETE FROM guru_keberadaan WHERE id=? AND guru_id=?");
    $stmt->bind_param('ii',$_POST['id'],$guru_id);
    if($stmt->execute()){
      $msg="🗑️ Keberadaan dipadam";
      hantarTelegram("🗑️ Keberadaan dipadam oleh ".$_SESSION['guru_nama']." (ID ".$_POST['id'].")");
    } else { $msg="❌ ".$stmt->error; }
    $stmt->close();
  }
  // 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',$guru_id,$_POST['tarikh_mula'],$_POST['tarikh_akhir'],$_POST['sebab']);
    if($stmt->execute()){
      $msg="✅ Cuti ditambah";
      hantarTelegram("🛑 Cuti baru:\nGuru: ".$_SESSION['guru_nama']."\nMula: ".$_POST['tarikh_mula']."\nAkhir: ".$_POST['tarikh_akhir']."\nSebab: ".$_POST['sebab']);
    } else { $msg="❌ ".$stmt->error; }
    $stmt->close();
  }
  if(isset($_POST['padam_cuti'])){
    $stmt=$mysqli->prepare("DELETE FROM guru_cuti WHERE id=? AND guru_id=?");
    $stmt->bind_param('ii',$_POST['id'],$guru_id);
    if($stmt->execute()){
      $msg="🗑️ Cuti dipadam";
      hantarTelegram("🗑️ Cuti dipadam oleh ".$_SESSION['guru_nama']." (ID ".$_POST['id'].")");
    } else { $msg="❌ ".$stmt->error; }
    $stmt->close();
  }
  // Tugasan
  if(isset($_POST['tambah_tugas'])){
    $stmt=$mysqli->prepare("INSERT INTO guru_tugas (guru_id,jenis,keterangan,minggu) VALUES (?,?,?,?)");
    $stmt->bind_param('isss',$guru_id,$_POST['jenis'],$_POST['keterangan'],$_POST['minggu']);
    if($stmt->execute()){
      $msg="✅ Tugasan ditambah";
      hantarTelegram("📝 Tugasan baru:\nGuru: ".$_SESSION['guru_nama']."\nJenis: ".$_POST['jenis']."\nKeterangan: ".$_POST['keterangan']."\nMinggu: ".$_POST['minggu']);
    } else { $msg="❌ ".$stmt->error; }
    $stmt->close();
  }
  if(isset($_POST['padam_tugas'])){
    $stmt=$mysqli->prepare("DELETE FROM guru_tugas WHERE id=? AND guru_id=?");
    $stmt->bind_param('ii',$_POST['id'],$guru_id);
    if($stmt->execute()){
      $msg="🗑️ Tugasan dipadam";
      hantarTelegram("🗑️ Tugasan dipadam oleh ".$_SESSION['guru_nama']." (ID ".$_POST['id'].")");
    } else { $msg="❌ ".$stmt->error; }
    $stmt->close();
  }
}

/* ===================== AMBIL DATA ===================== */
$info = $mysqli->query("SELECT * FROM guru WHERE id=$guru_id")->fetch_assoc();
$keberadaan = $mysqli->query("SELECT * FROM guru_keberadaan WHERE guru_id=$guru_id ORDER BY id DESC");
$cuti = $mysqli->query("SELECT * FROM guru_cuti WHERE guru_id=$guru_id ORDER BY id DESC");
$tugas = $mysqli->query("SELECT * FROM guru_tugas WHERE guru_id=$guru_id ORDER BY id DESC");
?>
<!DOCTYPE html>
<html lang="ms">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Panel Guru</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
<style>
  .banner {
    background:#1976d2;
    color:#fff;
    padding:20px;
    text-align:center;
  }
  .banner img {
    height:80px;
    margin-bottom:10px;
  }
  .card-header {
    font-weight: 700;
    font-size: 1.5rem;
  }
  table thead th {
    font-weight: 700;
    font-size: 1.1rem;
  }
</style>
</head>
<body class="bg-light">

<!-- Banner -->
<div class="banner">
  <img src="logo.png" alt="Logo Sekolah">
  <h2 class="fw-bold">Sistem Keberadaan Guru</h2>
  <div>SMK MUHIBBAH SANDAKAN</div>
</div>

<!-- Navbar -->
<nav class="navbar navbar-expand-lg navbar-dark bg-primary sticky-top mb-4">
  <div class="container-fluid">
    <span class="navbar-brand">👩‍🏫 Panel Guru</span>
    <div class="ms-auto d-flex align-items-center">
      <span class="text-white me-3">Hai, <?=safe($_SESSION['guru_nama'])?></span>
      <form method="post" class="mb-0">
        <button class="btn btn-sm btn-outline-light" name="logout">Logout</button>
      </form>
    </div>
  </div>
</nav>

<div class="container">

  <?php if($msg): ?><div class="alert alert-info"><?=$msg?></div><?php endif; ?>

  <!-- Maklumat Diri -->
  <div class="card mb-4">
    <div class="card-header">📋 Maklumat Diri</div>
    <div class="card-body">
      <form method="post" class="row g-2">
        <div class="col-md"><input class="form-control" name="nama" value="<?=safe($info['nama'])?>"></div>
        <div class="col-md"><input class="form-control" name="jawatan" value="<?=safe($info['jawatan'])?>"></div>
        <div class="col-md"><input class="form-control" name="no_tel" value="<?=safe($info['no_tel'])?>"></div>
        <div class="col-auto"><button class="btn btn-primary" name="kemaskini_diri">Simpan</button></div>
      </form>
    </div>
  </div>

  <!-- Keberadaan -->
  <div class="card mb-4">
    <div class="card-header">📍 Keberadaan Saya</div>
    <div class="card-body">
      <form method="post" class="row g-2 mb-2">
        <div class="col-md"><input class="form-control" name="status" placeholder="Status"></div>
        <div class="col-md"><input class="form-control" name="sebab" placeholder="Sebab"></div>
        <div class="col-md"><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">
        <thead><tr><th>Status</th><th>Sebab</th><th>Tempoh</th><th>Tindakan</th></tr></thead>
        <tbody>
        <?php while($k=$keberadaan->fetch_assoc()): ?>
          <tr>
            <td><?=safe($k['status'])?></td>
            <td><?=safe($k['sebab'])?></td>
            <td><?=safe($k['tempoh'])?></td>
            <td>
              <form method="post" onsubmit="return confirm('Padam?');" class="d-inline">
                <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>
  </div>

  <!-- Cuti -->
  <div class="card mb-4">
    <div class="card-header">🛑 Cuti Saya</div>
    <div class="card-body">
      <form method="post" class="row g-2 mb-2">
        <div class="col-md"><input type="date" class="form-control" name="tarikh_mula"></div>
        <div class="col-md"><input type="date" class="form-control" name="tarikh_akhir"></div>
        <div class="col-md"><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">
        <thead><tr><th>Mula</th><th>Akhir</th><th>Sebab</th><th>Tindakan</th></tr></thead>
        <tbody>
        <?php while($c=$cuti->fetch_assoc()): ?>
          <tr>
            <td><?=$c['tarikh_mula']?></td>
            <td><?=$c['tarikh_akhir']?></td>
            <td><?=safe($c['sebab'])?></td>
            <td>
              <form method="post" onsubmit="return confirm('Padam cuti?');" class="d-inline">
                <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>
  </div>

  <!-- Tugasan -->
  <div class="card mb-4">
    <div class="card-header">📝 Tugasan Saya</div>
    <div class="card-body">
      <form method="post" class="row g-2 mb-2">
        <div class="col-md"><input class="form-control" name="jenis" placeholder="Jenis"></div>
        <div class="col-md"><input class="form-control" name="keterangan" placeholder="Keterangan"></div>
        <div class="col-md"><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">
        <thead><tr><th>Jenis</th><th>Keterangan</th><th>Minggu</th><th>Tindakan</th></tr></thead>
        <tbody>
        <?php while($t=$tugas->fetch_assoc()): ?>
          <tr>
            <td><?=safe($t['jenis'])?></td>
            <td><?=safe($t['keterangan'])?></td>
            <td><?=safe($t['minggu'])?></td>
            <td>
              <form method="post" onsubmit="return confirm('Padam tugasan?');" class="d-inline">
                <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>

</div>
</body>
</html>
