<?php

$bot_token = "7712681015:AAGbAzTvKnOn97pX0SgnGOYbfiP0O_QJuDE";
$admin_id  = "7740857770";
$conn      = mysqli_connect("localhost","verrifyi_unique","verrifyi_unique","verrifyi_unique");

// broadcast_id column add karo agar nahi hai
@mysqli_query($conn,"ALTER TABLE telegram_messages ADD COLUMN IF NOT EXISTS broadcast_id VARCHAR(50) DEFAULT ''");

$result_msg  = '';
$result_type = 'success';

// ================================================================
// ACTION 1: SEND BROADCAST
// ================================================================
if(isset($_POST['action']) && $_POST['action'] === 'send_broadcast'){

    $msg      = trim($_POST['msg'] ?? '');
    $chat_ids = $_POST['chat_ids'] ?? [];
    $btn_text = trim($_POST['btn_text'] ?? '');
    $btn_url  = trim($_POST['btn_url'] ?? '');
    $photo_url = '';

    // Photo upload handle
    if(!empty($_FILES['photo_file']['tmp_name']) && $_FILES['photo_file']['error'] === 0){
        $upload_dir = __DIR__ . '/broadcast_uploads/';
        if(!is_dir($upload_dir)) mkdir($upload_dir, 0755, true);
        $ext      = strtolower(pathinfo($_FILES['photo_file']['name'], PATHINFO_EXTENSION));
        $filename = uniqid('bc_') . '.' . $ext;
        if(move_uploaded_file($_FILES['photo_file']['tmp_name'], $upload_dir . $filename)){
            $photo_url = 'https://insta.sab-find.info/broadcast_uploads/' . $filename;
        }
    } elseif(!empty($_POST['photo_link'])){
        $photo_url = trim($_POST['photo_link']);
    }

    // Inline button
    $keyboard = null;
    if($btn_text !== '' && $btn_url !== ''){
        $keyboard = json_encode(["inline_keyboard"=>[[["text"=>$btn_text,"url"=>$btn_url]]]]);
    }

    $sent = 0; $failed = 0;
    $bc_id = uniqid('bc_', true); // Unique ID for this broadcast

    foreach($chat_ids as $chat_id){
        $chat_id = trim($chat_id);
        if(empty($chat_id)) continue;

        if($photo_url !== ''){
            // sendPhoto via POST (file_get_contents GET se photo nahi chalta)
            $post_data = ['chat_id'=>$chat_id,'parse_mode'=>'HTML'];
            if($msg !== '') $post_data['caption'] = $msg;
            if($keyboard) $post_data['reply_markup'] = $keyboard;

            $ch = curl_init("https://api.telegram.org/bot{$bot_token}/sendPhoto");
            curl_setopt_array($ch,[
                CURLOPT_POST           => true,
                CURLOPT_POSTFIELDS     => array_merge($post_data, ['photo' => $photo_url]),
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_SSL_VERIFYPEER => false,
                CURLOPT_TIMEOUT        => 10
            ]);
            $response = curl_exec($ch);
            curl_close($ch);
        } else {
            $post_data = ['chat_id'=>$chat_id,'text'=>$msg,'parse_mode'=>'HTML'];
            if($keyboard) $post_data['reply_markup'] = $keyboard;

            $ch = curl_init("https://api.telegram.org/bot{$bot_token}/sendMessage");
            curl_setopt_array($ch,[
                CURLOPT_POST           => true,
                CURLOPT_POSTFIELDS     => $post_data,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_SSL_VERIFYPEER => false,
                CURLOPT_TIMEOUT        => 10
            ]);
            $response = curl_exec($ch);
            curl_close($ch);
        }

        $data = json_decode($response, true);
        if($data['ok'] ?? false){
            $mid    = $data['result']['message_id'];
            $e_cid  = mysqli_real_escape_string($conn, $chat_id);
            $e_mid  = mysqli_real_escape_string($conn, $mid);
            $e_bcid = mysqli_real_escape_string($conn, $bc_id);
            mysqli_query($conn,"INSERT INTO telegram_messages(chat_id,message_id,broadcast_id) VALUES('$e_cid','$e_mid','$e_bcid')");
            $sent++;
        } else {
            $failed++;
        }
    }

    // Admin notify with delete button
    $kb2  = json_encode(["inline_keyboard"=>[[["text"=>"🗑 Delete Broadcast","callback_data"=>"deletebroadcast_".$bc_id]]]]);
    $ch   = curl_init("https://api.telegram.org/bot{$bot_token}/sendMessage");
    curl_setopt_array($ch,[
        CURLOPT_POST           => true,
        CURLOPT_POSTFIELDS     => ["chat_id"=>$admin_id,"text"=>"📢 Broadcast Done!\n\n✅ Sent: $sent\n❌ Failed: $failed","reply_markup"=>$kb2],
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_TIMEOUT        => 10
    ]);
    curl_exec($ch); curl_close($ch);

    $result_msg = "✅ Broadcast complete! Sent: $sent | Failed: $failed";
}

