<?php
/**
 * =====================================================
 * SIMPAS v2.0
 * Modul : Simpan Data Siswa
 * =====================================================
 */

error_reporting(E_ALL);
ini_set('display_errors', 1);

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

/* ===============================
   Validasi Request
================================ */

if ($_SERVER['REQUEST_METHOD'] != 'POST') {
    header("Location:index.php");
    exit;
}

/* ===============================
   Ambil Data Form
================================ */

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

/* ===============================
   Validasi Wajib
================================ */

if (
    empty($nis) ||
    empty($nama) ||
    empty($id_kelas)
) {

    echo "<script>

    alert('Data belum lengkap.');

    history.back();

    </script>";

    exit;
}

/* ===============================
   Cek NIS Ganda
================================ */

$cek = mysqli_query($conn,"
SELECT id_siswa
FROM siswa
WHERE nis='$nis'
LIMIT 1
");

if(mysqli_num_rows($cek)>0){

    echo "<script>

    alert('NIS sudah digunakan!');

    history.back();

    </script>";

    exit;
}

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

$foto="default.png";

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

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

    $tmp=$_FILES['foto']['tmp_name'];

    $ukuran=$_FILES['foto']['size'];

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

    $valid=[
        "jpg",
        "jpeg",
        "png"
    ];

    if(!in_array($ext,$valid)){

        echo "<script>

        alert('Format foto harus JPG atau PNG');

        history.back();

        </script>";

        exit;

    }

    if($ukuran>2097152){

        echo "<script>

        alert('Ukuran foto maksimal 2 MB');

        history.back();

        </script>";

        exit;

    }

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

    if(!move_uploaded_file(
        $tmp,
        "../../uploads/foto/".$foto
    )){

        $foto="default.png";

    }

}

/* ===============================
   QR Awal
================================ */

$qr_code = $nis;
/* ===============================
   Simpan ke Database
================================ */

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

$result = mysqli_query($conn, $sql);

/* ===============================
   Jika Gagal
================================ */

if(!$result){

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

    die("
    <h3>MySQL Error</h3>
    <hr>
    ".mysqli_error($conn)."
    <br><br>
    <a href='javascript:history.back()'>Kembali</a>
    ");

}

/* ===============================
   Ambil ID Siswa Baru
================================ */

$id_siswa = mysqli_insert_id($conn);

if($id_siswa <= 0){

    die("
    Gagal mendapatkan ID siswa baru.
    ");

}
/* ===============================
   Generate QR Code
================================ */

header("Location: generate_qr.php?id=".$id_siswa);
exit;