<?php
include "koneksi.php";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $provider_id = intval($_POST['provider']);
    $keterangan = mysqli_real_escape_string($koneksi, $_POST['keterangan']);

    // Ambil nama provider berdasarkan ID
    $qry = mysqli_query($koneksi, "SELECT nama_provider FROM list_provider WHERE id = $provider_id");
    $provider = mysqli_fetch_array($qry);
    if (!$provider) {
        die("Provider tidak ditemukan.");
    }
    $nama_provider = $provider['nama_provider'];

    // Pastikan folder penyimpanan ada
    $upload_dir = "../img/" . $nama_provider;
    if (!is_dir($upload_dir)) {
        mkdir($upload_dir, 0777, true);
    }

    // Proses Upload Gambar
    $gambar_name = $_FILES['gambar']['name'];
    $gambar_tmp = $_FILES['gambar']['tmp_name'];
    $gambar_path = $upload_dir . "/" . $gambar_name;

    if (move_uploaded_file($gambar_tmp, $gambar_path)) {
        // Simpan ke database
        $query = "INSERT INTO list_game (provider, gambar, keterangan) VALUES ('$provider_id', '$gambar_path', '$keterangan')";
        if (mysqli_query($koneksi, $query)) {
            header("Location: index.php?page=voucher&notif=berhasil_tambah_data");
            exit();
        } else {
            echo "Error: " . mysqli_error($koneksi);
        }
    } else {
        echo "Gagal mengupload gambar.";
    }
}
?>
