<?php
/**
 * =====================================================
 * SIMPAS v1.0
 * Modul : Data Siswa
 * File   : update.php
 * =====================================================
 */

include "../../config/koneksi.php";
include "../../config/session.php";

$id_siswa   = mysqli_real_escape_string($conn, $_POST['id_siswa']);
$nis        = mysqli_real_escape_string($conn, $_POST['nis']);
$nisn       = mysqli_real_escape_string($conn, $_POST['nisn']);
$nama_siswa = mysqli_real_escape_string($conn, $_POST['nama_siswa']);
$jk         = mysqli_real_escape_string($conn, $_POST['jk']);
$id_kelas   = mysqli_real_escape_string($conn, $_POST['id_kelas']);
$status     = mysqli_real_escape_string($conn, $_POST['status']);

$foto = $_POST['foto_lama'];

/*
|--------------------------------------------------------------------------
| Upload Foto Baru
|--------------------------------------------------------------------------
*/

if(isset($_FILES['foto']) && $_FILES['foto']['error']==0){

    $namaFile = $_FILES['foto']['name'];
    $tmpFile  = $_FILES['foto']['tmp_name'];

    $ext = strtolower(pathinfo($namaFile, PATHINFO_EXTENSION));

    $extValid = ['jpg','jpeg','png'];

    if(in_array($ext,$extValid)){

        if($foto!="default.png" && file_exists("../../uploads/foto/".$foto)){
            unlink("../../uploads/foto/".$foto);
        }

        $foto = time().'_'.$namaFile;

        move_uploaded_file(
            $tmpFile,
            "../../uploads/foto/".$foto
        );

    }

}

/*
|--------------------------------------------------------------------------
| Update Database
|--------------------------------------------------------------------------
*/

$sql = mysqli_query($conn,"UPDATE siswa SET

nis='$nis',
nisn='$nisn',
nama_siswa='$nama_siswa',
id_kelas='$id_kelas',
jk='$jk',
foto='$foto',
status='$status'

WHERE id_siswa='$id_siswa'

");

if($sql){

    echo "

    <script>

    alert('Data siswa berhasil diperbarui.');

    window.location='index.php';

    </script>

    ";

}else{

    echo "

    <script>

    alert('Data gagal diperbarui.');

    window.history.back();

    </script>

    ";

}
?>