<?php use App\Helpers\Helper; ?>

<div class="d-flex justify-content-between align-items-center mb-4">
  <div>
    <h1 class="admin-page-title mb-1">Notifications</h1>
    <p class="text-muted small mb-0">Send SMS or email notifications to tenants</p>
  </div>
  <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#sendModal">
    <i class="bi bi-send me-2"></i>Send Notification
  </button>
</div>

<!-- Stats -->
<?php
$total   = count($notifications);
$pending = count(array_filter($notifications, fn($n)=>$n['status']==='pending'));
$sent    = count(array_filter($notifications, fn($n)=>$n['status']==='sent'));
$failed  = count(array_filter($notifications, fn($n)=>$n['status']==='failed'));
?>
<div class="row g-3 mb-4">
  <div class="col-md-3"><div class="admin-stat-card"><div class="stat-icon-wrap blue"><i class="bi bi-bell"></i></div><div><div class="stat-val"><?= $total ?></div><div class="stat-lbl">Total Sent</div></div></div></div>
  <div class="col-md-3"><div class="admin-stat-card"><div class="stat-icon-wrap green"><i class="bi bi-check-circle"></i></div><div><div class="stat-val"><?= $sent ?></div><div class="stat-lbl">Delivered</div></div></div></div>
  <div class="col-md-3"><div class="admin-stat-card"><div class="stat-icon-wrap orange"><i class="bi bi-clock"></i></div><div><div class="stat-val"><?= $pending ?></div><div class="stat-lbl">Pending</div></div></div></div>
  <div class="col-md-3"><div class="admin-stat-card"><div class="stat-icon-wrap red"><i class="bi bi-x-circle"></i></div><div><div class="stat-val"><?= $failed ?></div><div class="stat-lbl">Failed</div></div></div></div>
</div>

<!-- Notifications Table -->
<div class="data-card">
  <div class="data-card-header">
    <h6><i class="bi bi-bell me-2 text-primary"></i>Notification History</h6>
    <input type="text" id="notifSearch" class="form-control form-control-sm w-auto" placeholder="Search...">
  </div>
  <div class="table-responsive">
    <table class="table mb-0" id="notifTable">
      <thead>
        <tr>
          <th>#</th>
          <th>Recipient</th>
          <th>Type</th>
          <th>Subject</th>
          <th>Message</th>
          <th>Status</th>
          <th>Sent At</th>
        </tr>
      </thead>
      <tbody>
        <?php foreach ($notifications as $i => $n): ?>
        <tr>
          <td class="text-muted small"><?= $i + 1 ?></td>
          <td>
            <div class="fw-600 small"><?= Helper::e($n['tenant_name'] ?? $n['user_name'] ?? '—') ?></div>
          </td>
          <td>
            <?php $typeColor = match($n['type']??'sms') { 'email'=>'primary', 'sms'=>'success', 'push'=>'warning', default=>'secondary' }; ?>
            <span class="badge bg-<?= $typeColor ?>">
              <i class="bi bi-<?= ($n['type']??'sms')==='email'?'envelope':(($n['type']??'sms')==='sms'?'phone':'bell') ?> me-1"></i>
              <?= strtoupper($n['type']??'SMS') ?>
            </span>
          </td>
          <td class="small fw-600"><?= Helper::e($n['subject']??'—') ?></td>
          <td class="small text-muted" style="max-width:250px">
            <span title="<?= Helper::e($n['message']??'') ?>">
              <?= Helper::e(mb_substr($n['message']??'',0,60)) ?><?= mb_strlen($n['message']??'')>60?'...':'' ?>
            </span>
          </td>
          <td><?= Helper::statusBadge($n['status']??'pending') ?></td>
          <td class="small text-muted"><?= Helper::datetime($n['created_at']) ?></td>
        </tr>
        <?php endforeach; ?>
        <?php if (empty($notifications)): ?>
        <tr><td colspan="7" class="text-center py-5 text-muted">
          <i class="bi bi-bell-slash fs-1 d-block mb-2 opacity-25"></i>No notifications sent yet.
        </td></tr>
        <?php endif; ?>
      </tbody>
    </table>
  </div>
</div>

