<?php
require_once __DIR__ . '/../../admin/_nav.php';
$pageTitle  = 'Send SMS';
$sidebarNav = adminNav();
$u = function($p) { return \Core\View::url($p); };
$sent   = array_sum(array_column($logs['data'] ?? [], 'status' === 'sent' ? 'status' : ''));
$totalLogs = $logs['total'] ?? 0;
?>
<div class="page-header">
  <div><h1><i class="bi bi-chat-dots"></i> SMS Center</h1><p>Send messages to groups or individuals</p></div>
  <a href="<?= $u('admin/dashboard') ?>" class="btn btn-secondary"><i class="bi bi-arrow-left"></i> Dashboard</a>
</div>

<div class="grid g2" style="margin-bottom:20px;align-items:start">

  <!-- ── Compose ── -->
  <div class="card">
    <div class="card-header"><h5><i class="bi bi-pencil-square"></i> Compose SMS</h5></div>
    <div class="card-body">
      <form method="POST" action="<?= $u('admin/sms/send') ?>" id="smsForm">
        <?= \Core\View::csrf() ?>

        <!-- Recipient type toggle -->
        <div class="form-group">
          <label>Send To</label>
          <div style="display:flex;gap:8px">
            <label style="display:flex;align-items:center;gap:6px;cursor:pointer;padding:8px 14px;border:2px solid var(--primary);border-radius:8px;font-size:13px;font-weight:500">
              <input type="radio" name="recipient_type" value="group" checked onchange="toggleRecipient(this.value)"> Group
            </label>
            <label style="display:flex;align-items:center;gap:6px;cursor:pointer;padding:8px 14px;border:2px solid var(--border);border-radius:8px;font-size:13px;font-weight:500">
              <input type="radio" name="recipient_type" value="individual" onchange="toggleRecipient(this.value)"> Individual
            </label>
          </div>
        </div>

        <!-- Group options -->
        <div id="groupSection">
          <div class="form-group">
            <label>Select Group *</label>
            <select name="group" id="groupSelect" onchange="onGroupChange(this.value)" required>
              <option value="">— Choose group —</option>
              <optgroup label="Parents">
                <option value="all_parents">All Parents</option>
                <option value="unpaid_parents">Parents with Unpaid Fees</option>
                <option value="custom_class">Parents by Class</option>
                <option value="stream">Parents by Stream</option>
                <?php foreach($groups as $k=>$l): if(str_starts_with($k,'class_')): ?>
                <option value="<?= $k ?>"><?= $l ?></option>
                <?php endif; endforeach; ?>
              </optgroup>
              <optgroup label="Staff">
                <option value="all_teachers">All Teachers</option>
              </optgroup>
              <optgroup label="Students">
                <option value="all_students">All Students (own phones)</option>
              </optgroup>
            </select>
          </div>
          <!-- Class picker -->
          <div class="form-group" id="classPicker" style="display:none">
            <label>Select Class</label>
            <select name="class_id">
              <option value="">— Select Class —</option>
              <?php foreach($classes as $c): ?>
              <option value="<?= $c['id'] ?>"><?= htmlspecialchars($c['name']) ?></option>
              <?php endforeach; ?>
            </select>
          </div>
          <!-- Stream picker -->
          <div class="form-group" id="streamPicker" style="display:none">
            <label>Select Stream</label>
            <select name="stream_id">
              <option value="">— Select Stream —</option>
              <?php foreach($streams as $s): ?>
              <option value="<?= $s['id'] ?>"><?= htmlspecialchars($s['full_name']) ?></option>
              <?php endforeach; ?>
            </select>
          </div>
          <input type="hidden" name="group_label" id="groupLabel">
        </div>

        <!-- Individual phones -->
        <div id="individualSection" style="display:none">
          <div class="form-group">
            <label>Phone Numbers *</label>
            <textarea name="individual_phones" rows="3" placeholder="0712345678, 0723456789&#10;One per line or comma-separated" style="font-family:monospace;font-size:13px"></textarea>
            <small style="color:var(--gray)">Kenyan format: 07xx or +2547xx</small>
          </div>
        </div>

        <!-- Message -->
        <div class="form-group">
          <label>Message *</label>
          <textarea name="message" id="smsMessage" rows="4" maxlength="320" required placeholder="Type your message here..." oninput="updateCount()"></textarea>
          <div style="display:flex;justify-content:space-between;font-size:11px;color:var(--gray);margin-top:4px">
            <span id="charCount">0 / 160 chars (1 SMS)</span>
            <span>Max 320 chars (2 SMS)</span>
          </div>
        </div>

        <button type="submit" class="btn btn-primary" style="width:100%"><i class="bi bi-send"></i> Send SMS</button>
      </form>
    </div>
  </div>

  <!-- ── Stats sidebar ── -->
  <div style="display:flex;flex-direction:column;gap:16px">
    <div class="stat-card" style="">
      <div class="stat-icon si-blue"><i class="bi bi-chat-dots"></i></div>
      <div class="stat-info"><h3><?= number_format($totalLogs) ?></h3><p>Total SMS Sent</p></div>
    </div>
    <div class="card">
      <div class="card-header"><h5><i class="bi bi-info-circle"></i> Quick Tips</h5></div>
      <div class="card-body" style="font-size:13px;line-height:1.8;color:var(--gray)">
        <p><i class="bi bi-check-circle" style="color:var(--success)"></i> <strong>All Parents</strong> — every parent with a phone number</p>
        <p><i class="bi bi-check-circle" style="color:var(--success)"></i> <strong>Unpaid Fees</strong> — parents of students with outstanding balance</p>
        <p><i class="bi bi-check-circle" style="color:var(--success)"></i> <strong>By Stream</strong> — target a specific class stream</p>
        <p><i class="bi bi-check-circle" style="color:var(--success)"></i> <strong>Individual</strong> — paste any phone numbers manually</p>
        <p style="margin-top:8px"><i class="bi bi-exclamation-triangle" style="color:var(--warning)"></i> SMS provider must be configured in <a href="<?= $u('admin/settings?tab=sms') ?>">Settings → SMS</a></p>
      </div>
    </div>
  </div>