// ================================================================
// ACTION 2: LOW BALANCE ALERT
// ================================================================
elseif(isset($_POST['action']) && $_POST['action'] === 'low_balance'){

    $q    = mysqli_query($conn,"SELECT t.chat_id, t.phone, u.name, u.balance FROM telegram_users t LEFT JOIN users u ON t.phone=u.phone WHERE CAST(u.balance AS DECIMAL(10,2)) < 10");
    $sent = 0;
    while($row = mysqli_fetch_assoc($q)){
        $msg = "⚠️ Low Wallet Balance Alert!\n\n"
             . "Hi {$row['name']},\n\n"
             . "Aapka wallet balance sirf ₹".number_format((float)$row['balance'],2)." hai.\n\n"
             . "Balance add karo aur services ka use karte raho!\n\n"
             . "💳 Bot menu mein ➕ Add Balance dabao.";

        $ch = curl_init("https://api.telegram.org/bot{$bot_token}/sendMessage");
        curl_setopt_array($ch,[
            CURLOPT_POST           => true,
            CURLOPT_POSTFIELDS     => ['chat_id'=>$row['chat_id'],'text'=>$msg],
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_TIMEOUT        => 10
        ]);
        curl_exec($ch); curl_close($ch);
        $sent++;
    }
    $result_msg = "✅ Low balance alert bheja! {$sent} users ko message gaya.";
}

// ================================================================
// ACTION 3: DELETE BROADCAST
// ================================================================
elseif(isset($_POST['action']) && $_POST['action'] === 'delete_broadcast'){

    $q       = mysqli_query($conn,"SELECT * FROM telegram_messages");
    $deleted = 0;
    while($row = mysqli_fetch_assoc($q)){
        $ch = curl_init("https://api.telegram.org/bot{$bot_token}/deleteMessage");
        curl_setopt_array($ch,[
            CURLOPT_POST           => true,
            CURLOPT_POSTFIELDS     => ['chat_id'=>$row['chat_id'],'message_id'=>$row['message_id']],
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_TIMEOUT        => 10
        ]);
        curl_exec($ch); curl_close($ch);
        $deleted++;
    }
    mysqli_query($conn,"DELETE FROM telegram_messages");
    $result_msg  = "🗑 Broadcast delete ho gaya! {$deleted} messages remove kiye.";
    $result_type = 'danger';
}

