<?php
// ---------- Bootstrap & Security ----------
error_reporting(0);
ini_set('display_errors', 0);

use SendinBlue\Client\Configuration;
use SendinBlue\Client\Api\TransactionalEmailsApi;
use SendinBlue\Client\Model\SendSmtpEmail;
use Zenoph\Notify\Enums\AuthModel;
use Zenoph\Notify\Enums\SMSType;
use Zenoph\Notify\Request\SMSRequest;

require_once('../vendor/autoload.php');
include_once("../Zenoph/Notify/AutoLoader.php");
include_once('../header.php');
include_once('../functions.php');

if (!check_login()) {
  header("Location: " . WEB_URL . "logout.php");
  die();
}

include_once(ROOT_PATH . 'language/' . $lang_code_global . '/lang_mailsms_list.php');

// ---------- Helpers ----------
function v($arr, $key, $default = '') { return isset($arr[$key]) ? $arr[$key] : $default; }
function clean_text($s) { return trim((string)$s); }
function e($s) { return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }

/** Normalize Ghana phone numbers for SMS (digits only, no '+') */
function normalize_phone_gh($raw) {
  $n = preg_replace('/\D+/', '', (string)$raw);
  if ($n === '') return '';
  if (preg_match('/^0\d{9}$/', $n)) return '233' . substr($n, 1);
  if (preg_match('/^233\d{9}$/', $n)) return $n;
  return ltrim($n, '+');
}

/** Validate Ghana E.164 digits (no plus): 233 followed by 9 digits */
function is_valid_gh_msisdn($digitsNoPlus) {
  return (bool)preg_match('/^233\d{9}$/', $digitsNoPlus);
}

/**
 * Recipients: tenants, current tenants (block/unit), admins, buyers, or a specific tenant/buyer by exact name
 */
