<?php
include "koneksi.php";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $id = intval($_POST['id']);
    $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'];

    // Ambil data lama untuk hapus gambar lama jika ada upload baru
    $qry_old = mysqli_query($koneksi, "SELECT gambar FROM list_game WHERE id = $id");
    $old_game = mysqli_fetch_array($qry_old);
    $old_image = $old_game['gambar'];

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

    // Proses Upload Gambar Baru jika Ada
    if (!empty($_FILES['gambar']['name'])) {
        $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)) {
            // Hapus gambar lama jika ada
            if (file_exists($old_image) && !empty($old_image)) {
                unlink($old_image);
            }

            // Update dengan gambar baru
            $query = "UPDATE list_game SET provider = '$provider_id', gambar = '$gambar_path', keterangan = '$keterangan' WHERE id = $id";
        } else {
            echo "Gagal mengupload gambar.";
            exit();
        }
    } else {
        // Jika tidak ada gambar baru, hanya update data lainnya
        $query = "UPDATE list_game SET provider = '$provider_id', keterangan = '$keterangan' WHERE id = $id";
    }

    if (mysqli_query($koneksi, $query)) {
        header("Location: index.php?page=voucher&notif=berhasil_ubah_data");
        exit();
    } else {
        echo "Error: " . mysqli_error($koneksi);
    }
}
?>