<?php
session_start();
include '../koneksi.php';

// Aksi Simpan & Update (Otomatis menyesuaikan kolom)
if (isset($_POST['simpan'])) {
    $id = $_POST['id'];
    $data = $_POST;
    unset($data['simpan'], $data['id']);

    if (!empty($_FILES['foto']['name'])) {
        $nama_foto = time() . '_' . $_FILES['foto']['name'];
        move_uploaded_file($_FILES['foto']['tmp_name'], '../assets/img/siswa/' . $nama_foto);
        $data['foto'] = $nama_foto;
    }

    $set_query = "";
    foreach ($data as $k => $v) { $set_query .= "$k = '" . mysqli_real_escape_string($koneksi, $v) . "', "; }
    $set_query = rtrim($set_query, ', ');

    if ($id != "") {
        mysqli_query($koneksi, "UPDATE master_siswa SET $set_query WHERE id_siswa='$id'");
    } else {
        mysqli_query($koneksi, "INSERT INTO master_siswa SET $set_query");
    }
    header("Location: siswa.php?pesan=berhasil");
}

// Aksi Hapus
elseif (isset($_GET['hapus'])) {
    mysqli_query($koneksi, "DELETE FROM master_siswa WHERE id_siswa='".(int)$_GET['hapus']."'");
    header("Location: siswa.php?pesan=terhapus");
}

// Aksi Import CSV (Pemisah titik koma ;)
elseif (isset($_POST['import'])) {
    $file = fopen($_FILES['file_csv']['tmp_name'], "r");
    fgetcsv($file); // Skip header
    while (($row = fgetcsv($file, 2000, ";")) !== FALSE) {
        $row = array_pad($row, 4, '');
        $q = "INSERT INTO master_siswa (nis, nisn, nama, jk) VALUES ('".mysqli_real_escape_string($koneksi, $row[0])."', '".mysqli_real_escape_string($koneksi, $row[1])."', '".mysqli_real_escape_string($koneksi, $row[2])."', '".mysqli_real_escape_string($koneksi, $row[3])."')";
        mysqli_query($koneksi, $q);
    }
    fclose($file);
    header("Location: siswa.php?pesan=import_berhasil");
}
?>