<?php
require_once('includes/load.php');
$page_title = 'Edit Template Message';

// Cek apakah ID template ada di URL
if (isset($_GET['id'])) {
  $template_id = intval($_GET['id']);
  // Ambil data template dari database
  $template = $db->query("SELECT * FROM crm_template_message WHERE id = $template_id")->fetch_assoc();

  // Jika template tidak ditemukan, redirect ke daftar
  if (!$template) {
    redirect('list_template_message.php');
  }
} else {
  redirect('list_template_message.php');
}

// Proses form jika disubmit
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update'])) {
  $name = $_POST['name'];
  $message = $_POST['message'];
  $tipe = $_POST['tipe'];
  $status = $_POST['status'];

  // Validasi data (tambahkan validasi sesuai kebutuhan)
  if (!empty($name) && !empty($message)) {
    // Query untuk memperbarui data di database
    $query = "UPDATE crm_template_message SET name = '$name', message = '$message', tipe = '$tipe', status = '$status' WHERE id = $template_id";

    if ($db->query($query)) {
      echo "<script>alert('Data berhasil diperbarui!');</script>";
      redirect('list_template_message.php');
    } else {
      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 Template Pesan</h2>
  <form method="POST" action="edit_template_message.php?id=<?php echo $template['id']; ?>">
    <div class="form-group">
      <label>Nama Template</label>
      <input type="text" name="name" class="form-control" value="<?php echo htmlspecialchars($template['name']); ?>"
        required>
    </div>
    <div class="form-group">
      <label>Isi Pesan</label>
      <textarea name="message" class="form-control"
        required><?php echo htmlspecialchars($template['message']); ?></textarea>
    </div>
    <div class="form-group">
      <label>Tipe</label>
      <select name="tipe" class="form-control" required>
        <option value="Internal" <?php echo $template['tipe'] === 'Internal' ? 'selected' : ''; ?>>Internal</option>
        <option value="Marketing" <?php echo $template['tipe'] === 'Marketing' ? 'selected' : ''; ?>>Marketing</option>
      </select>
    </div>
    <div class="form-group">
      <label>Status</label>
      <select name="status" class="form-control" required>
        <option value="Disetujui" <?php echo $template['status'] === 'Disetujui' ? 'selected' : ''; ?>>Disetujui
        </option>
        <option value="Menunggu Persetujuan"
          <?php echo $template['status'] === 'Menunggu Persetujuan' ? 'selected' : ''; ?>>Menunggu Persetujuan</option>
      </select>
    </div>
    <button type="submit" name="update" class="btn btn-primary">Submit</button>
    <a href="list_template_message.php" class="btn btn-secondary">Batal</a>
  </form>
</div>

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