<?php
    require 'database.php';

    if (!empty($_POST)) {
        // Ambil nilai dari form
        $name = $_POST['name'];
        $id = $_POST['id'];
        $gender = $_POST['gender'];
        $umur = $_POST['umur'];
        $mobile = $_POST['mobile'];
        
        // Validasi UID
        $pdo = Database::connect();
        $sql = "SELECT COUNT(*) AS count FROM table_nodemcu_rfidrc522_mysql WHERE id = ?";
        $q = $pdo->prepare($sql);
        $q->execute(array($id));
        $data = $q->fetch(PDO::FETCH_ASSOC);
        $count = $data['count'];
        Database::disconnect();
        
        if ($count > 0) {
            // Jika UID sudah ada, tampilkan pesan peringatan
            echo "<script>alert('Kartu UID sudah digunakan. Gunakan kartu UID yang belum didaftarkan.');</script>";
            // Redirect kembali ke user data.php
            echo "<script>window.location.href = 'user data.php';</script>";
            exit; // Keluar dari skrip setelah melakukan redirect
        } else {
            // Jika UID belum ada, lanjutkan proses insert data
            $pdo = Database::connect();
            $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $sql = "INSERT INTO table_nodemcu_rfidrc522_mysql (name, id, gender, umur, mobile) VALUES (?, ?, ?, ?, ?)";
            $q = $pdo->prepare($sql);
            $q->execute(array($name, $id, $gender, $umur, $mobile));
            Database::disconnect();
            header("Location: user data.php");
        }
    }
?>
