<?php
require_once __DIR__ . '/../auth/protect_admin.php';
require_once __DIR__ . '/../config/db.php';

// Ambil input
$id      = isset($_POST['id']) ? (int)$_POST['id'] : 0;
$nis     = trim($_POST['nis'] ?? '');
$nama    = trim($_POST['nama'] ?? '');
$kelas   = trim($_POST['kelas'] ?? '');
$jurusan = trim($_POST['jurusan'] ?? '');
$rombel  = trim($_POST['rombel'] ?? '');

// Simple validation
if (!$nama) {
    header("Location: /presensi_v1/pages/manage_siswa.php?err=nama_kosong");
    exit;
}

// ===============================
//  HANDLE FOTO UPLOAD (optional, max 1MB)
// ===============================
$fotoNamaBaru = null;
$uploadDir = __DIR__ . '/../upload/siswa/';

if (!is_dir($uploadDir)) {
    mkdir($uploadDir, 0777, true);
}

if (!empty($_FILES['foto']['name'])) {
    if ($_FILES['foto']['error'] !== UPLOAD_ERR_OK) {
        header("Location: /presensi_v1/pages/manage_siswa.php?err=upload_error");
        exit;
    }

    // size limit 1MB
    $maxSize = 1 * 1024 * 1024;
    if ($_FILES['foto']['size'] > $maxSize) {
        header("Location: /presensi_v1/pages/manage_siswa.php?err=file_too_large");
        exit;
    }

    $fileTmp  = $_FILES['foto']['tmp_name'];
    $fileName = $_FILES['foto']['name'];
    $fileExt  = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
    $allowedExt = ['jpg','jpeg','png'];

    if (!in_array($fileExt, $allowedExt)) {
        header("Location: /presensi_v1/pages/manage_siswa.php?err=bad_format");
        exit;
    }

    $fotoNamaBaru = time() . "_" . rand(1000,9999) . "." . $fileExt;
    if (!move_uploaded_file($fileTmp, $uploadDir . $fotoNamaBaru)) {
        header("Location: /presensi_v1/pages/manage_siswa.php?err=move_failed");
        exit;
    }
}

// ===============================
//  MODE EDIT
// ===============================
if ($id > 0) {

    $stmt = $pdo->prepare("SELECT foto FROM siswa WHERE id = :id LIMIT 1");
    $stmt->execute([':id'=>$id]);
    $old = $stmt->fetch();

    if ($fotoNamaBaru && !empty($old['foto'])) {
        $oldFile = $uploadDir . $old['foto'];
        if (file_exists($oldFile)) unlink($oldFile);
    }

    $sql = "UPDATE siswa SET nis = :nis, nama = :nama, kelas = :kelas, jurusan = :jurusan, rombel = :rombel";
    if ($fotoNamaBaru) $sql .= ", foto = :foto";
    $sql .= " WHERE id = :id";

    $stmt = $pdo->prepare($sql);
    $params = [
        ':nis' => $nis,
        ':nama' => $nama,
        ':kelas' => $kelas,
        ':jurusan' => $jurusan,
        ':rombel' => $rombel,
        ':id' => $id
    ];
    if ($fotoNamaBaru) $params[':foto'] = $fotoNamaBaru;
    $stmt->execute($params);

    header("Location: /presensi_v1/pages/manage_siswa.php?msg=updated");
    exit;
}

// ===============================
//  MODE TAMBAH
// ===============================
$stmt = $pdo->prepare("INSERT INTO siswa (nis, nama, kelas, jurusan, rombel, foto) VALUES (:nis, :nama, :kelas, :jurusan, :rombel, :foto)");
$stmt->execute([
    ':nis' => $nis,
    ':nama' => $nama,
    ':kelas' => $kelas,
    ':jurusan' => $jurusan,
    ':rombel' => $rombel,
    ':foto' => $fotoNamaBaru
]);

header("Location: /presensi_v1/pages/manage_siswa.php?msg=added");
exit;
