<?php
include "koneksi.php";

// ==== PROSES SIMPAN ====
if (isset($_POST['simpan'])) {
    $nama    = trim($_POST['nama']);
    $alamat  = trim($_POST['alamat']);
    $telepon = trim($_POST['telepon']);
    $email   = trim($_POST['email']);

    // Validasi duplikat (berdasarkan nama + telepon)
    $cek = $conn->prepare("SELECT id FROM tabel_pelanggan WHERE nama=? AND telepon=?");
    $cek->bind_param("ss", $nama, $telepon);
    $cek->execute();
    $res = $cek->get_result();

    if ($res->num_rows > 0) {
        echo "<script>alert('Pelanggan sudah ada!'); location.href='index.php?page=pelanggan_tambah';</script>";
    } else {
        $stmt = $conn->prepare("INSERT INTO tabel_pelanggan (nama, alamat, telepon, email) VALUES (?,?,?,?)");
        $stmt->bind_param("ssss", $nama, $alamat, $telepon, $email);

        if ($stmt->execute()) {
            echo "<script>alert('Pelanggan berhasil ditambahkan!'); location.href='index.php?page=pelanggan';</script>";
        } else {
            echo "Gagal tambah pelanggan: " . $stmt->error;
        }
    }
}
?>

<div class="container mt-4">
    <h3>Tambah Pelanggan Baru</h3>
    <form method="post">
        <div class="mb-3">
            <label>Nama</label>
            <input type="text" name="nama" class="form-control" required>
        </div>
        <div class="mb-3">
            <label>Alamat</label>
            <textarea name="alamat" class="form-control"></textarea>
        </div>
        <div class="mb-3">
            <label>Telepon</label>
            <input type="text" name="telepon" class="form-control">
        </div>
        <div class="mb-3">
            <label>Email</label>
            <input type="email" name="email" class="form-control">
        </div>
        <button type="submit" name="simpan" class="btn btn-success">Simpan</button>
        <a href="index.php?page=pelanggan" class="btn btn-secondary">Kembali</a>
    </form>
</div>
