<?php 
include '../../koneksi/koneksi.php';

// ambil file dari form
$nama_gambar = $_FILES['file_qris']['name'] ?? '';
$size_gambar = $_FILES['file_qris']['size'] ?? 0;
$tmp_file = $_FILES['file_qris']['tmp_name'] ?? '';
$eror = $_FILES['file_qris']['error'] ?? 4;

// validasi file
if($eror === 4){
    echo "<script>alert('TIDAK ADA FILE YANG DIPILIH'); window.location = '../tm_qris.php';</script>";
    die;
}

$ekstensiGambar = ['jpg','jpeg','png'];
$ekstensiGambarValid = explode(".", $nama_gambar);
$ekstensiGambarValid = strtolower(end($ekstensiGambarValid));

if(!in_array($ekstensiGambarValid, $ekstensiGambar)){
    echo "<script>alert('EKSTENSI GAMBAR HARUS JPG, JPEG, PNG'); window.location = '../tm_qris.php';</script>";
    die;
}

if($size_gambar > 1000000){
    echo "<script>alert('UKURAN GAMBAR TERLALU BESAR'); window.location = '../tm_qris.php';</script>";
    die;
}

// nama file baru unik
$namaGambarBaru = uniqid() . "." . $ekstensiGambarValid;

// simpan file
if (move_uploaded_file($tmp_file, "../../image/qris/".$namaGambarBaru)) {

    $tanggal = date('Y-m-d H:i:s'); // datetime otomatis

    $result = mysqli_query($conn, "INSERT INTO qris (image, tanggal) 
                                   VALUES('$namaGambarBaru', '$tanggal')");

    if($result){
        echo "<script>alert('QRIS BERHASIL DITAMBAHKAN'); window.location = '../m_qris.php';</script>";
    } else {
        echo "<script>alert('GAGAL MENYIMPAN QRIS'); window.location = '../tm_qris.php';</script>";
    }

} else {
    echo "<script>alert('GAGAL UPLOAD FILE'); window.location = '../tm_qris.php';</script>";
}
?>