function get_recipients(mysqli $link, array $opts) {
  $out = [];

  $specific_tenant = clean_text(v($opts, 'specific_tenant', ''));
  $specific_buyer  = clean_text(v($opts, 'specific_buyer', ''));

  $send_tenants    = !empty($opts['tenants']);
  $send_current    = !empty($opts['current']);
  $send_admins     = !empty($opts['admins']);
  $send_buyers     = !empty($opts['buyers']);

  $block_id        = (int)v($opts, 'block_id', 0);
  $unit_id         = (int)v($opts, 'unit_id', 0);

  // Exclusive: a specific tenant by exact name
  if ($specific_tenant !== '') {
    $nameEsc = mysqli_real_escape_string($link, $specific_tenant);
    $sql = "SELECT r_name AS name, r_contact AS phone, r_email AS email
              FROM tenants
             WHERE r_name = '{$nameEsc}'";
    if ($res = mysqli_query($link, $sql)) {
      while ($r = mysqli_fetch_assoc($res)) {
        $out[] = ['name'=>clean_text($r['name']), 'phone'=>clean_text($r['phone']), 'email'=>clean_text($r['email'])];
      }
      mysqli_free_result($res);
    }
    return $out;
  }

  // Exclusive: a specific buyer by exact name
  if ($specific_buyer !== '') {
    $nameEsc = mysqli_real_escape_string($link, $specific_buyer);
    // NOTE: uses buyer_contact — change to buyer_comtact here ONLY if your DB column is misspelled.
    $sql = "SELECT buyer_name AS name, buyer_contact AS phone, buyer_email AS email
              FROM buyers
             WHERE buyer_name = '{$nameEsc}'";
    if ($res = mysqli_query($link, $sql)) {
      while ($r = mysqli_fetch_assoc($res)) {
        $out[] = ['name'=>clean_text($r['name']), 'phone'=>clean_text($r['phone']), 'email'=>clean_text($r['email'])];
      }
      mysqli_free_result($res);
    }
    return $out;
  }

  // All tenants
  if ($send_tenants) {
    $sql = "SELECT r_name AS name, r_contact AS phone, r_email AS email
              FROM tenants
             WHERE (COALESCE(r_contact,'') <> '' OR COALESCE(r_email,'') <> '')";
    if ($res = mysqli_query($link, $sql)) {
      while ($r = mysqli_fetch_assoc($res)) {
        $out[] = ['name'=>clean_text($r['name']), 'phone'=>clean_text($r['phone']), 'email'=>clean_text($r['email'])];
      }
      mysqli_free_result($res);
    }
  }

  // Current tenants (occupied units), optional block/unit filter
  if ($send_current) {
    $filter = ($unit_id > 0) ? "uid = {$unit_id}" : (($block_id > 0) ? "bid = {$block_id}" : "1=1");
    $sql = "SELECT r_name AS name, r_contact AS phone, r_email AS email
              FROM occupied_units_view
             WHERE {$filter}
               AND (COALESCE(r_contact,'') <> '' OR COALESCE(r_email,'') <> '')
             GROUP BY r_name, r_contact, r_email";
    if ($res = mysqli_query($link, $sql)) {
      while ($r = mysqli_fetch_assoc($res)) {
        $out[] = ['name'=>clean_text($r['name']), 'phone'=>clean_text($r['phone']), 'email'=>clean_text($r['email'])];
      }
      mysqli_free_result($res);
    }
  }

  // Admins
  if ($send_admins) {
    $sql = "SELECT name, contact AS phone, email
              FROM admins
             WHERE (COALESCE(contact,'') <> '' OR COALESCE(email,'') <> '')";
    if ($res = mysqli_query($link, $sql)) {
      while ($r = mysqli_fetch_assoc($res)) {
        $out[] = ['name'=>clean_text($r['name']), 'phone'=>clean_text($r['phone']), 'email'=>clean_text($r['email'])];
      }
      mysqli_free_result($res);
    }
  }

  // Buyers
  if ($send_buyers) {
    // NOTE: uses buyer_contact — change to buyer_comtact here ONLY if your DB column is misspelled.
    $sql = "SELECT buyer_name AS name, buyer_contact AS phone, buyer_email AS email
              FROM buyers
             WHERE (COALESCE(buyer_contact,'') <> '' OR COALESCE(buyer_email,'') <> '')";
    if ($res = mysqli_query($link, $sql)) {
      while ($r = mysqli_fetch_assoc($res)) {
        $out[] = ['name'=>clean_text($r['name']), 'phone'=>clean_text($r['phone']), 'email'=>clean_text($r['email'])];
      }
      mysqli_free_result($res);
    }
  }

  return $out;
}

// ---------- UI data (blocks & units) ----------
$blocks_result = mysqli_query($link, "SELECT DISTINCT bid, b_name FROM unit_view ORDER BY b_name");
$units_result  = mysqli_query($link, "SELECT uid, bid, unit_no FROM unit_view ORDER BY unit_no");

// ---------- Banner states ----------
$delinfo = 'none';
$addinfo = 'none';
$msg     = '';
$cur_time = date("Y-m-d H:i:s");