</div>

<!-- ── SMS Log ── -->
<div class="card">
  <div class="card-header">
    <h5><i class="bi bi-clock-history"></i> SMS History</h5>
    <span style="font-size:12px;color:var(--gray)"><?= $totalLogs ?> messages sent</span>
  </div>
  <div class="table-wrap"><table>
    <thead><tr><th>Date</th><th>Recipient</th><th>Message</th><th>Status</th><th>Provider</th></tr></thead>
    <tbody>
      <?php foreach($logs['data'] as $log): ?>
      <tr>
        <td style="font-size:12px;white-space:nowrap"><?= date('d M Y H:i', strtotime($log['created_at'])) ?></td>
        <td style="font-size:12px;font-family:monospace"><?= htmlspecialchars($log['recipient']) ?></td>
        <td style="font-size:12px;max-width:250px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap" title="<?= htmlspecialchars($log['message']) ?>"><?= htmlspecialchars($log['message']) ?></td>
        <td><span class="badge <?= $log['status']==='sent'?'badge-success':'badge-danger' ?>"><?= ucfirst($log['status']) ?></span></td>
        <td style="font-size:12px"><?= htmlspecialchars($log['provider'] ?? '—') ?></td>
      </tr>
      <?php endforeach; ?>
      <?php if(empty($logs['data'])): ?>
      <tr><td colspan="6" style="text-align:center;padding:40px;color:var(--gray)"><i class="bi bi-chat-dots" style="font-size:32px;display:block;margin-bottom:8px"></i>No SMS sent yet</td></tr>
      <?php endif; ?>
    </tbody>
  </table></div>
  <div style="padding:14px"><?= \Core\View::paginate($logs, $u('admin/sms')) ?></div>
</div>

<?php $extraScripts = '<script>
function toggleRecipient(val){
  document.getElementById("groupSection").style.display    = val==="group"?"block":"none";
  document.getElementById("individualSection").style.display = val==="individual"?"block":"none";
  document.querySelectorAll("[name=recipient_type]~label, label:has([name=recipient_type])").forEach(function(el){});
  // update border highlight
  document.querySelectorAll("input[name=recipient_type]").forEach(function(r){
    r.closest("label").style.borderColor = r.checked ? "var(--primary)" : "var(--border)";
  });
}
function onGroupChange(val){
  document.getElementById("classPicker").style.display  = val==="custom_class"?"block":"none";
  document.getElementById("streamPicker").style.display = val==="stream"?"block":"none";
  document.getElementById("groupLabel").value = document.getElementById("groupSelect").options[document.getElementById("groupSelect").selectedIndex].text;
}
function updateCount(){
  var len = document.getElementById("smsMessage").value.length;
  var sms = len<=160?1:2;
  document.getElementById("charCount").textContent = len+" / 160 chars ("+sms+" SMS)";
}
</script>'; ?>
