<?php
include "koneksi.php";

$id = intval($_GET['id'] ?? 0);
$pelanggan = $conn->query("SELECT * FROM tabel_pelanggan WHERE id=$id")->fetch_assoc();

if (!$pelanggan) {
    die("Pelanggan tidak ditemukan!");
}

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

    $stmt = $conn->prepare("UPDATE tabel_pelanggan SET nama=?, alamat=?, telepon=?, email=? WHERE id=?");
    $stmt->bind_param("ssssi", $nama, $alamat, $telepon, $email, $id);

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

<div class="container mt-4">
    <h3>Edit Pelanggan</h3>
    <form method="post">
        <div class="mb-3">
            <label>Nama</label>
            <input type="text" name="nama" class="form-control" value="<?= htmlspecialchars($pelanggan['nama']) ?>" required>
        </div>
        <div class="mb-3">
            <label>Alamat</label>
            <textarea name="alamat" class="form-control"><?= htmlspecialchars($pelanggan['alamat']) ?></textarea>
        </div>
        <div class="mb-3">
            <label>Telepon</label>
            <input type="text" name="telepon" class="form-control" value="<?= htmlspecialchars($pelanggan['telepon']) ?>">
        </div>
        <div class="mb-3">
            <label>Email</label>
            <input type="email" name="email" class="form-control" value="<?= htmlspecialchars($pelanggan['email']) ?>">
        </div>
        <button type="submit" name="update" class="btn btn-success">Update</button>
        <a href="index.php?page=pelanggan" class="btn btn-secondary">Kembali</a>
    </form>
</div>