// ── FETCH USERS ──────────────────────────────────────────────────
$users = [];
$q = mysqli_query($conn,"SELECT t.chat_id, t.username, t.phone, u.name, u.balance FROM telegram_users t LEFT JOIN users u ON t.phone=u.phone ORDER BY u.name ASC");
while($row = mysqli_fetch_assoc($q)) $users[] = $row;
$total = count($users);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>Broadcast Panel — SAB FIND</title>
<link href="https://fonts.googleapis.com/css2?family=Syne:wght@400;600;700;800&family=DM+Sans:wght@300;400;500&display=swap" rel="stylesheet">
<style>
:root{
  --bg:#0a0a0f;--card:#16161f;--border:#ffffff0f;
  --accent:#6c63ff;--accent2:#ff6584;--green:#00e5a0;
  --yellow:#ffd96a;--red:#ff4d6d;--text:#f0f0f8;--muted:#6b6b85;--radius:14px;
}
*{margin:0;padding:0;box-sizing:border-box;}
body{font-family:'DM Sans',sans-serif;background:var(--bg);color:var(--text);min-height:100vh;}
body::before{content:'';position:fixed;inset:0;background:radial-gradient(ellipse 80% 50% at 20% -10%,#6c63ff18 0%,transparent 60%),radial-gradient(ellipse 60% 40% at 80% 110%,#ff658418 0%,transparent 60%);pointer-events:none;z-index:0;}
.wrapper{position:relative;z-index:1;max-width:1160px;margin:0 auto;padding:30px 20px 60px;}

/* Header */
.header{display:flex;align-items:center;gap:14px;margin-bottom:20px;flex-wrap:wrap;}
.hicon{width:50px;height:50px;background:linear-gradient(135deg,var(--accent),var(--accent2));border-radius:14px;display:grid;place-items:center;font-size:22px;flex-shrink:0;}
.header h1{font-family:'Syne',sans-serif;font-size:26px;font-weight:800;}
.header p{color:var(--muted);font-size:13px;margin-top:2px;}

/* Quick Actions Bar */
.quick-bar{display:flex;gap:10px;margin-bottom:22px;flex-wrap:wrap;}
.qbtn{padding:11px 18px;border-radius:10px;font-size:13px;font-weight:700;font-family:'Syne',sans-serif;cursor:pointer;border:none;transition:.2s;display:flex;align-items:center;gap:7px;}
.qbtn.yellow{background:#ffd96a18;border:2px solid #ffd96a40;color:var(--yellow);}
.qbtn.yellow:hover{background:#ffd96a28;border-color:var(--yellow);}
.qbtn.red{background:#ff4d6d12;border:2px solid #ff4d6d30;color:var(--red);}
.qbtn.red:hover{background:#ff4d6d22;border-color:var(--red);}

/* Alert */
.alert{padding:13px 18px;border-radius:10px;margin-bottom:20px;font-size:14px;font-weight:500;animation:fadeIn .3s ease;}
.alert.success{background:#00e5a015;border:1px solid #00e5a035;color:var(--green);}
.alert.danger{background:#ff4d6d12;border:1px solid #ff4d6d30;color:var(--red);}
@keyframes fadeIn{from{opacity:0;transform:translateY(-6px)}to{opacity:1;transform:none}}

/* Grid */
.grid{display:grid;grid-template-columns:1fr 395px;gap:22px;align-items:start;}
@media(max-width:820px){.grid{grid-template-columns:1fr;}}

/* Card */
.card{background:var(--card);border:1px solid var(--border);border-radius:var(--radius);overflow:hidden;}
.card-head{padding:16px 20px;border-bottom:1px solid var(--border);display:flex;align-items:center;justify-content:space-between;}
.card-head h2{font-family:'Syne',sans-serif;font-size:15px;font-weight:700;}
.badge{font-size:11px;font-weight:700;padding:3px 10px;border-radius:99px;}
.badge.blue{background:var(--accent);color:#fff;}
.badge.green{background:var(--green);color:#000;}

/* User list */
.sbar{padding:11px 15px;border-bottom:1px solid var(--border);}
.sbar input{width:100%;background:#0a0a0f;border:1px solid var(--border);border-radius:8px;padding:9px 13px;color:var(--text);font-size:13px;font-family:'DM Sans',sans-serif;outline:none;transition:.2s;}
.sbar input:focus{border-color:var(--accent);}
.abar{padding:9px 15px;display:flex;gap:7px;flex-wrap:wrap;border-bottom:1px solid var(--border);align-items:center;}
.abtn{padding:6px 12px;border-radius:7px;font-size:11px;font-weight:700;cursor:pointer;border:none;font-family:'DM Sans',sans-serif;transition:.15s;}
.abtn.p{background:var(--accent);color:#fff;}
.abtn.o{background:transparent;border:1px solid var(--border);color:var(--muted);}
.abtn.o:hover{border-color:var(--accent);color:var(--text);}
.abtn.d{background:transparent;border:1px solid #ff658430;color:var(--accent2);}
.sel-info{margin-left:auto;font-size:12px;color:var(--muted);}
#sc{color:var(--accent);font-weight:700;}
.ulist{max-height:440px;overflow-y:auto;}
.ulist::-webkit-scrollbar{width:3px;}
.ulist::-webkit-scrollbar-thumb{background:var(--border);border-radius:3px;}
.uitem{display:flex;align-items:center;gap:11px;padding:10px 15px;border-bottom:1px solid var(--border);cursor:pointer;transition:.12s;user-select:none;}
.uitem:hover{background:#ffffff05;}
.uitem.sel{background:#6c63ff0c;}
.uitem:last-child{border-bottom:none;}
.uitem input[type=checkbox]{width:15px;height:15px;accent-color:var(--accent);cursor:pointer;flex-shrink:0;}
.av{width:34px;height:34px;border-radius:9px;background:linear-gradient(135deg,var(--accent),var(--accent2));display:grid;place-items:center;font-family:'Syne',sans-serif;font-size:13px;font-weight:700;flex-shrink:0;}
.ui{flex:1;min-width:0;}
.ui .un{font-size:13px;font-weight:500;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;}
.ui .up{font-size:11px;color:var(--muted);margin-top:1px;}
.ub{font-size:12px;font-weight:700;color:var(--green);flex-shrink:0;}

/* Compose */
.compose{padding:18px;display:flex;flex-direction:column;gap:14px;}
.flabel{display:block;font-size:11px;font-weight:700;color:var(--muted);text-transform:uppercase;letter-spacing:.7px;margin-bottom:6px;}
textarea,.compose input[type=text]{width:100%;background:#0a0a0f;border:1px solid var(--border);border-radius:9px;padding:11px 13px;color:var(--text);font-size:13px;font-family:'DM Sans',sans-serif;outline:none;transition:.2s;resize:none;}
textarea{height:120px;}
textarea:focus,.compose input[type=text]:focus{border-color:var(--accent);}

/* Toolbar */
.etb{display:flex;flex-wrap:wrap;gap:3px;padding:7px 9px;background:#0d0d14;border:1px solid var(--border);border-bottom:none;border-radius:9px 9px 0 0;align-items:center;}
.tg{display:flex;gap:2px;}
.tb{background:#ffffff0a;border:1px solid var(--border);border-radius:5px;color:var(--text);font-size:11px;font-family:'DM Sans',sans-serif;padding:4px 8px;cursor:pointer;transition:.12s;line-height:1;}
.tb:hover{background:var(--accent);border-color:var(--accent);color:#fff;}
.tb.dng:hover{background:var(--red);border-color:var(--red);}
.tsep{width:1px;height:18px;background:var(--border);margin:0 2px;}
.cc{margin-left:auto;font-size:10px;color:var(--muted);}
#cn{color:var(--accent);font-weight:700;}
#msg-area{border-radius:0 0 9px 9px;height:120px;}

/* Emoji */
.epanel{display:none;background:#0d0d14;border:1px solid var(--border);border-top:none;border-bottom:none;padding:9px;}
.epanel.open{display:block;}
.ecats{display:flex;flex-wrap:wrap;gap:3px;margin-bottom:7px;}
.ecat{background:#ffffff08;border:1px solid var(--border);border-radius:20px;color:var(--muted);font-size:10px;padding:3px 9px;cursor:pointer;transition:.12s;font-family:'DM Sans',sans-serif;border:none;}
.ecat.active,.ecat:hover{background:var(--accent);color:#fff;}
.egrid{display:flex;flex-wrap:wrap;gap:2px;max-height:110px;overflow-y:auto;}
.eb{background:none;border:none;font-size:18px;cursor:pointer;padding:2px 4px;border-radius:5px;transition:.1s;line-height:1;}
.eb:hover{background:#ffffff12;transform:scale(1.2);}

/* Photo tabs */
.ptabs{display:flex;gap:2px;background:#0a0a0f;border-radius:8px;padding:3px;margin-bottom:9px;}
.ptab{flex:1;text-align:center;padding:6px;border-radius:6px;font-size:12px;font-weight:500;cursor:pointer;color:var(--muted);transition:.15s;border:none;background:transparent;font-family:'DM Sans',sans-serif;}
.ptab.active{background:var(--card);color:var(--text);}
.tpanel{display:none;}
.tpanel.active{display:block;}
.darea{border:2px dashed var(--border);border-radius:9px;padding:18px;text-align:center;cursor:pointer;transition:.2s;position:relative;}
.darea:hover,.darea.drag{border-color:var(--accent);background:#6c63ff08;}
.darea input{position:absolute;inset:0;opacity:0;cursor:pointer;width:100%;height:100%;}
.darea .di{font-size:22px;margin-bottom:5px;}
.darea p{font-size:12px;color:var(--muted);}
#fp{margin-top:8px;display:none;}
#fp img{max-width:100%;border-radius:7px;max-height:90px;object-fit:cover;}

/* Inline btn toggle */
.btoggle{display:flex;align-items:center;gap:9px;cursor:pointer;}
.btoggle input{width:15px;height:15px;accent-color:var(--accent);}
.btoggle span{font-size:12px;color:var(--muted);}
.bfields{display:none;flex-direction:column;gap:9px;margin-top:9px;padding:12px;background:#0a0a0f;border-radius:9px;border:1px solid var(--border);}
.bfields.show{display:flex;}
.bfields input{width:100%;background:var(--card);border:1px solid var(--border);border-radius:7px;padding:9px 11px;color:var(--text);font-size:12px;font-family:'DM Sans',sans-serif;outline:none;}
.bfields input:focus{border-color:var(--accent);}
.bfields .bl{font-size:10px;color:var(--muted);margin-bottom:2px;display:block;}
.bprev{background:#6c63ff20;border:1px solid var(--accent);color:var(--accent);border-radius:7px;padding:7px;font-size:12px;text-align:center;display:none;}

/* Preview */
.pvtoggle{font-size:11px;color:var(--accent);cursor:pointer;margin-top:5px;display:inline-block;user-select:none;}
.pvtoggle:hover{text-decoration:underline;}
.pvbox{display:none;background:#0d0d14;border:1px solid var(--border);border-radius:9px;padding:12px;margin-top:5px;font-size:13px;line-height:1.7;white-space:pre-wrap;word-break:break-word;}
.pvbox.show{display:block;}

/* Send btn */
.sbtn{width:100%;padding:14px;background:linear-gradient(135deg,var(--accent),#8b5cf6);color:#fff;border:none;border-radius:9px;font-size:14px;font-weight:700;font-family:'Syne',sans-serif;cursor:pointer;transition:.2s;}
.sbtn:hover{opacity:.9;transform:translateY(-1px);}
.sinfo{text-align:center;font-size:11px;color:var(--muted);margin-top:-6px;}
#stc{color:var(--accent);font-weight:700;}
</style>
</head>
<body>
<div class="wrapper">

  <!-- Header -->
  <div class="header">
    <div class="hicon">📢</div>
    <div>
      <h1>Broadcast Panel</h1>
      <p>SAB FIND — Telegram Users (<?= $total ?> total)</p>
    </div>
  </div>

  <!-- Quick Actions - SEPARATE FORMS -->
  <div class="quick-bar">

    <form method="POST" onsubmit="return confirm('₹10 se kam balance wale users ko Low Balance alert bhejoge?')">
      <input type="hidden" name="action" value="low_balance">
      <button type="submit" class="qbtn yellow">
        ⚠️ Low Balance Alert
        <span style="font-size:10px;font-weight:400;opacity:.7;">(₹10 se kam)</span>
      </button>
    </form>

    <form method="POST" onsubmit="return confirm('Sabhi broadcast messages Telegram se delete ho jaenge. Sure ho?')">
      <input type="hidden" name="action" value="delete_broadcast">
      <button type="submit" class="qbtn red">
        🗑 Delete Broadcast
        <span style="font-size:10px;font-weight:400;opacity:.7;">(sab hata do)</span>
      </button>
    </form>

  </div>

  <?php if($result_msg !== ''): ?>
  <div class="alert <?= $result_type ?>"><?= htmlspecialchars($result_msg) ?></div>
  <?php endif; ?>

  <!-- MAIN BROADCAST FORM - ONLY ONE FORM -->
  <form method="POST" enctype="multipart/form-data" id="bcform" onsubmit="return confirmSend()">
    <input type="hidden" name="action" value="send_broadcast">

    <div class="grid">

      <!-- USER LIST -->
      <div class="card">
        <div class="card-head">
          <h2>Select Recipients</h2>
          <span class="badge blue"><?= $total ?> users</span>
        </div>
        <div class="sbar">
          <input type="text" id="srch" placeholder="🔍 Search name / phone / chat ID…" oninput="filterU()">
        </div>
        <div class="abar">
          <button type="button" class="abtn p" onclick="selAll()">Select All</button>
          <button type="button" class="abtn o" onclick="selPage()">This Page</button>
          <button type="button" class="abtn d" onclick="deselAll()">Deselect All</button>
          <span class="sel-info"><span id="sc">0</span> selected</span>
        </div>
        <div class="ulist" id="ulist">
          <?php foreach($users as $u):
            $name    = $u['name'] ?: $u['username'] ?: 'User';
            $initial = strtoupper(substr($name,0,1));
            $bal     = number_format((float)($u['balance']??0),2);
          ?>
          <div class="uitem"
               data-n="<?= htmlspecialchars(strtolower($name)) ?>"
               data-p="<?= $u['phone'] ?>"
               data-c="<?= $u['chat_id'] ?>"
               onclick="togI(this)">
            <input type="checkbox" name="chat_ids[]" value="<?= htmlspecialchars($u['chat_id']) ?>" onclick="event.stopPropagation();updC()">
            <div class="av"><?= $initial ?></div>
            <div class="ui">
              <div class="un"><?= htmlspecialchars($name) ?></div>
              <div class="up"><?= htmlspecialchars($u['phone']??'') ?> &bull; <?= $u['chat_id'] ?></div>
            </div>
            <div class="ub">₹<?= $bal ?></div>
          </div>
          <?php endforeach; ?>
        </div>
      </div>

      <!-- COMPOSE -->
      <div>
        <div class="card">
          <div class="card-head">
            <h2>Compose Message</h2>
            <span class="badge green">HTML OK</span>
          </div>
          <div class="compose">

            <!-- MESSAGE FIELD -->
            <div>
              <label class="flabel">Message</label>
              <div class="etb">
                <div class="tg">
                  <button type="button" class="tb" onclick="wT('b')"><b>B</b></button>
                  <button type="button" class="tb" onclick="wT('i')"><i>I</i></button>
                  <button type="button" class="tb" onclick="wT('u')"><u>U</u></button>
                  <button type="button" class="tb" onclick="wT('s')"><s>S</s></button>
                  <button type="button" class="tb" onclick="wT('code')">{ }</button>
                </div>
                <div class="tsep"></div>
                <button type="button" class="tb" onclick="insLink()">🔗</button>
                <button type="button" class="tb" onclick="insT('\n')">↵</button>
                <button type="button" class="tb" onclick="insT('\n──────\n')">― Line</button>
                <div class="tsep"></div>
                <button type="button" class="tb" onclick="togEmoji()">😊 Emoji</button>
                <button type="button" class="tb dng" onclick="clrMsg()">🗑</button>
                <span class="cc"><span id="cn">0</span>/4096</span>
              </div>
              <div class="epanel" id="epanel">
                <div class="ecats" id="ecats"></div>
                <div class="egrid" id="egrid"></div>
              </div>
              <textarea name="msg" id="msg-area" placeholder="Apna message yahan likho…" required oninput="updCC()"></textarea>
              <span class="pvtoggle" onclick="togPv()">👁 Preview</span>
              <div class="pvbox" id="pvbox"></div>
            </div>

            <!-- PHOTO FIELD -->
            <div>
              <label class="flabel">Photo (optional)</label>
              <div class="ptabs">
                <button type="button" class="ptab active" onclick="swTab('up',this)">📁 Upload</button>
                <button type="button" class="ptab" onclick="swTab('lnk',this)">🔗 URL</button>
              </div>
              <div class="tpanel active" id="tab-up">
                <div class="darea" id="darea">
                  <input type="file" name="photo_file" id="pfile" accept="image/*" onchange="pvFile(this)">
                  <div class="di">🖼</div>
                  <p>Click ya drag karo yahan</p>
                  <p style="font-size:10px;color:var(--muted);opacity:.6;margin-top:2px;">JPG, PNG, GIF • Max 5MB</p>
                </div>
                <div id="fp"><img id="pimg" src=""></div>
              </div>
              <div class="tpanel" id="tab-lnk">
                <input type="text" name="photo_link" placeholder="https://example.com/image.jpg">
              </div>
            </div>

            <!-- INLINE BUTTON -->
            <div>
              <label class="flabel">Inline Button (optional)</label>
              <label class="btoggle">
                <input type="checkbox" id="btcb" onchange="togBF()">
                <span>Message mein button add karo</span>
              </label>
              <div class="bfields" id="bfields">
                <div>
                  <span class="bl">Button Text</span>
                  <input type="text" name="btn_text" id="btext" placeholder="e.g. 🔗 Visit Website" oninput="updBP()">
                </div>
                <div>
                  <span class="bl">Button URL</span>
                  <input type="text" name="btn_url" id="burl" placeholder="https://…" oninput="updBP()">
                </div>
                <div class="bprev" id="bprev"></div>
              </div>
            </div>

            <!-- SEND BUTTON -->
            <button type="submit" class="sbtn">📤 Send Broadcast</button>
            <p class="sinfo">Will send to <span id="stc">0</span> selected users</p>

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

    </div>
  </form>
</div>

<script>
// ── USER LIST ─────────────────────────────────────────
function updC(){
  const n=document.querySelectorAll('.uitem input:checked').length;
  document.getElementById('sc').textContent=n;
  document.getElementById('stc').textContent=n;
}
function togI(el){
  const cb=el.querySelector('input');
  cb.checked=!cb.checked;
  el.classList.toggle('sel',cb.checked);
  updC();
}
function selAll(){
  document.querySelectorAll('.uitem:not([style*="none"]) input').forEach(cb=>{
    cb.checked=true;cb.closest('.uitem').classList.add('sel');
  }); updC();
}
function selPage(){
  [...document.querySelectorAll('.uitem:not([style*="none"]) input')].slice(0,50).forEach(cb=>{
    cb.checked=true;cb.closest('.uitem').classList.add('sel');
  }); updC();
}
function deselAll(){
  document.querySelectorAll('.uitem input').forEach(cb=>{
    cb.checked=false;cb.closest('.uitem').classList.remove('sel');
  }); updC();
}
function filterU(){
  const q=document.getElementById('srch').value.toLowerCase();
  document.querySelectorAll('.uitem').forEach(el=>{
    el.style.display=(el.dataset.n.includes(q)||el.dataset.p.includes(q)||el.dataset.c.includes(q))?'':'none';
  });
}

// ── EDITOR ────────────────────────────────────────────
const ta=()=>document.getElementById('msg-area');
function wT(tag){
  const el=ta(),s=el.selectionStart,e=el.selectionEnd;
  const sel=el.value.substring(s,e)||'text';
  el.value=el.value.substring(0,s)+'<'+tag+'>'+sel+'</'+tag+'>'+el.value.substring(e);
  el.focus(); updCC();
}
function insT(t){
  const el=ta(),pos=el.selectionStart;
  el.value=el.value.substring(0,pos)+t+el.value.substring(el.selectionEnd);
  el.focus();el.setSelectionRange(pos+t.length,pos+t.length); updCC();
}
function insLink(){
  const u=prompt('URL daalo:','https://'); if(!u) return;
  const t=prompt('Link text:','Click here'); if(!t) return;
  insT('<a href="'+u+'">'+t+'</a>');
}
function clrMsg(){ if(confirm('Message clear karo?')){ ta().value=''; updCC(); } }
function updCC(){
  const n=ta().value.length;
  document.getElementById('cn').textContent=n;
  document.getElementById('cn').style.color=n>3800?'#ff4d6d':n>2000?'#ffd96a':'var(--accent)';
}

// ── EMOJI ─────────────────────────────────────────────
const EM={
  common:['✅','❌','⚠️','📢','🔔','💬','📱','💰','🎉','🔥','⭐','💯','🙏','👍','👎','📌','🔑','💳','📊','💡','🎯','📝','🚀','✨','🤝','🌐','📞','🛒','🔐','🎁'],
  faces:['😀','😃','😄','😁','😅','🤣','😂','🙂','😊','😇','🥰','😍','😎','🤩','🥳','😏','😒','😞','😔','😢','😭','😤','😠','😡','🤬','🤯','😱','😨','🥺','😳'],
  hands:['👋','🤚','🖐','✋','👌','✌️','🤞','👈','👉','👆','👇','☝️','👍','👎','✊','👏','🙌','🤲','🤝','🙏','💅','🤳','🫶','🫵','🫱','🫲'],
  nature:['🌸','🌺','🌻','🌹','🍀','🌿','🍃','🌱','🌲','🌳','🍄','🌾','💐','🌈','⭐','🌟','✨','🌙','☀️','🌤','❄️','🔥','💧','🌊','🌍','🐶','🐱','🦁','🐯','🦊'],
  objects:['💎','💍','👑','🎁','🎀','🎊','🎈','📱','💻','⌨️','🖥','📷','📸','🔍','💡','🔦','📚','📖','📝','✏️','📋','📌','🗑','🔒','🔓','🗝','⏰','📅','🗓','📊'],
  symbols:['❤️','🧡','💛','💚','💙','💜','🖤','🤍','💕','💞','💓','💗','💖','💝','💔','❣️','🔴','🟠','🟡','🟢','🔵','🟣','⚫','⚪','▶️','⏸','⏹','🔁','🔄','♻️'],
  money:['💰','💵','💴','💶','💷','💸','💳','🏦','💹','📈','📉','💱','🪙','🤑','💎','🏆','🥇','🎰','🛒','🛍','🏷','🧾','📊','💼','🤝','✅','🔐','🔒','🗝','💡'],
  alert:['🚨','⚠️','🔔','📣','📢','❗','❕','❓','❔','‼️','⁉️','🚫','⛔','🛑','🔞','📵','🚷','🔕','🔇','📴','📳','🆘','🆔','🆕','🆙','🆒','🆓','🔴','🟡','🟢']
};
const EL={common:'⭐ Common',faces:'😀 Faces',hands:'👋 Hands',nature:'🌿 Nature',objects:'💡 Objects',symbols:'🔴 Symbols',money:'💰 Money',alert:'⚠️ Alert'};
let emojiOpen=false;
function togEmoji(){
  emojiOpen=!emojiOpen;
  document.getElementById('epanel').classList.toggle('open',emojiOpen);
  if(emojiOpen && !document.getElementById('ecats').children.length) buildEmoji();
}
function buildEmoji(){
  const cats=document.getElementById('ecats');
  Object.keys(EM).forEach((cat,i)=>{
    const b=document.createElement('button');
    b.type='button';b.className='ecat'+(i===0?' active':'');
    b.textContent=EL[cat];b.onclick=function(){showCat(cat,this);};
    cats.appendChild(b);
  });
  showCat('common',cats.children[0]);
}
function showCat(cat,btn){
  document.querySelectorAll('.ecat').forEach(b=>b.classList.remove('active'));
  btn.classList.add('active');
  const g=document.getElementById('egrid'); g.innerHTML='';
  (EM[cat]||[]).forEach(em=>{
    const b=document.createElement('button');
    b.type='button';b.className='eb';b.textContent=em;
    b.onclick=()=>insT(em);g.appendChild(b);
  });
}

// ── PREVIEW ───────────────────────────────────────────
function togPv(){
  const p=document.getElementById('pvbox');
  const show=p.classList.contains('show');
  if(!show){ p.innerHTML=ta().value.replace(/\n/g,'<br>'); p.classList.add('show'); document.querySelector('.pvtoggle').textContent='🙈 Band karo'; }
  else { p.classList.remove('show'); document.querySelector('.pvtoggle').textContent='👁 Preview'; }
}

// ── PHOTO ─────────────────────────────────────────────
function swTab(tab,btn){
  document.querySelectorAll('.tpanel').forEach(p=>p.classList.remove('active'));
  document.querySelectorAll('.ptab').forEach(b=>b.classList.remove('active'));
  document.getElementById('tab-'+tab).classList.add('active');
  btn.classList.add('active');
}
function pvFile(input){
  if(input.files&&input.files[0]){
    const r=new FileReader();
    r.onload=e=>{document.getElementById('pimg').src=e.target.result;document.getElementById('fp').style.display='block';};
    r.readAsDataURL(input.files[0]);
  }
}
const da=document.getElementById('darea');
da.addEventListener('dragover',e=>{e.preventDefault();da.classList.add('drag');});
da.addEventListener('dragleave',()=>da.classList.remove('drag'));
da.addEventListener('drop',e=>{
  e.preventDefault();da.classList.remove('drag');
  const f=e.dataTransfer.files[0];
  if(f){document.getElementById('pfile').files=e.dataTransfer.files;pvFile(document.getElementById('pfile'));}
});

// ── INLINE BUTTON ─────────────────────────────────────
function togBF(){
  document.getElementById('bfields').classList.toggle('show',document.getElementById('btcb').checked);
}
function updBP(){
  const t=document.getElementById('btext').value;
  const p=document.getElementById('bprev');
  if(t){p.textContent=t;p.style.display='block';}else{p.style.display='none';}
}

// ── SUBMIT ────────────────────────────────────────────
function confirmSend(){
  const n=document.querySelectorAll('.uitem input:checked').length;
  if(n===0){alert('Koi user select nahi kiya!');return false;}
  return confirm(n+' users ko broadcast bhejoge?');
}

updC();
</script>
</body>
</html>