// ---------- Handle form POST (send) ----------
if ($_SERVER["REQUEST_METHOD"] === "POST") {
  $post   = post_input_serilization();
  $title  = clean_text(v($_POST, "title", ''));
  $message= clean_text(v($_POST, "message", ''));
  $specific_tenant = clean_text(v($_POST, "specific_tenant", ''));
  $specific_buyer  = clean_text(v($_POST, "specific_buyer", ''));

  $block_id      = (int)v($_POST, "block_id", 0);
  $specific_unit = (int)v($_POST, "specific_unit", 0);

  if ($message === '' || $title === '') {
    $msg     = "Provide both a title and message.";
    $delinfo = 'block';
  } else {
    // Selection
    $send_to_tenants         = v($post,'recipient_tenants') === 'on';
    $send_to_current_tenants = v($post,'recipient_current_tenants') === 'on';
    $send_to_admins          = v($post,'recipient_admins') === 'on';
    $send_to_buyers          = v($post,'recipient_buyers') === 'on';

    if (!$send_to_tenants && !$send_to_admins && !$send_to_current_tenants && !$send_to_buyers && $specific_tenant === '' && $specific_buyer === '') {
      $msg     = "Select at least one group (Tenants, Current Tenants, Buyers, Admins) or specify a tenant/buyer.";
      $delinfo = 'block';
    } else {
      // Build recipients (includes buyers)
      $recipients = get_recipients($link, [
        'specific_tenant' => $specific_tenant,
        'specific_buyer'  => $specific_buyer,
        'tenants'         => $send_to_tenants,
        'current'         => $send_to_current_tenants,
        'admins'          => $send_to_admins,
        'buyers'          => $send_to_buyers,
        'block_id'        => $block_id,
        'unit_id'         => $specific_unit,
      ]);

      // Deduplicate by phone/email (keep invalid phones for email path; filter for SMS later)
      $seenPhones = [];
      $seenEmails = [];
      $unique = [];
      foreach ($recipients as $r) {
        $p = normalize_phone_gh($r['phone']);
        $em= strtolower(trim($r['email'] ?? ''));
        $key = $p ?: $em;
        if ($key === '') continue;
        if ($p && isset($seenPhones[$p])) continue;
        if ($em && isset($seenEmails[$em])) continue;
        if ($p)  $seenPhones[$p] = true;
        if ($em) $seenEmails[$em] = true;
        $unique[] = ['name'=>$r['name'], 'phone'=>$p, 'email'=>$em];
      }

      if (empty($unique)) {
        $msg     = "No valid recipients found for your selection.";
        $delinfo = 'block';
      } else {
        $sent_any = false;

        // SMS (Zenoph)
        if (v($post, "sms") === "on") {
          try {
            $request = new SMSRequest();
            $request->setHost('api.smsonlinegh.com');
            $request->setAuthModel(AuthModel::API_KEY);
            $request->setAuthApiKey('9fd9d812b64966b33328ef33341e799c2b6344177b69636510baa520db7bc975');
            $request->setSMSType(SMSType::GSM_DEFAULT);
            $request->setSender('NK Property');
            $request->setMessage($message);

            $smsList = [];
            foreach ($unique as $r) {
              if ($r['phone'] !== '' && is_valid_gh_msisdn($r['phone'])) {
                $request->addDestination($r['phone']);
                $smsList[] = $r;
              }
            }

            if (!empty($smsList)) {
              $request->submit(); // one shot to all added destinations
              foreach ($smsList as $r) {
                saveSMS($link, $title, $message, 'sent', $r['name'], $r['phone'], $cur_time);
              }
              $sent_any = true;
            }
          } catch (Exception $ex) {
            $delinfo = 'block';
            $msg .= ($msg ? " " : "") . "SMS error: " . $ex->getMessage();
          }
        }

        // Email (Sendinblue)
        if (v($post, "email") === "on") {
          try {
            $api_key = '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';
            $config  = Configuration::getDefaultConfiguration()->setApiKey('api-key', $api_key);
            $api     = new TransactionalEmailsApi(new GuzzleHttp\Client(), $config);

            $template_path = ROOT_PATH . "templates/email/message.html";
            $baseTemplate  = is_file($template_path) ? file_get_contents($template_path) : null;

            foreach ($unique as $r) {
              if ($r['email'] === '') continue;

              $html = $baseTemplate ?: '<h3>{subject}</h3><p>Hi {name},</p><div>{message}</div>';
              $html = str_replace(['{name}','{subject}','{message}'], [e($r['name']), e($title), nl2br(e($message))], $html);

              $emailContent = new SendSmtpEmail([
                'subject'     => $title,
                'htmlContent' => $html,
                'sender'      => ['email' => 'info@londoneyeluxury.com', 'name' => 'sideGiGGuYs'],
                'to'          => [['email' => $r['email'], 'name' => $r['name']]],
                'textContent' => strip_tags($message),
              ]);

              $response = $api->sendTransacEmail($emailContent);
              $status = (is_array($response) && isset($response['messageId'])) ? 'delivered' : 'sent';
              saveEmail($link, $title, $message, $status, $r['name'], $r['email'], $r['phone'], $cur_time);
              $sent_any = true;
            }
          } catch (Exception $e) {
            $delinfo = 'block';
            $msg .= ($msg ? " " : "") . "Email error: " . $e->getMessage();
          }
        }

        if ($sent_any && $delinfo !== 'block') {
          $addinfo = 'block';
          $msg = "Your message has been sent.";
        } elseif (!$sent_any && $delinfo !== 'block') {
          $delinfo = 'block';
          $msg = "No messages were sent (no valid phone/email found).";
        }
      }
    }
  }
}

