<?php
if(!defined('INDEX')) die();

// Mengambil data dari form
$id      = $_POST['id'];
$nama    = mysqli_real_escape_string($con, $_POST['nama_siswa']);
$nis     = mysqli_real_escape_string($con, $_POST['nis']);
$tgl     = $_POST['tanggal_lahir']; // DISESUAIKAN: tadi di form namanya tanggal_lahir
$kelas   = $_POST['kelas'];
$jurusan = $_POST['jurusan'];
$gender  = $_POST['gender'];

// Data Foto
$foto   = $_FILES['foto']['name'];
$lokasi = $_FILES['foto']['tmp_name'];
$tipe   = $_FILES['foto']['type'];
$ukuran = $_FILES['foto']['size'];

$error = "";

if($foto == ""){
    // Update data TANPA ganti foto
    $query  = "UPDATE siswa SET ";
    $query .= "nama_siswa = '$nama', ";
    $query .= "nis = '$nis', ";
    $query .= "tanggal_lahir = '$tgl', ";
    $query .= "kelas = '$kelas', ";
    $query .= "jurusan = '$jurusan', ";
    $query .= "gender = '$gender' "; // Pastikan ada spasi sebelum kutip tutup
    $query .= "WHERE id_siswa = '$id'";

    $result = mysqli_query($con, $query);
} else {
    // Proses jika ganti foto
    $tipe_diizinkan = ["image/jpeg", "image/jpg", "image/png"];
    
    if(!in_array($tipe, $tipe_diizinkan)){
        $error = "Maaf, tipe file tidak didukung! Gunakan JPG/PNG.";
    } elseif($ukuran >= 1000000){
        $error = "Ukuran file terlalu besar (Maksimal 1 MB)!";
    } else {
        // Hapus foto lama agar tidak memenuhi server
        $query_lama = mysqli_query($con, "SELECT foto FROM siswa WHERE id_siswa ='$id'");
        $data_lama  = mysqli_fetch_assoc($query_lama);
        
        if($data_lama['foto'] != "" && $data_lama['foto'] != "nophoto.jpg"){
            if(file_exists("images/$data_lama[foto]")){
                unlink("images/$data_lama[foto]");
            }
        }

        // Upload foto baru
        move_uploaded_file($lokasi, "images/".$foto);

        $query  = "UPDATE siswa SET ";
        $query .= "foto = '$foto', ";
        $query .= "nama_siswa = '$nama', ";
        $query .= "nis = '$nis', ";
        $query .= "tanggal_lahir = '$tgl', ";
        $query .= "kelas = '$kelas', ";
        $query .= "jurusan = '$jurusan', ";
        $query .= "gender = '$gender' ";
        $query .= "WHERE id_siswa = '$id'";
        
        $result = mysqli_query($con, $query);
    }
}

// Cek Hasil
if($error != ""){
    echo "<div class='alert alert-danger'>$error</div>";
    echo "<meta http-equiv='refresh' content='2; url=?hal=siswa_edit&id=$id'>";
} elseif ($result){
    echo "<div class='alert alert-success'>Berhasil memperbaharui data Siswa: <b>$nama</b></div>";
    echo "<meta http-equiv='refresh' content='1; url=?hal=siswa'>";
} else {
    echo "<div class='alert alert-danger'>Tidak dapat menyimpan data!<br>";
    echo mysqli_error($con) . "</div>";
    echo "<meta http-equiv='refresh' content='3; url=?hal=siswa_edit&id=$id'>";
}
?>