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

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

// Ambil data dari form
$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']);

// Default
$foto = "default.png";
$qr_code = "";

// ==========================
// Upload Foto
// ==========================

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)){

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

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

    }

}

// ==========================
// Simpan Database
// ==========================

$sql = mysqli_query($conn,"INSERT INTO siswa
(
    nis,
    nisn,
    nama_siswa,
    id_kelas,
    jk,
    foto,
    qr_code,
    status
)
VALUES
(
    '$nis',
    '$nisn',
    '$nama_siswa',
    '$id_kelas',
    '$jk',
    '$foto',
    '$qr_code',
    '$status'
)");

if($sql){

    echo "

    <script>

    alert('Data siswa berhasil disimpan.');

    window.location='index.php';

    </script>

    ";

}else{

    echo "

    <script>

    alert('Gagal menyimpan data!');

    window.history.back();

    </script>

    ";

}
?>