<?php
if(!defined('INDEX')) die();

// 1. Amankan input data menggunakan mysqli_real_escape_string
$nama = mysqli_real_escape_string($con, $_POST['nama']);
$kode = mysqli_real_escape_string($con, $_POST['kode']);
$poin = mysqli_real_escape_string($con, $_POST['poin']);

// 2. Validasi sederhana agar data tidak kosong
if(empty($nama) || empty($kode) || empty($poin)){
    echo "<script>alert('Gagal! Semua kolom harus diisi.'); window.history.back();</script>";
    exit();
}

// 3. Cek apakah kode tebusan sudah ada sebelumnya (mencegah duplikat)
$cek_kode = mysqli_query($con, "SELECT kode_tebus FROM tebus WHERE kode_tebus = '$kode'");
if(mysqli_num_rows($cek_kode) > 0){
    echo "<script>alert('Gagal! Kode tebusan sudah digunakan, gunakan kode lain.'); window.history.back();</script>";
    exit();
}

// 4. Proses Insert Data
$query  = "INSERT INTO tebus (nama_tebus, kode_tebus, poin_tebus) 
           VALUES ('$nama', '$kode', '$poin')";
$result = mysqli_query($con, $query);

// 5. Tampilan Pesan Berhasil/Gagal dengan desain AdminLTE
echo "<section class='content'>";
if ($result) {
    echo "<div class='alert alert-success alert-dismissible'>
            <button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;</button>
            <h4><i class='icon fa fa-check'></i> Berhasil!</h4>
            Macam tebusan <b>$nama</b> telah berhasil ditambahkan ke database.
          </div>";
    echo "<meta http-equiv='refresh' content='2; url=?hal=pebus'>";
} else {
    echo "<div class='alert alert-danger alert-dismissible'>
            <button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;</button>
            <h4><i class='icon fa fa-ban'></i> Gagal!</h4>
            Terjadi kesalahan sistem: " . mysqli_error($con) . "
          </div>";
    echo "<a href='?hal=pebus_tambah' class='btn btn-warning'>Kembali ke Form</a>";
}
echo "</section>";
?>