<!-- FILE: tambahsupplier.php -->
<?php
include 'koneksi.php';

if (isset($_POST['tambah'])) {
    $nama_supplier = $_POST['nama_supplier'];
    $alamat = $_POST['alamat'];
    $telepon = $_POST['telepon'];
    $email = $_POST['email'];

    // Cek nama supplier sudah ada atau belum
    $cek_nama = "SELECT * FROM supplier WHERE nama_supplier = '$nama_supplier'";
    $result_nama = mysqli_query($conn, $cek_nama);

    // Cek email sudah digunakan atau belum
    $cek_email = "SELECT * FROM supplier WHERE email = '$email'";
    $result_email = mysqli_query($conn, $cek_email);

    // Cek telepon sudah digunakan atau belum
    $cek_telepon = "SELECT * FROM supplier WHERE telepon = '$telepon'";
    $result_telepon = mysqli_query($conn, $cek_telepon);

    if (mysqli_num_rows($result_nama) > 0) {
        echo "<script>alert('Nama supplier sudah digunakan! Gunakan nama supplier lain.'); window.location='supplier.php';</script>";
    } elseif (mysqli_num_rows($result_email) > 0) {
        echo "<script>alert('Email sudah digunakan! Gunakan email lain.'); window.location='supplier.php';</script>";
    } elseif (mysqli_num_rows($result_telepon) > 0) {
        echo "<script>alert('Nomor telepon sudah digunakan! Gunakan nomor telepon lain.'); window.location='supplier.php';</script>";
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        echo "<script>alert('Format email tidak valid!'); window.location='supplier.php';</script>";
    } else {
        $query = "INSERT INTO supplier (nama_supplier, alamat, telepon, email) 
                  VALUES ('$nama_supplier', '$alamat', '$telepon', '$email')";
        
        if (mysqli_query($conn, $query)) {
            echo "<script>alert('Supplier berhasil ditambahkan!'); window.location='supplier.php';</script>";
        } else {
            echo "<script>alert('Gagal menambahkan supplier.'); window.location='supplier.php';</script>";
        }
    }
}
?>