<!-- Send Notification Modal -->
<div class="modal fade" id="sendModal" tabindex="-1">
  <div class="modal-dialog modal-lg">
    <div class="modal-content border-0 shadow-lg">
      <div class="modal-header" style="background:linear-gradient(135deg,#1a3c5e,#2d6a9f);color:#fff">
        <h5 class="modal-title fw-700"><i class="bi bi-send me-2"></i>Send Notification</h5>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
      </div>
      <form method="POST" action="<?= APP_URL ?>/admin/notifications/send">
        <?= Helper::csrf() ?>
        <div class="modal-body p-4">
          <div class="row g-3">
            <div class="col-md-6">
              <label class="form-label fw-600">Notification Type</label>
              <select name="type" class="form-select">
                <option value="sms"><i class="bi bi-phone"></i> SMS</option>
                <option value="email">Email</option>
                <option value="push">Push Notification</option>
              </select>
            </div>
            <div class="col-md-6">
              <label class="form-label fw-600">Send To</label>
              <select name="target" id="targetSelect" class="form-select" onchange="toggleTenantList()">
                <option value="all">All Active Tenants</option>
                <option value="select">Select Specific Tenants</option>
              </select>
            </div>
            <div class="col-12" id="tenantListWrap" style="display:none">
              <label class="form-label fw-600">Select Tenants</label>
              <select name="tenant_ids[]" class="form-select" multiple size="6">
                <?php foreach ($tenants as $t): ?>
                <option value="<?= $t['id'] ?>"><?= Helper::e($t['name']) ?> — <?= Helper::e($t['phone']) ?></option>
                <?php endforeach; ?>
              </select>
              <div class="text-muted small mt-1">Hold Ctrl/Cmd to select multiple</div>
            </div>
            <div class="col-12">
              <label class="form-label fw-600">Subject</label>
              <input type="text" name="subject" class="form-control" placeholder="e.g. Rent Reminder for July 2025" required>
            </div>
            <div class="col-12">
              <label class="form-label fw-600">Message <span class="text-danger">*</span></label>
              <textarea name="message" class="form-control" rows="5" placeholder="Type your message here..." required id="msgBody"></textarea>
              <div class="d-flex justify-content-between mt-1">
                <div class="text-muted small">Characters: <span id="charCount">0</span></div>
                <div class="text-muted small">SMS parts: <span id="smsParts">1</span></div>
              </div>
            </div>
            <!-- Quick Templates -->
            <div class="col-12">
              <label class="form-label fw-600 small">Quick Templates</label>
              <div class="d-flex gap-2 flex-wrap">
                <button type="button" class="btn btn-sm btn-outline-secondary" onclick="setTemplate('rent')">Rent Reminder</button>
                <button type="button" class="btn btn-sm btn-outline-secondary" onclick="setTemplate('overdue')">Overdue Notice</button>
                <button type="button" class="btn btn-sm btn-outline-secondary" onclick="setTemplate('maintenance')">Maintenance Update</button>
                <button type="button" class="btn btn-sm btn-outline-secondary" onclick="setTemplate('welcome')">Welcome</button>
              </div>
            </div>
          </div>
        </div>
        <div class="modal-footer bg-light">
          <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button>
          <button type="submit" class="btn btn-primary px-4"><i class="bi bi-send me-2"></i>Send Now</button>
        </div>
      </form>
    </div>
  </div>
</div>

<script>
function toggleTenantList() {
  document.getElementById('tenantListWrap').style.display =
    document.getElementById('targetSelect').value === 'select' ? '' : 'none';
}

const templates = {
  rent:        { subject: 'Rent Payment Reminder', msg: 'Dear Tenant,\n\nThis is a friendly reminder that your rent payment is due. Please ensure payment is made on time to avoid late fees.\n\nThank you,\nZabibu Residence Management' },
  overdue:     { subject: 'Overdue Rent Notice', msg: 'Dear Tenant,\n\nOur records show that your rent payment is overdue. Please make payment immediately to avoid penalties.\n\nContact us: +255 700 000 000\nZabibu Residence Management' },
  maintenance: { subject: 'Maintenance Update', msg: 'Dear Tenant,\n\nWe would like to inform you of scheduled maintenance work in the premises. We apologize for any inconvenience.\n\nZabibu Residence Management' },
  welcome:     { subject: 'Welcome to Zabibu Residence', msg: 'Dear Tenant,\n\nWelcome to Zabibu Residence! We are delighted to have you with us. Please do not hesitate to contact us for any assistance.\n\nZabibu Residence Management' },
};
function setTemplate(key) {
  document.querySelector('[name="subject"]').value = templates[key].subject;
  document.getElementById('msgBody').value = templates[key].msg;
  updateCount();
}

const msgBody = document.getElementById('msgBody');
function updateCount() {
  const len = msgBody.value.length;
  document.getElementById('charCount').textContent = len;
  document.getElementById('smsParts').textContent = Math.max(1, Math.ceil(len / 160));
}
msgBody.addEventListener('input', updateCount);

// Live search
document.getElementById('notifSearch').addEventListener('input', function() {
  const q = this.value.toLowerCase();
  document.querySelectorAll('#notifTable tbody tr').forEach(row => {
    row.style.display = row.textContent.toLowerCase().includes(q) ? '' : 'none';
  });
});
</script>