// ---------- Fetch message logs (newest first) ----------
$result_logs = mysqli_query($link, "SELECT * FROM messages ORDER BY id DESC");
?>
<!-- ---------- Page Header ---------- -->
<section class="content-header">
  <h1 style="display:flex;align-items:center;gap:12px;margin-bottom:8px;">
    <span style="display:inline-flex;width:42px;height:42px;border-radius:12px;background:#2563eb1a;align-items:center;justify-content:center;">
      <i class="fa fa-envelope" style="color:#1e40af;"></i>
    </span>
    <span style="font-weight:800;">Messages</span>
  </h1>
  <ol class="breadcrumb">
    <li><a href="<?= WEB_URL ?>dashboard.php"><i class="fa fa-dashboard"></i> <?= e($_data['home_breadcam']); ?></a></li>
    <li class="active">Messages</li>
  </ol>
</section>

<!-- ---------- Styles ---------- -->
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700;800&display=swap" rel="stylesheet">
<style>
  :root{
    --ink:#0f172a; --ink2:#334155; --muted:#64748b; --line:#e5e7eb;
    --ok:#16a34a; --warn:#d97706; --danger:#dc2626; --brand:#2563eb; --brand2:#1e40af;
    --soft:#f8fafc; --soft2:#eef2ff; --card:#fff;
  }
  .content-wrapper, .box, .table, label, .btn, .alert, input, select, textarea {
    font-family:'Inter',system-ui,Segoe UI,Roboto,Helvetica,Arial;
    color:var(--ink2);
  }
  .content-header > h1{ font-weight:800; color:var(--ink); letter-spacing:.2px; }

  .card { background:var(--card); border:1px solid var(--line); border-radius:18px;
    box-shadow:0 16px 40px rgba(2,6,23,.06); overflow:hidden; margin-bottom:18px; }
  .card-header { display:flex; align-items:center; justify-content:space-between; gap:12px;
    padding:14px 16px; background:linear-gradient(135deg,var(--soft),var(--soft2)); border-bottom:1px solid var(--line); }
  .card-title { margin:0; font-weight:800; color:var(--ink); letter-spacing:.2px; }

  .toolbar { display:flex; gap:8px; flex-wrap:wrap; }
  .btn-pill { border-radius:999px !important; padding:10px 16px; font-weight:800; letter-spacing:.2px; }
  .btn-primary{ background:var(--brand); border-color:var(--brand); color:#fff; }
  .btn-primary:hover{ background:#1d4ed8; border-color:#1d4ed8; }
  .btn-success{ background:var(--ok); border-color:var(--ok); color:#fff; }
  .btn-success:hover{ background:#15803d; border-color:#15803d; }

  .alert{ border-radius:12px; }
  .alert-success{ background:#ecfdf5; color:#065f46; border:1px solid #bbf7d0; }
  .alert-danger{ background:#fef2f2; color:#7f1d1d; border:1px solid #fecaca; }

  .section { padding:14px 16px; color:var(--muted); }

  .table-polished { width:100%; border-collapse:separate; border-spacing:0 8px; }
  .table-polished thead th{ font-weight:800; color:var(--ink2); text-transform:uppercase; font-size:12px; letter-spacing:.35px;
    border-bottom:1px solid var(--line); padding:10px 12px; }
  .table-polished tbody tr{ background:#fff; border:1px solid var(--line); }
  .table-polished tbody td{ padding:12px; border-top:1px solid var(--line); vertical-align:middle; }
  .table-polished tbody tr:first-child td{ border-top:none; }
  .table-polished tbody tr td:first-child{ border-left:1px solid var(--line); border-radius:12px 0 0 12px; }
  .table-polished tbody tr td:last-child{ border-right:1px solid var(--line); border-radius:0 12px 12px 0; }

  .chip { display:inline-block; padding:4px 10px; border-radius:999px; border:1px solid var(--line); background:#fff; font-weight:700; font-size:12px; }
  .status-ok { color:#065f46; background:#ecfdf5; border-color:#a7f3d0; }
  .status-fail { color:#7f1d1d; background:#fef2f2; border-color:#fecaca; }

  .modal-content{ border-radius:18px; overflow:hidden; border:1px solid var(--line); box-shadow:0 30px 80px rgba(2,6,23,.18); }
  .modal-header{ background:linear-gradient(135deg,var(--soft),var(--soft2)); border-bottom:1px solid var(--line); }
  .modal-title{ font-weight:800; color:var(--ink); }

  /* Form bits */
  .grid-2 { display:grid; grid-template-columns: 1.15fr .85fr; gap:18px; }
  @media(max-width: 980px){ .grid-2{ grid-template-columns:1fr; } }

  .input, .select, .textarea { width:100%; border:1px solid var(--line); border-radius:12px; padding:10px 12px; outline:none; background:#fff; }
  .input:focus, .select:focus, .textarea:focus { border-color:#93c5fd; box-shadow:0 0 0 3px rgba(59,130,246,.15); }
  .label { font-weight:800; color:#111827; margin-bottom:6px; }
  .muted { color:var(--muted); font-size:12px; }

  /* Pretty toggles */
  .toggle { display:flex; align-items:center; gap:10px; font-weight:700; margin:6px 0; }
  .toggle input[type="checkbox"] { appearance:none; width:42px; height:24px; border-radius:999px; background:#e5e7eb; position:relative; outline:none; cursor:pointer; transition:.2s; }
  .toggle input[type="checkbox"]::after{
    content:""; position:absolute; top:3px; left:3px; width:18px; height:18px; border-radius:50%; background:#fff; box-shadow:0 2px 6px rgba(0,0,0,.15); transition:.2s;
  }
  .toggle input[type="checkbox"]:checked{ background:#2563eb; }
  .toggle input[type="checkbox"]:checked::after{ left:21px; }

  /* Live preview */
  .preview {
    border:1px dashed var(--line); border-radius:14px; padding:12px; background:#fff; margin-top:12px;
  }
  .preview h5{ margin:0 0 6px; font-weight:800; color:var(--ink); }
  .counter { font-size:12px; color:var(--muted); display:flex; gap:8px; align-items:center; }
  .badge { display:inline-block; padding:2px 8px; border-radius:999px; background:#eff6ff; color:#1e40af; font-weight:700; font-size:11px; border:1px solid #bfdbfe; }
</style>

<!-- ---------- Main ---------- -->
<section class="content">
  <div class="row">
    <div class="col-xs-12">

      <!-- Alerts -->
      <div id="me" class="alert alert-danger alert-dismissable" style="display:<?= $delinfo; ?>">
        <button aria-hidden="true" data-dismiss="alert" class="close" type="button"><i class="fa fa-close"></i></button>
        <h4 style="margin:0 0 6px;"><i class="icon fa fa-ban"></i> Error</h4>
        <?= e($msg); ?>
      </div>
      <div id="you" class="alert alert-success alert-dismissable" style="display:<?= $addinfo; ?>">
        <button aria-hidden="true" data-dismiss="alert" class="close" type="button"><i class="fa fa-close"></i></button>
        <h4 style="margin:0 0 6px;"><i class="icon fa fa-check"></i> Success</h4>
        <?= e($msg); ?>
      </div>

      <!-- Compose card -->
      <div class="card">
        <div class="card-header">
          <h3 class="card-title"><i class="fa fa-paper-plane"></i> Compose message</h3>
          <div class="toolbar">
            <a class="btn btn-primary btn-pill" data-toggle="modal" href="#addModal"><i class="fa fa-plus"></i> New</a>
            <a class="btn btn-success btn-pill" href="<?= WEB_URL; ?>dashboard.php"><i class="fa fa-dashboard"></i> <?= e($_data['home_breadcam']); ?></a>
          </div>
        </div>
        <div class="section">
          Use the <strong>New</strong> button to craft a message and send via <span class="chip">SMS</span> and/or <span class="chip">Email</span>.
        </div>
      </div>

      <!-- Logs card -->
      <div class="card">
        <div class="card-header">
          <h3 class="card-title"><i class="fa fa-list"></i> <?= e($_data['list_title']); ?></h3>
        </div>
        <div class="section">
          <div class="table-responsive">
            <table id="msgTable" class="table table-polished table-bordered dt-responsive">
              <thead>
                <tr>
                  <th>Date</th>
                  <th>Subject</th>
                  <th>Message</th>
                  <th>Channel</th>
                  <th>Receiver</th>
                  <th>Email</th>
                  <th>Phone</th>
                  <th>Status</th>
                </tr>
              </thead>
              <tbody>
                <?php while ($row = mysqli_fetch_array($result_logs)) { ?>
                  <tr>
                    <td><?= e(date('jS M, Y H:i', strtotime($row['time_created']))); ?></td>
                    <td><?= e($row['subject']); ?></td>
                    <td title="<?= e($row['message']); ?>"><?= e(mb_strimwidth($row['message'], 0, 120, '…')); ?></td>
                    <td><?= e($row['channel']); ?></td>
                    <td><?= e($row['receiver']); ?></td>
                    <td><?= e($row['receiver_email']); ?></td>
                    <td><?= e($row['receiver_phone']); ?></td>
                    <td>
                      <?php
                        $ok = in_array(strtolower($row['status']), ['sent','delivered','success']);
                        $cls = $ok ? 'status-ok' : 'status-fail';
                      ?>
                      <span class="chip <?= $cls ?>"><?= e(ucfirst($row['status'])); ?></span>
                    </td>
                  </tr>
                <?php } ?>
              </tbody>
            </table>
          </div>
        </div>
      </div>

    </div>
  </div>
</section>

<!-- ---------- Compose Modal ---------- -->
<form method="post" enctype="multipart/form-data" id="composeForm">
  <div class="modal fade" id="addModal" tabindex="-1" role="dialog" aria-labelledby="composeTitle">
    <div class="modal-dialog modal-lg">
      <div class="modal-content" style="max-width: 860px; margin: 0 auto;">
        <div class="modal-header">
          <button aria-label="Close" data-dismiss="modal" class="close" type="button"><span aria-hidden="true">&times;</span></button>
          <h4 class="modal-title" id="composeTitle">
            <span style="display:inline-flex;width:36px;height:36px;border-radius:10px;background:#22c55e1a;align-items:center;justify-content:center;margin-right:8px;">
              <i class="fa fa-edit" style="color:#16a34a;"></i>
            </span>
            <strong><?= e($_data['add_sms']); ?></strong>
          </h4>
        </div>

        <div class="modal-body">
          <div class="grid-2">
            <!-- Left column -->
            <div>
              <div class="form-group">
                <div class="label"><?= e($_data['text_2']); ?> <span class="text-danger">*</span></div>
                <input type="text" class="input" name="title" id="msgTitle" placeholder="Message title" required maxlength="120">
                <div class="counter" id="titleCounter">0 / 120</div>
              </div>

              <div class="form-group">
                <div class="label"><?= e($_data['text_3']); ?> <span class="text-danger">*</span></div>
                <textarea class="textarea" name="message" id="msgBody" rows="7" placeholder="Write your message..." required></textarea>
                <div class="counter" id="bodyCounter">
                  <span id="charCount">0</span> chars •
                  <span id="segmentCount" class="badge">~0 segments</span>
                </div>
              </div>

              <div class="preview" id="livePreview">
                <h5>Live Preview</h5>
                <div style="font-size:13px;color:#111827;margin-bottom:2px;"><strong id="pTitle">—</strong></div>
                <div style="white-space:pre-wrap;color:#334155;" id="pBody">—</div>
              </div>

              <div class="form-group" style="margin-top:10px;">
                <div class="label">Specific Tenant (optional)</div>
                <input type="text" class="input" name="specific_tenant" id="specificTenant" placeholder="Exact tenant name">
                <div class="muted" style="margin-top:6px;">If set, only this tenant will receive the message.</div>
              </div>

              <div class="form-group" style="margin-top:10px;">
                <div class="label">Specific Buyer (optional)</div>
                <input type="text" class="input" name="specific_buyer" id="specificBuyer" placeholder="Exact buyer name">
                <div class="muted" style="margin-top:6px;">If set, only this buyer will receive the message.</div>
              </div>
            </div>

            <!-- Right column -->
            <div>
              <div class="label">Select Recipients</div>
              <label class="toggle" title="Send to all tenants">
                <input type="checkbox" name="recipient_tenants" id="chkTenants"> <span>All Tenants</span>
              </label>
              <label class="toggle" title="Send to current/occupied tenants (optionally filter)">
                <input type="checkbox" id="curChk" name="recipient_current_tenants">
                <span>All Current Tenants</span>
              </label>
              <label class="toggle" title="Send to all buyers">
                <input type="checkbox" name="recipient_buyers" id="chkBuyers"> <span>All Buyers</span>
              </label>
              <label class="toggle" title="Send to all admins">
                <input type="checkbox" name="recipient_admins" id="chkAdmins"> <span>All Admins</span>
              </label>

              <div id="blkDiv" class="form-group" style="display:none;">
                <div class="label">Filter by Block</div>
                <select id="blockSelect" name="block_id" class="select">
                  <option value="0">-- All Blocks --</option>
                  <?php while($b = mysqli_fetch_assoc($blocks_result)): ?>
                    <option value="<?= (int)$b['bid']; ?>"><?= e($b['b_name']); ?></option>
                  <?php endwhile; ?>
                </select>
              </div>

              <div id="unitDiv" class="form-group" style="display:none;">
                <div class="label">Filter by Unit</div>
                <select id="unitSelect" name="specific_unit" class="select">
                  <option value="0">-- All Units --</option>
                </select>
              </div>

              <div class="label" style="margin-top:12px;">Send Via</div>
              <label class="toggle"><input type="checkbox" name="sms" id="chkSMS" checked> <span>SMS</span></label>
              <label class="toggle"><input type="checkbox" name="email" id="chkEmail"> <span>Email</span></label>
              <div class="muted" style="margin-top:8px;">Choose one or both channels.</div>

              <div class="muted" style="margin-top:12px;">
                <span class="chip">Tip</span> Leave the “Specific” fields empty to reach the selected groups.
              </div>
            </div>
          </div>
        </div>

        <div class="modal-footer" style="display:flex;gap:8px;justify-content:flex-end;">
          <button type="submit" id="sendBtn" class="btn btn-success btn-pill">
            <i class="fa fa-paper-plane"></i> <?= e($_data['text_14']); ?>
          </button>
          <button type="button" class="btn btn-danger btn-pill" data-dismiss="modal">
            <i class="fa fa-times"></i> <?= e($_data['text_15']); ?>
          </button>
        </div>
      </div>
    </div>
  </div>
</form>

<!-- ---------- Scripts ---------- -->
<script src="<?= WEB_URL; ?>assets/js/jquery-ui.js"></script>
<link href="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css" rel="stylesheet">
<style>.ui-autocomplete { z-index: 2147483647; }</style>

<script>
  $(function(){
    setTimeout(function(){ $("#me").fadeOut(300); $("#you").fadeOut(300); }, 4000);

    // DataTables for logs
    if ($.fn.DataTable) {
      $('#msgTable').DataTable({
        pageLength: 10,
        order: [[0, 'desc']],
        responsive: true,
        language: {
          search: "Quick Search:",
          searchPlaceholder: "Type to filter…"
        },
        columnDefs: [
          { targets: 2, orderable: false } // message column
        ]
      });
    }

    // Toggle block/unit filters for current tenants
    $('#curChk').on('change', function(){
      const on = this.checked;
      $('#blkDiv, #unitDiv').toggle(on);
      if (!on) { $('#blockSelect').val('0').trigger('change'); $('#unitSelect').val('0'); }
    });

    // Preload units from PHP
    const units = <?php
      $units = mysqli_fetch_all($units_result, MYSQLI_ASSOC);
      echo json_encode($units, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
    ?>;

    // Populate units based on block
    $('#blockSelect').on('change', function(){
      const bid = parseInt(this.value, 10);
      const $u = $('#unitSelect').empty().append('<option value="0">-- All Units --</option>');
      units.forEach(u => {
        const match = bid === 0 || parseInt(u.bid, 10) === bid;
        if (match) $u.append(`<option value="${u.uid}">${u.unit_no}</option>`);
      });
    });

    // Live counters & preview
    const $title = $('#msgTitle');
    const $body  = $('#msgBody');
    const $tCtr  = $('#titleCounter');
    const $cCtr  = $('#charCount');
    const $seg   = $('#segmentCount');
    const $pT    = $('#pTitle');
    const $pB    = $('#pBody');
    const $send  = $('#sendBtn');

    function isUnicode(str){
      for (let i=0; i<str.length; i++){
        if (str.charCodeAt(i) > 127) return true;
      }
      return false;
    }
    function estimateSegments(text){
      const unicode = isUnicode(text);
      const len = text.length;
      let per = unicode ? 70 : 160;
      let concat = unicode ? 67 : 153;
      if (len === 0) return 0;
      if (len <= per) return 1;
      return Math.ceil(len / concat);
    }
    function refreshUI(){
      const t = $title.val() || '';
      const m = $body.val()  || '';
      $tCtr.text(`${t.length} / 120`);
      $cCtr.text(m.length);
      $seg.text(`~${estimateSegments(m)} segments`);
      $pT.text(t || '—');
      $pB.text(m || '—');

      // Basic enable/disable of Send button
      const anyRecipient =
        $('#specificTenant').val().trim() !== '' ||
        $('#specificBuyer').val().trim()  !== '' ||
        $('#chkTenants').is(':checked')   ||
        $('#chkAdmins').is(':checked')    ||
        $('#curChk').is(':checked')       ||
        $('#chkBuyers').is(':checked');

      const anyChannel   = $('#chkSMS').is(':checked') || $('#chkEmail').is(':checked');
      const ok = (t.trim() !== '' && m.trim() !== '' && anyRecipient && anyChannel);
      $send.prop('disabled', !ok);
    }
    $title.on('input', refreshUI);
    $body.on('input', refreshUI);
    $('#specificTenant, #specificBuyer, #chkTenants, #chkAdmins, #curChk, #chkBuyers, #chkSMS, #chkEmail').on('change input', refreshUI);
    refreshUI();

    // Confirm on submit if extremely long SMS
    $('#composeForm').on('submit', function(e){
      const m = $body.val() || '';
      const segs = estimateSegments(m);
      if ($('#chkSMS').is(':checked') && segs > 5) {
        if (!confirm(`This SMS is about ${segs} segments. Send anyway?`)) {
          e.preventDefault();
        }
      }
    });

    // Open modal = focus title after a tick
    $('#addModal').on('shown.bs.modal', function(){ setTimeout(()=>{ $('#msgTitle').focus(); }, 150); });
  });
</script>

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