<?php
require_once('includes/load.php');
page_require_level(1);

// Ambil data pelanggan berdasarkan ID
if (!isset($_GET['id']) || empty($_GET['id'])) {
  redirect('list_pelanggan.php');
}
$id = (int)$_GET['id'];
$pelanggan = find_by_id('pelanggan', $id);
if (!$pelanggan) {
  redirect('list_pelanggan.php');
}

// Proses update data
if (isset($_POST['update'])) {
  $nama_toko = remove_junk($db->escape($_POST['nama_toko']));
  $pic = remove_junk($db->escape($_POST['pic']));
  $alamat = remove_junk($db->escape($_POST['alamat']));
  $nomor_telp = remove_junk($db->escape($_POST['nomor_telp']));

  $query  = "UPDATE pelanggan SET nama_toko='{$nama_toko}', pic='{$pic}', alamat='{$alamat}', nomor_telp='{$nomor_telp}' WHERE id='{$id}'";
  if ($db->query($query)) {
    $session->msg('s', "Data pelanggan berhasil diperbarui");
    redirect('list_pelanggan.php', false);
  } else {
    $session->msg('d', "Gagal memperbarui data pelanggan");
    redirect("edit_pelanggan.php?id={$id}", false);
  }
}
?>

<?php include_once('layouts/header.php'); ?>

<div class="row">
  <div class="col-md-12">
    <?php echo display_msg($msg); ?>
  </div>
</div>
<div class="row">
  <div class="col-md-6">
    <div class="panel panel-default">
      <div class="panel-heading">
        <strong>
          <span class="glyphicon glyphicon-edit"></span>
          <span>Edit Pelanggan</span>
        </strong>
      </div>
      <div class="panel-body">
        <form method="POST" action="">
          <div class="form-group">
            <label>Nama Toko</label>
            <input type="text" name="nama_toko" class="form-control" value="<?php echo $pelanggan['nama_toko']; ?>"
              required>
          </div>
          <div class="form-group">
            <label>PIC</label>
            <input type="text" name="pic" class="form-control" value="<?php echo $pelanggan['pic']; ?>" required>
          </div>
          <div class="form-group">
            <label>Alamat</label>
            <textarea name="alamat" class="form-control" required><?php echo $pelanggan['alamat']; ?></textarea>
          </div>
          <div class="form-group">
            <label>Nomor Telepon</label>
            <input type="text" name="nomor_telp" class="form-control" value="<?php echo $pelanggan['nomor_telp']; ?>"
              required>
          </div>
          <button type="submit" name="update" class="btn btn-success">Update</button>
          <a href="list_pelanggan.php" class="btn btn-default">Batal</a>
        </form>
      </div>
    </div>
  </div>
</div>

<?php include_once('layouts/footer.php'); ?>