<?php
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/functions.php';
require_login();
$db = get_db();

// Lightweight migration: ensure 'photo' column exists (older DBs may lack it)
try {
  $cols = $db->query("PRAGMA table_info(students)")->fetchAll(PDO::FETCH_ASSOC);
  $names = array_map(function($c){ return $c['name']; }, $cols ?: []);
  if (!in_array('photo', $names)) {
    // Add photo column (TEXT, nullable)
    $db->exec("ALTER TABLE students ADD COLUMN photo TEXT");
  }
} catch (Exception $e) {
  // ignore - if table missing or other issue, operations below will handle via exceptions
}

// Add student (with optional photo upload)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'add') {
  $nis = trim($_POST['nis'] ?? '');
  $name = trim($_POST['name'] ?? '');
  $grade = trim($_POST['grade'] ?? '');
  $photoFilename = null;
  if (!empty($_FILES['photo']['name'])) {
    $up = __DIR__ . '/../data/uploads';
    if (!is_dir($up)) mkdir($up, 0755, true);
    $ext = pathinfo($_FILES['photo']['name'], PATHINFO_EXTENSION);
    $photoFilename = uniqid('s_') . '.' . $ext;
    move_uploaded_file($_FILES['photo']['tmp_name'], $up . '/' . $photoFilename);
  }
  if ($nis && $name) {
    $stmt = $db->prepare('INSERT INTO students (nis,name,grade,photo) VALUES (:nis,:name,:grade,:photo)');
    try {
      $stmt->execute([':nis'=>$nis,':name'=>$name,':grade'=>$grade,':photo'=>$photoFilename]);
      flash_set('success','Siswa berhasil ditambahkan');
    } catch (Exception $e) {
      flash_set('error','Gagal menyimpan: '.$e->getMessage());
    }
  } else {
    flash_set('error','NIS dan Nama wajib diisi');
  }
  header('Location: students.php');
  exit;
}

// Update student
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'update') {
  $id = (int)($_POST['id'] ?? 0);
  $nis = trim($_POST['nis'] ?? '');
  $name = trim($_POST['name'] ?? '');
  $grade = trim($_POST['grade'] ?? '');
  // handle photo replace
  $photoFilename = null;
  if (!empty($_FILES['photo']['name'])) {
    $up = __DIR__ . '/../data/uploads';
    if (!is_dir($up)) mkdir($up, 0755, true);
    $ext = pathinfo($_FILES['photo']['name'], PATHINFO_EXTENSION);
    $photoFilename = uniqid('s_') . '.' . $ext;
    move_uploaded_file($_FILES['photo']['tmp_name'], $up . '/' . $photoFilename);
    // optionally: remove old photo
    $old = $db->prepare('SELECT photo FROM students WHERE id = :id');
    $old->execute([':id'=>$id]);
    $row = $old->fetch(PDO::FETCH_ASSOC);
    if ($row && !empty($row['photo'])) {
      @unlink(__DIR__ . '/../data/uploads/' . $row['photo']);
    }
  }
  $sql = 'UPDATE students SET nis=:nis, name=:name, grade=:grade';
  if ($photoFilename) $sql .= ', photo=:photo';
  $sql .= ' WHERE id=:id';
  $stmt = $db->prepare($sql);
  $params = [':nis'=>$nis,':name'=>$name,':grade'=>$grade,':id'=>$id];
  if ($photoFilename) $params[':photo'] = $photoFilename;
  try {
    $stmt->execute($params);
    flash_set('success','Siswa berhasil diupdate');
  } catch (Exception $e) {
    flash_set('error','Gagal update: '.$e->getMessage());
  }
  header('Location: students.php');
  exit;
}

// Delete
if (isset($_GET['delete'])) {
  $id = (int)$_GET['delete'];
  // remove photo file
  $old = $db->prepare('SELECT photo FROM students WHERE id = :id');
  $old->execute([':id'=>$id]);
  $row = $old->fetch(PDO::FETCH_ASSOC);
  if ($row && !empty($row['photo'])) {
    @unlink(__DIR__ . '/../data/uploads/' . $row['photo']);
  }
  $stmt = $db->prepare('DELETE FROM students WHERE id = :id');
  $stmt->execute([':id'=>$id]);
  flash_set('success','Siswa dihapus');
  header('Location: students.php');
  exit;
}

 $students = $db->query('SELECT * FROM students ORDER BY id DESC')->fetchAll(PDO::FETCH_ASSOC);
?>

<?php
// render header (sidebar + top) and open content container
require __DIR__ . '/_header.php';
?>

  <h1>Kelola Siswa</h1>
  <?php if ($msg = flash_get('success')): ?>
    <div class="alert alert-success"><?php echo e($msg); ?></div>
  <?php endif; ?>
  <?php if ($msg = flash_get('error')): ?>
    <div class="alert alert-danger"><?php echo e($msg); ?></div>
  <?php endif; ?>

  <h4>Tambah Siswa</h4>
  <form method="post" enctype="multipart/form-data" class="row g-2 mb-4">
    <input type="hidden" name="action" value="add">
    <div class="col-md-2"><input name="nis" placeholder="NIS" class="form-control"></div>
    <div class="col-md-4"><input name="name" placeholder="Nama" class="form-control"></div>
    <div class="col-md-2"><input name="grade" placeholder="Kelas" class="form-control"></div>
    <div class="col-md-2"><input type="file" name="photo" class="form-control-file"></div>
    <div class="col-md-2"><button class="btn btn-success">Tambah</button></div>
  </form>

  <table class="table table-bordered">
    <thead><tr><th>#</th><th>NIS</th><th>Nama</th><th>Kelas</th><th>Foto</th><th>Aksi</th></tr></thead>
    <tbody>
      <?php $no = 1; foreach ($students as $s): ?>
        <tr>
          <td><?php echo e($no++); ?></td>
          <td><?php echo e($s['nis']); ?></td>
          <td><?php echo e($s['name']); ?></td>
          <td><?php echo e($s['grade']); ?></td>
          <td>
            <?php if (!empty($s['photo'])): ?>
              <img src="<?php echo e(base_url()); ?>/data/uploads/<?php echo e(basename($s['photo'])); ?>" alt="foto" style="height:48px;width:48px;object-fit:cover;border-radius:6px;" />
            <?php else: ?>
              -
            <?php endif; ?>
          </td>
          <td>
            <a class="btn btn-sm btn-primary" href="student_edit.php?id=<?php echo e($s['id']); ?>">Edit</a>
            <a class="btn btn-sm btn-danger" href="students.php?delete=<?php echo e($s['id']); ?>" onclick="return confirm('Hapus?')">Hapus</a>
          </td>
        </tr>
      <?php endforeach; ?>
    </tbody>
  </table>

<?php
// render footer which closes content and includes scripts
require __DIR__ . '/_footer.php';
?>