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

// Check if the ID is provided
if (isset($_GET['id'])) {
  $group_id = intval($_GET['id']);
  // Fetch the group details from the database
  $group = find_by_id('crm_group_contact', $group_id);

  // Check if the group exists
  if (!$group) {
    redirect('list_group_contact.php');
  }
} else {
  redirect('list_group_contact.php');
}

// Check if the form has been submitted
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update'])) {
  // Get data from the form
  $name = $_POST['name'];

  // Validate data (optional, add validation as needed)
  if (!empty($name)) {
    // Query to update the group in the database
    $query = "UPDATE crm_group_contact SET name = '$name' WHERE id = $group_id";

    if ($db->query($query)) {
      // If successful, redirect or display success message
      echo "<script>alert('Data berhasil diperbarui!');</script>";
      redirect('list_group_contact.php');
    } else {
      // If failed, display error message
      echo "<script>alert('Gagal memperbarui data: " . $db->error . "');</script>";
    }
  } else {
    echo "<script>alert('Harap isi semua data dengan benar!');</script>";
  }
}
?>

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

<div class="container mt-5">
  <h2>Edit Group Contact</h2>
  <form method="POST" action="edit_group_contact.php?id=<?php echo $group_id; ?>">
    <div class="form-group">
      <label>Nama Group</label>
      <input type="text" name="name" class="form-control" value="<?php echo htmlspecialchars($group['name']); ?>"
        required>
    </div>
    <button type="submit" name="update" class="btn btn-primary">Update</button>
    <a href="list_group_contact.php" class="btn btn-secondary">Batal</a>
  </form>
</div>

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