<?php
require '../assets/config-data.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $nama = mysqli_real_escape_string($data, $_REQUEST['namapasaran']);
    $gambar = mysqli_real_escape_string($data, $_REQUEST['gambarpasaran']);
    $link = strtolower(mysqli_real_escape_string($data, $_REQUEST['linklivedraw']));
    $tutup = preg_replace('/[^0-9\s]+/', '', mysqli_real_escape_string($data, $_REQUEST['jamtutuppasaran']));
    $buka = preg_replace('/[^0-9\s]+/', '', mysqli_real_escape_string($data, $_REQUEST['jamresultpasaran']));

    $lower = strtolower($nama);
    $remove_space = preg_replace('/\s+/', '-', trim($lower));
    $remove_symbols = preg_replace('/\s+/', '-', trim($remove_space));
    $formated_name = rtrim($remove_symbols, '-');

    $find_pasaran = "SELECT nama_pasaranweb FROM pasaran_web WHERE nama_pasaranweb = '$formated_name'";
    $query_find_pasaran = mysqli_query($data, $find_pasaran);

    if (mysqli_num_rows($query_find_pasaran) === 0) {
        $insert_pasaran = "INSERT INTO pasaran_web (nama_pasaranweb, gambar_pasaran, link_livedraw, jam_tutuppas, jam_undipass) VALUES('$formated_name', '$gambar', '$link', '$tutup', '$buka')";
        $query = mysqli_query($data, $insert_pasaran);

        if ($query) {
            echo '
    <script>
        alert("Pasaran add Successfully!!");
        window.location.href = "../dashboard.php?hal=daftarpasaran";
    </script>
    ';
        } else {
            echo '
    <script>
        alert("Gagal Tambahkan pasaran!!");
        window.location.href = "../dashboard.php?hal=daftarpasaran";
    </script>
    ';
        }
    } else {
        echo '
    <script>
        alert("Nama Tersebut sudah ada, Silahkan isi namanya dengan unik!!");
        window.location.href = "../dashboard.php?hal=daftarpasaran";
    </script>
    ';
    }
}
