<?php
include('../session.php');

$nama_qris   = mysqli_real_escape_string($conn, $_POST['nama_qris'] ?? '');
$status      = intval($_POST['status'] ?? 1); // default aktif
$uploadDir   = '../../upload/qris/';

// Pastikan folder upload ada
if (!file_exists($uploadDir)) {
    mkdir($uploadDir, 0777, true);
}

if (isset($_FILES['image']) && $_FILES['image']['error'] == 0) {
    $allowed = ['jpg', 'jpeg', 'png'];
    $filename = $_FILES['image']['name'];
    $filesize = $_FILES['image']['size'];
    $filetmp  = $_FILES['image']['tmp_name'];
    $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));

    // Validasi ekstensi file
    if (!in_array($ext, $allowed)) {
        header('location:../qris.php?notif=3'); // ❌ ekstensi tidak valid
        exit;
    }

    // Validasi ukuran file (maks 2 MB)
    if ($filesize > 5 * 1024 * 1024) {
        header('location:../qris.php?notif=2'); // ❌ ukuran terlalu besar
        exit;
    }

    // Nonaktifkan QRIS lama jika yang baru diaktifkan
    if ($status == 1) {
        mysqli_query($conn, "UPDATE tb_qris SET status = 0");
    }

    // Simpan file baru dengan nama unik
    $newname = 'qris_' . time() . '.' . $ext;
    $target  = $uploadDir . $newname;

    if (move_uploaded_file($filetmp, $target)) {
        // Simpan ke database
        $sql = "INSERT INTO tb_qris (nama_qris, gambar_qris, keterangan, status)
                VALUES ('$nama_qris', '$newname', 'Aktif', '$status')";
        if (mysqli_query($conn, $sql)) {
            header('location:../qris.php?notif=1'); // ✅ berhasil
            exit;
        } else {
            echo "Database error: " . mysqli_error($conn);
        }
    } else {
        echo "Upload gagal!";
    }
} else {
    header('location:../qris.php?notif=4'); // ❌ tidak ada file diupload
    exit;
}
?>
