<?php
include 'koneksi.php';

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

    // Cek nama supplier sudah digunakan oleh supplier lain
    $cek_nama = "SELECT * FROM supplier WHERE nama_supplier = '$nama_supplier' AND id_supplier != '$id_supplier'";
    $result_nama = mysqli_query($conn, $cek_nama);

    // Cek email sudah digunakan oleh supplier lain
    $cek_email = "SELECT * FROM supplier WHERE email = '$email' AND id_supplier != '$id_supplier'";
    $result_email = mysqli_query($conn, $cek_email);

    // Cek telepon sudah digunakan oleh supplier lain
    $cek_telepon = "SELECT * FROM supplier WHERE telepon = '$telepon' AND id_supplier != '$id_supplier'";
    $result_telepon = mysqli_query($conn, $cek_telepon);

    if (mysqli_num_rows($result_nama) > 0) {
        echo "<script>alert('Nama supplier sudah digunakan oleh supplier lain!'); window.location='supplier.php';</script>";
    } elseif (mysqli_num_rows($result_email) > 0) {
        echo "<script>alert('Email sudah digunakan oleh supplier lain!'); window.location='supplier.php';</script>";
    } elseif (mysqli_num_rows($result_telepon) > 0) {
        echo "<script>alert('Nomor telepon sudah digunakan oleh supplier 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 = "UPDATE supplier SET 
                  nama_supplier = '$nama_supplier',
                  alamat = '$alamat',
                  telepon = '$telepon',
                  email = '$email'
                  WHERE id_supplier = '$id_supplier'";
        
        if (mysqli_query($conn, $query)) {
            echo "<script>alert('Data supplier berhasil diperbarui!'); window.location='supplier.php';</script>";
        } else {
            echo "<script>alert('Gagal memperbarui data supplier.'); window.location='supplier.php';</script>";
        }
    }
}
?>