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

if(isset($_FILES['file_csv'])){
    $file = $_FILES['file_csv']['tmp_name'];
    $handle = fopen($file, "r");
    $baris = 0;

    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $baris++;
        if($baris == 1) continue; // Melewati baris judul di Excel

        // Ambil data dari kolom CSV
        $nama    = mysqli_real_escape_string($con, $data[0]);
        $nis     = mysqli_real_escape_string($con, $data[1]);
        $tgl     = mysqli_real_escape_string($con, $data[2]);
        $kelas   = mysqli_real_escape_string($con, $data[3]);
        $jurusan = mysqli_real_escape_string($con, $data[4]);
        $gender  = mysqli_real_escape_string($con, $data[5]);

        // Cek duplikat NIS agar tidak ada data ganda
        $cek = mysqli_query($con, "SELECT nis FROM siswa WHERE nis = '$nis'");
        if(mysqli_num_rows($cek) == 0){
            // Insert ke database dengan foto default jika tidak ada
            mysqli_query($con, "INSERT INTO siswa (nama_siswa, nis, tanggal_lahir, kelas, jurusan, gender, poin_sis, foto) 
                                VALUES ('$nama', '$nis', '$tgl', '$kelas', '$jurusan', '$gender', 0, 'nophoto.jpg')");
        }
    }
    fclose($handle);
    echo "<script>alert('Data Berhasil Diimport!'); window.location='?hal=siswa';</script>";
}
?>