<?php
require "../../config/koneksi.php";
require "../../vendor/autoload.php";
require("../../config/function.php");

cek_session_admin();
$file_mimes = array('application/vnd.ms-excel', 'text/csv', 'application/csv', 'application/excel', 'application/vnd.msexcel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
if (isset($_FILES['file']['name'])) {
    $ext = ['xls', 'xlsx'];
    $arr_file = explode('.', $_FILES['file']['name']);
    $extension = end($arr_file);
    if (in_array($extension, $ext)) {
        if ('xls' == $extension) {
            $reader = new \PhpOffice\PhpSpreadsheet\Reader\Xls();
        } else {
            $reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx();
        }

        $spreadsheet = $reader->load($_FILES['file']['tmp_name']);

        $sheetData = $spreadsheet->getActiveSheet()->toArray();
        $sukses = $gagal = 0;
        
        for ($i = 1; $i < count($sheetData); $i++) {
            $id_siswa = $sheetData[$i]['0'];
            $nis = $sheetData[$i]['1'];
            $t_lahir = $sheetData[$i]['4'];
			$tgl_lahir = $sheetData[$i]['5'];
			$alamat = $sheetData[$i]['6'];
			$ayah = $sheetData[$i]['7'];
			$ibu = $sheetData[$i]['8'];
			$pek_ayah = $sheetData[$i]['9'];
			$pek_ibu = $sheetData[$i]['10'];
			$alamat_ortu = $sheetData[$i]['11'];
			$desa = $sheetData[$i]['12'];
			$kec = $sheetData[$i]['13'];
			$kab = $sheetData[$i]['14'];
			$prop = $sheetData[$i]['15'];
			$wali = $sheetData[$i]['16'];
			$pek_wali = $sheetData[$i]['17'];
			$alamat_wali = $sheetData[$i]['18'];
           $cari = mysqli_num_rows(mysqli_query($koneksi,"SELECT nis FROM siswa WHERE id_siswa='$id_siswa'"));
		   if($cari > 0){
                $exec = mysqli_query($koneksi, "UPDATE siswa 
				SET tempat_lahir='$t_lahir',
				tgl_lahir='$tgl_lahir',alamat='$alamat',ayah='$ayah',ibu='$ibu',pek_ayah='$pek_ayah',
				pek_ibu='$pek_ibu',alamat_ortu='$alamat_ortu',desa='$desa',kecamatan='$kec',
				kabupaten='$kab',provinsi='$prop',wali='$wali',pek_wali='$pek_wali',alamat_wali='$alamat_wali'
				WHERE nis='$nis'");
				
			   ($exec) ? $sukses++ : $gagal++;



            }
        }
        echo "Berhasil: $sukses | Gagal: $gagal ";
    } else {
        echo "Pilih file yang bertipe xlsx or xls";
    }
}
