<?php
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/functions.php';
require_login();
$db = get_db();
// Buat tabel guru jika belum ada
$db->exec("CREATE TABLE IF NOT EXISTS teachers (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  name TEXT NOT NULL,
  subject TEXT,
  contact TEXT,
  photo TEXT,
  created_at TEXT DEFAULT CURRENT_TIMESTAMP
)");
$uploadsDir = __DIR__ . '/../data/uploads/teachers';
if (!is_dir($uploadsDir)) mkdir($uploadsDir, 0755, true);


$editing = null;
// Tambah guru
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'add') {
  $name = trim($_POST['name'] ?? '');
  $subject = trim($_POST['subject'] ?? '');
  $contact = trim($_POST['contact'] ?? '');
  $photo = null;
  if (!empty($_FILES['photo']['name'])) {
    $tmp = $_FILES['photo']['tmp_name'];
    $ext = strtolower(pathinfo($_FILES['photo']['name'], PATHINFO_EXTENSION));
    $photo = uniqid('g_') . '.' . $ext;
    $dest = $uploadsDir . '/' . $photo;
    move_uploaded_file($tmp, $dest);
    // Resize jika perlu (opsional)
  }
  $stmt = $db->prepare('INSERT INTO teachers (name,subject,contact,photo) VALUES (?,?,?,?)');
  $stmt->execute([$name,$subject,$contact,$photo]);
  flash_set('success','Guru berhasil ditambahkan');
  header('Location: guru.php'); exit;
}

// Edit guru (load data)
if (isset($_GET['edit'])) {
  $id = (int)$_GET['edit'];
  $stmt = $db->prepare('SELECT * FROM teachers WHERE id=?');
  $stmt->execute([$id]);
  $editing = $stmt->fetch(PDO::FETCH_ASSOC);
}

// Update guru
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'update') {
  $id = (int)$_POST['id'];
  $name = trim($_POST['name'] ?? '');
  $subject = trim($_POST['subject'] ?? '');
  $contact = trim($_POST['contact'] ?? '');
  $photo = null;
  if (!empty($_FILES['photo']['name'])) {
    $tmp = $_FILES['photo']['tmp_name'];
    $ext = strtolower(pathinfo($_FILES['photo']['name'], PATHINFO_EXTENSION));
    $photo = uniqid('g_') . '.' . $ext;
    $dest = $uploadsDir . '/' . $photo;
    move_uploaded_file($tmp, $dest);
    // Hapus foto lama
    $old = $db->prepare('SELECT photo FROM teachers WHERE id=?');
    $old->execute([$id]);
    $r = $old->fetch(PDO::FETCH_ASSOC);
    if ($r && !empty($r['photo'])) @unlink($uploadsDir . '/' . $r['photo']);
  }
  $sql = 'UPDATE teachers SET name=?,subject=?,contact=?';
  $params = [$name,$subject,$contact];
  if ($photo) { $sql .= ',photo=?'; $params[] = $photo; }
  $sql .= ' WHERE id=?'; $params[] = $id;
  $db->prepare($sql)->execute($params);
  flash_set('success','Guru berhasil diupdate');
  header('Location: guru.php'); exit;
}

// Hapus guru
if (isset($_GET['delete'])) {
  $id = (int)$_GET['delete'];
  $old = $db->prepare('SELECT photo FROM teachers WHERE id=?');
  $old->execute([$id]);
  $r = $old->fetch(PDO::FETCH_ASSOC);
  if ($r && !empty($r['photo'])) @unlink($uploadsDir . '/' . $r['photo']);
  $db->prepare('DELETE FROM teachers WHERE id=?')->execute([$id]);
  flash_set('success','Guru dihapus');
  header('Location: guru.php'); exit;
}

$teachers = $db->query('SELECT * FROM teachers ORDER BY name ASC')->fetchAll(PDO::FETCH_ASSOC);

require __DIR__ . '/_header.php';
?>
<h1>Daftar Guru</h1>
<?php if ($m = flash_get('success')): ?><div class="alert alert-success"><?php echo e($m); ?></div><?php endif; ?>

<div class="card mb-4">
  <div class="card-body">
    <form method="post" enctype="multipart/form-data" class="row g-2 align-items-end">
      <input type="hidden" name="action" value="<?php echo $editing ? 'update' : 'add'; ?>">
      <?php if ($editing): ?><input type="hidden" name="id" value="<?php echo e($editing['id']); ?>"><?php endif; ?>
      <div class="col-md-4"><label>Nama</label><input name="name" value="<?php echo e($editing['name'] ?? ''); ?>" class="form-control" required></div>
      <div class="col-md-3"><label>Mata Pelajaran</label><input name="subject" value="<?php echo e($editing['subject'] ?? ''); ?>" class="form-control"></div>
      <div class="col-md-3"><label>Kontak</label><input name="contact" value="<?php echo e($editing['contact'] ?? ''); ?>" class="form-control"></div>
      <div class="col-md-2"><label>Foto</label><input type="file" name="photo" class="form-control-file"></div>
      <div class="col-md-2"><button class="btn btn-primary"><?php echo $editing ? 'Simpan Perubahan' : 'Tambah Guru'; ?></button></div>
    </form>
  </div>
</div>

<div class="card">
  <div class="card-body">
    <table class="table table-bordered table-hover">
      <thead><tr><th>#</th><th>Nama</th><th>Mapel</th><th>Kontak</th><th>Foto</th><th>Aksi</th></tr></thead>
      <tbody>
        <?php foreach ($teachers as $i=>$g): ?>
        <tr>
          <td><?php echo $i+1; ?></td>
          <td><?php echo e($g['name']); ?></td>
          <td><?php echo e($g['subject']); ?></td>
          <td><?php echo e($g['contact']); ?></td>
          <td><?php if (!empty($g['photo'])): ?><img src="<?php echo base_url(); ?>/data/uploads/teachers/<?php echo e($g['photo']); ?>" style="height:48px;width:48px;object-fit:cover;border-radius:4px;"><?php endif; ?></td>
          <td>
            <a href="guru.php?edit=<?php echo $g['id']; ?>" class="btn btn-sm btn-primary">Edit</a>
            <a href="guru.php?delete=<?php echo $g['id']; ?>" class="btn btn-sm btn-danger" onclick="return confirm('Hapus guru?')">Hapus</a>
          </td>
        </tr>
        <?php endforeach; ?>
        <?php if (empty($teachers)): ?><tr><td colspan="6" class="text-center text-muted">Belum ada data guru.</td></tr><?php endif; ?>
      </tbody>
    </table>
  </div>
</div>
<?php require __DIR__ . '/_footer.php'; ?>
