<?php
require_once('includes/load.php');
$page_title = 'Kirim Pesan';

// Ambil daftar template pesan
$templates = $db->query("SELECT * FROM crm_template_message");

// Ambil daftar grup kontak
$groups = $db->query("SELECT * FROM crm_group_contact");

// Proses form jika disubmit
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['send'])) {
  $template_id = $_POST['template_id'];
  $group_id = $_POST['group_id'];
  $template = $db->query("SELECT * FROM crm_template_message WHERE id = $template_id")->fetch_assoc();
  // Ambil kontak dari grup
  $contacts = $db->query("SELECT * FROM crm_contact WHERE crm_group_contact_id = $group_id");

  // Kirim pesan ke setiap kontak
  while ($contact = $contacts->fetch_assoc()) {
    $message_text = $template['message'];
    $nameTemplate = $template['name'];
    $typeTemplate = $template['tipe'];
    $sender_id = 1; // Ganti dengan ID pengirim yang sesuai
    $receiver_id = $contact['id'];
    $phoneNumber = $contact['phone_number'];
    $sendWA = false;
    if ($typeTemplate == "Marketing") {
      $sendWA = sendWhatsAppTemplateMessage($phoneNumber, $nameTemplate);
    } else {
      $sendWA = sendWhatsAppMessage($phoneNumber, $message_text);
    }
    if ($sendWA) {
      $db->query("INSERT INTO crm_message (sender_id, receiver_id, message_text) VALUES ($sender_id, $receiver_id, '$message_text')");
    }
  }

  redirect('send_bulk_message.php');
}
?>

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

<div class="container mt-5">
  <h2>Kirim Pesan Massal</h2>
  <form method="POST" action="send_bulk_message.php">
    <div class="form-group">
      <label>Pilih Template Pesan</label>
      <select name="template_id" class="form-control" required>
        <?php while ($template = $templates->fetch_assoc()): ?>
        <option value="<?php echo $template['id']; ?>"><?php echo htmlspecialchars($template['name']); ?></option>
        <?php endwhile; ?>
      </select>
    </div>
    <div class="form-group">
      <label>Pilih Grup Kontak</label>
      <select name="group_id" class="form-control" required>
        <?php while ($group = $groups->fetch_assoc()): ?>
        <option value="<?php echo $group['id']; ?>"><?php echo htmlspecialchars($group['name']); ?></option>
        <?php endwhile; ?>
      </select>
    </div>
    <button type="submit" name="send" class="btn btn-primary">Kirim Pesan</button>
  </form>
</div>

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