<?php
session_start();
$config_file = __DIR__ . '/../config.json';
$users_file  = __DIR__ . '/../users.json';
$log_file    = __DIR__ . '/../log.txt';

$config = file_exists($config_file) ? json_decode(file_get_contents($config_file), true) : [];
if (!is_array($config)) $config = [];
foreach (['videos','apks','extra_files'] as $k) { if(!isset($config[$k])) $config[$k]=[]; }

// ─── Helpers ────────────────────────────────────────────
function saveConfig(&$c,$f){ file_put_contents($f,json_encode($c,JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE)); }
function tgAPI($tok,$method,$params=[]){
    $ch=curl_init("https://api.telegram.org/bot{$tok}/{$method}");
    curl_setopt_array($ch,[CURLOPT_POST=>true,CURLOPT_POSTFIELDS=>json_encode($params),
        CURLOPT_HTTPHEADER=>['Content-Type: application/json'],CURLOPT_RETURNTRANSFER=>true,CURLOPT_TIMEOUT=>15]);
    $r=curl_exec($ch);curl_close($ch);return json_decode($r,true);
}
function sizeStr($p){ if(!$p||!file_exists($p))return '?'; $b=filesize($p); return $b>1048576?round($b/1048576,1).'MB':round($b/1024,0).'KB'; }
function getTypeByExt($e){
    return ['mp4'=>'video','mov'=>'video','avi'=>'video','webm'=>'video','mkv'=>'video',
            'jpg'=>'photo','jpeg'=>'photo','png'=>'photo','gif'=>'photo','webp'=>'photo',
            'mp3'=>'audio','ogg'=>'audio','wav'=>'audio','m4a'=>'audio'][$e]??'document';
}
function typeIcon($t){ return ['video'=>'🎬','photo'=>'🖼️','audio'=>'🎵','document'=>'📄','apk'=>'📱'][$t]??'📄'; }
function redirect($url){ header("Location: $url"); exit; }

// ─── Login ───────────────────────────────────────────────
if (!isset($_SESSION['admin_in'])) {
    if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['login'])) {
        if ($_POST['u']===$config['admin_username'] && $_POST['p']===$config['admin_password']) {
            $_SESSION['admin_in']=true; redirect('index.php');
        } else { $loginErr='ভুল Username বা Password!'; }
    }
    renderLogin($loginErr??''); exit;
}
if (isset($_GET['logout'])){ session_destroy(); redirect('index.php'); }

$msg=''; $msgType='';
$page = $_GET['page'] ?? 'dashboard';

// ─── AJAX: inline save single field ──────────────────────
if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['ajax_field'])) {
    header('Content-Type: application/json');
    $field = $_POST['ajax_field'];
    $value = $_POST['ajax_value'] ?? '';
    $allowed = ['bot_token','group_link','domain','welcome_caption','welcome_text',
                'welcome_video_url','admin_password','admin_username'];
    if (in_array($field, $allowed)) {
        $config[$field] = trim($value);
        if ($field==='bot_token'||$field==='domain'||$field==='group_link') {
            $config['welcome_video_file_id']=''; // reset cache on token change
        }
        saveConfig($config, $config_file);
        echo json_encode(['ok'=>true,'msg'=>'✅ সেভ হয়েছে']);
    } else {
        echo json_encode(['ok'=>false,'msg'=>'Invalid field']);
    }
    exit;
}

// ─── AJAX: toggle ──────────────────────────────────────
if (isset($_GET['ajax_toggle'])) {
    header('Content-Type: application/json');
    $field = $_GET['ajax_toggle'];
    if (in_array($field,['auto_approve','send_to_private','send_to_group'])) {
        $config[$field] = !($config[$field]??false);
        saveConfig($config,$config_file);
        echo json_encode(['ok'=>true,'state'=>$config[$field]]);
    }
    exit;
}

// ─── Delete items ───────────────────────────────────────
foreach (['del_video'=>'videos','del_apk'=>'apks','del_file'=>'extra_files'] as $param=>$arr) {
    if (isset($_GET[$param])) {
        $idx=(int)$_GET[$param];
        if (isset($config[$arr][$idx])) {
            $p=$config[$arr][$idx]['path']??'';
            if ($p&&file_exists($p)) @unlink($p);
            array_splice($config[$arr],$idx,1);
            saveConfig($config,$config_file);
        }
        redirect("index.php?page={$arr}&ok=ডিলিট সফল"); 
    }
}
// del welcome video
if (isset($_GET['del_welcome_video'])) {
    if (!empty($config['welcome_video_path'])&&file_exists($config['welcome_video_path'])) @unlink($config['welcome_video_path']);
    $config['welcome_video_path']=$config['welcome_video_filename']=$config['welcome_video_file_id']='';
    saveConfig($config,$config_file);
    redirect('index.php?page=settings&ok=ভিডিও ডিলিট হয়েছে');
}

// ─── Toggle items ────────────────────────────────────────
foreach (['toggle_video'=>'videos','toggle_apk'=>'apks','toggle_file'=>'extra_files'] as $param=>$arr) {
    if (isset($_GET[$param])) {
        $idx=(int)$_GET[$param];
        if (isset($config[$arr][$idx])) {
            $config[$arr][$idx]['enabled']=!($config[$arr][$idx]['enabled']??true);
            saveConfig($config,$config_file);
        }
        redirect("index.php?page={$arr}");
    }
}

// ─── Clear video cache ───────────────────────────────────
if (isset($_GET['clear_vid_cache'])) {
    $config['welcome_video_file_id']=''; saveConfig($config,$config_file);
    redirect('index.php?page=settings&ok=Video cache clear হয়েছে');
}

// ─── Upload helpers ──────────────────────────────────────
function phpUploadErr($code) {
    $e = [
        UPLOAD_ERR_INI_SIZE   => 'ফাইল php.ini limit-এর চেয়ে বড় (.htaccess বা .user.ini দিয়ে বাড়ান)',
        UPLOAD_ERR_FORM_SIZE  => 'ফাইল form limit-এর চেয়ে বড়',
        UPLOAD_ERR_PARTIAL    => 'ফাইল আংশিক আপলোড হয়েছে, আবার চেষ্টা করুন',
        UPLOAD_ERR_NO_FILE    => 'কোনো ফাইল সিলেক্ট করা হয়নি',
        UPLOAD_ERR_NO_TMP_DIR => 'সার্ভারে tmp ফোল্ডার নেই',
        UPLOAD_ERR_CANT_WRITE => 'সার্ভারে ডিস্ক লেখা যাচ্ছে না',
        UPLOAD_ERR_EXTENSION  => 'PHP extension ফাইল block করেছে',
    ];
    return $e[$code] ?? "অজানা error (code: $code)";
}
function ensureDir($dir) {
    if (!file_exists($dir)) { @mkdir($dir, 0755, true); }
    if (!file_exists($dir)) { return false; }
    @chmod($dir, 0755);
    return is_writable($dir);
}
function safeFilename($orig) {
    return time().'_'.preg_replace('/[^a-zA-Z0-9._-]/', '_', $orig);
}

// ─── Upload welcome video ────────────────────────────────
if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['save_welcome_video'])) {
    $fkey = 'welcome_video';
    if (empty($_FILES[$fkey]['name'])) {
        redirect('index.php?page=settings&err=কোনো ভিডিও সিলেক্ট করা হয়নি');
    }
    if ($_FILES[$fkey]['error'] !== UPLOAD_ERR_OK) {
        redirect('index.php?page=settings&err='.urlencode(phpUploadErr($_FILES[$fkey]['error'])));
    }
    $dir = __DIR__.'/../uploads/videos/';
    if (!ensureDir($dir)) redirect('index.php?page=settings&err=uploads/videos/ ফোল্ডার তৈরি হয়নি — setup.php রান করুন');
    $ext = strtolower(pathinfo($_FILES[$fkey]['name'], PATHINFO_EXTENSION));
    if (!in_array($ext, ['mp4','mov','avi','mkv','webm','3gp'])) redirect('index.php?page=settings&err=এই video format সাপোর্টেড না');
    $nm   = 'welcome_'.time().'.'.$ext;
    $dest = $dir.$nm;
    if (!move_uploaded_file($_FILES[$fkey]['tmp_name'], $dest)) redirect('index.php?page=settings&err=ফাইল সরানো যায়নি — folder permission 755 দিন');
    if (!empty($config['welcome_video_path']) && file_exists($config['welcome_video_path'])) @unlink($config['welcome_video_path']);
    $config['welcome_video_path']=$dest; $config['welcome_video_filename']=$nm; $config['welcome_video_file_id']='';
    saveConfig($config,$config_file);
    redirect('index.php?page=settings&ok=✅ Welcome ভিডিও আপলোড সফল!');
}

// ─── Upload extra video ──────────────────────────────────
if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['upload_video'])) {
    if (empty($_FILES['vfile']['name'])) redirect('index.php?page=videos&err=কোনো ভিডিও সিলেক্ট করা হয়নি');
    if ($_FILES['vfile']['error'] !== UPLOAD_ERR_OK) redirect('index.php?page=videos&err='.urlencode(phpUploadErr($_FILES['vfile']['error'])));
    $dir = __DIR__.'/../uploads/videos/';
    if (!ensureDir($dir)) redirect('index.php?page=videos&err=uploads/videos/ ফোল্ডার তৈরি হয়নি — setup.php রান করুন');
    $orig = $_FILES['vfile']['name'];
    $ext  = strtolower(pathinfo($orig, PATHINFO_EXTENSION));
    if (!in_array($ext, ['mp4','mov','avi','mkv','webm','3gp'])) redirect('index.php?page=videos&err=এই video format সাপোর্টেড না');
    $dest = $dir.safeFilename($orig);
    if (!move_uploaded_file($_FILES['vfile']['tmp_name'], $dest)) redirect('index.php?page=videos&err=ফাইল সরানো যায়নি — folder permission 755 দিন');
    $config['videos'][]=['name'=>$orig,'path'=>$dest,'caption'=>trim($_POST['vcap']??''),'file_id'=>'','enabled'=>true];
    saveConfig($config,$config_file);
    redirect('index.php?page=videos&ok='.urlencode("✅ {$orig} আপলোড হয়েছে!"));
}

// ─── Upload APK ──────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['upload_apk'])) {
    if (empty($_FILES['apkfile']['name'])) redirect('index.php?page=apks&err=কোনো APK সিলেক্ট করা হয়নি');
    if ($_FILES['apkfile']['error'] !== UPLOAD_ERR_OK) redirect('index.php?page=apks&err='.urlencode(phpUploadErr($_FILES['apkfile']['error'])));
    $dir = __DIR__.'/../uploads/apks/';
    if (!ensureDir($dir)) redirect('index.php?page=apks&err=uploads/apks/ ফোল্ডার তৈরি হয়নি — setup.php রান করুন');
    $orig = $_FILES['apkfile']['name'];
    $dest = $dir.safeFilename($orig);
    if (!move_uploaded_file($_FILES['apkfile']['tmp_name'], $dest)) redirect('index.php?page=apks&err=ফাইল সরানো যায়নি — folder permission 755 দিন');
    $config['apks'][]=['name'=>$orig,'path'=>$dest,'caption'=>trim($_POST['acap']??''),'file_id'=>'','enabled'=>true];
    saveConfig($config,$config_file);
    redirect('index.php?page=apks&ok='.urlencode("✅ {$orig} আপলোড হয়েছে!"));
}

// ─── Upload other file ───────────────────────────────────
if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['upload_file'])) {
    if (empty($_FILES['xfile']['name'])) redirect('index.php?page=extra_files&err=কোনো ফাইল সিলেক্ট করা হয়নি');
    if ($_FILES['xfile']['error'] !== UPLOAD_ERR_OK) redirect('index.php?page=extra_files&err='.urlencode(phpUploadErr($_FILES['xfile']['error'])));
    $dir = __DIR__.'/../uploads/files/';
    if (!ensureDir($dir)) redirect('index.php?page=extra_files&err=uploads/files/ ফোল্ডার তৈরি হয়নি — setup.php রান করুন');
    $orig = $_FILES['xfile']['name'];
    $ext  = strtolower(pathinfo($orig, PATHINFO_EXTENSION));
    $dest = $dir.safeFilename($orig);
    if (!move_uploaded_file($_FILES['xfile']['tmp_name'], $dest)) redirect('index.php?page=extra_files&err=ফাইল সরানো যায়নি — folder permission 755 দিন');
    $config['extra_files'][]=['name'=>$orig,'path'=>$dest,'type'=>getTypeByExt($ext),'caption'=>trim($_POST['fcap']??''),'file_id'=>'','enabled'=>true];
    saveConfig($config,$config_file);
    redirect('index.php?page=extra_files&ok='.urlencode("✅ {$orig} আপলোড হয়েছে!"));
}

// ─── Webhook ─────────────────────────────────────────────
if (isset($_GET['set_webhook'])) {
    $d=$config['domain']??'';
    if ($d) {
        $res=tgAPI($config['bot_token'],'setWebhook',['url'=>"https://{$d}/webhook.php",'allowed_updates'=>['message','chat_join_request']]);
        redirect('index.php?page=webhook&ok='.urlencode($res['ok']?'✅ Webhook সেট হয়েছে!':'❌ '.($res['description']??'Error')));
    } else redirect('index.php?page=settings&err=Domain আগে সেট করুন');
}
// ─── Clear logs ──────────────────────────────────────────
if (isset($_GET['clear_logs'])){ file_put_contents($log_file,''); redirect('index.php?page=logs&ok=Logs clear হয়েছে'); }

// ─── Broadcast ───────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['broadcast'])) {
    $txt=trim($_POST['btext']??'');
    if ($txt && file_exists($users_file)) {
        $users=json_decode(file_get_contents($users_file),true)??[];
        $s=$f=0;
        foreach($users as $u){ $res=tgAPI($config['bot_token'],'sendMessage',['chat_id'=>$u['id'],'text'=>$txt,'parse_mode'=>'HTML']); $res['ok']?$s++:$f++; }
        $msg="📢 ✅ {$s} জন পেয়েছেন, ❌ {$f} জন fail"; $msgType='ok';
    }
}

// ─── Stats ───────────────────────────────────────────────
$users       = file_exists($users_file)?json_decode(file_get_contents($users_file),true):[];
$totalUsers  = count($users);
$logLines    = file_exists($log_file)?count(array_filter(explode("\n",file_get_contents($log_file)))):0;
if (isset($_GET['ok'])){ $msg=$_GET['ok']; $msgType='ok'; }
if (isset($_GET['err'])){ $msg=$_GET['err']; $msgType='err'; }

// ═══════════════════════════════════════════════════════════
// LOGIN PAGE
// ═══════════════════════════════════════════════════════════
function renderLogin($err) { ?>
<!DOCTYPE html><html lang="bn"><head>
<meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Bot Admin</title>
<link href="https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@400;500;600;700&family=Hind+Siliguri:wght@400;500;600&display=swap" rel="stylesheet">
<style>
*{margin:0;padding:0;box-sizing:border-box}
body{font-family:'Hind Siliguri',sans-serif;background:#080818;min-height:100vh;display:flex;align-items:center;justify-content:center;overflow:hidden}
.bg{position:fixed;inset:0}
.bg-grid{position:absolute;inset:0;background-image:linear-gradient(rgba(99,102,241,.05)1px,transparent 1px),linear-gradient(90deg,rgba(99,102,241,.05)1px,transparent 1px);background-size:40px 40px}
.blob{position:absolute;border-radius:50%;filter:blur(90px)}
.b1{width:600px;height:600px;background:rgba(99,102,241,.12);top:-200px;left:-100px;animation:fl 9s ease-in-out infinite}
.b2{width:500px;height:500px;background:rgba(168,85,247,.1);bottom:-150px;right:-100px;animation:fl 12s ease-in-out infinite reverse}
@keyframes fl{0%,100%{transform:translate(0,0) scale(1)}50%{transform:translate(40px,20px) scale(1.05)}}
.wrap{position:relative;z-index:10;width:100%;max-width:420px;padding:0 20px}
.card{background:rgba(255,255,255,.04);border:1px solid rgba(255,255,255,.08);border-radius:24px;padding:46px 38px;backdrop-filter:blur(24px)}
.brand{text-align:center;margin-bottom:36px}
.logo{font-size:52px;display:block;margin-bottom:14px}
.brand h1{font-family:'Space Grotesk',sans-serif;font-size:24px;font-weight:700;color:#fff;letter-spacing:.3px}
.brand p{color:#64748b;font-size:13px;margin-top:6px}
.field{margin-bottom:16px}
.field label{display:block;font-size:11px;color:#94a3b8;text-transform:uppercase;letter-spacing:.8px;margin-bottom:7px;font-family:'Space Grotesk',sans-serif}
.field input{width:100%;background:rgba(255,255,255,.06);border:1px solid rgba(255,255,255,.09);border-radius:12px;padding:13px 16px;color:#fff;font-family:'Hind Siliguri',sans-serif;font-size:14px;outline:none;transition:all .3s}
.field input:focus{border-color:#6366f1;box-shadow:0 0 0 3px rgba(99,102,241,.15)}
.btn-login{width:100%;margin-top:8px;background:linear-gradient(135deg,#6366f1,#a855f7);border:none;border-radius:12px;padding:14px;color:#fff;font-family:'Space Grotesk',sans-serif;font-size:15px;font-weight:700;cursor:pointer;transition:all .3s;box-shadow:0 4px 20px rgba(99,102,241,.3);letter-spacing:.3px}
.btn-login:hover{transform:translateY(-2px);box-shadow:0 8px 30px rgba(99,102,241,.45)}
.err{background:rgba(239,68,68,.1);border:1px solid rgba(239,68,68,.25);border-radius:10px;padding:11px;color:#fca5a5;font-size:13px;margin-bottom:18px;text-align:center}
</style></head><body>
<div class="bg"><div class="bg-grid"></div><div class="blob b1"></div><div class="blob b2"></div></div>
<div class="wrap"><div class="card">
  <div class="brand"><span class="logo">🤖</span><h1>BOT ADMIN PANEL</h1><p>Telegram Automation Manager</p></div>
  <?php if($err):?><div class="err">⚠️ <?=htmlspecialchars($err)?></div><?php endif?>
  <form method="POST">
    <div class="field"><label>Username</label><input type="text" name="u" placeholder="admin" required autofocus></div>
    <div class="field"><label>Password</label><input type="password" name="p" placeholder="••••••••" required></div>
    <button type="submit" name="login" class="btn-login">লগইন করুন →</button>
  </form>
</div></div></body></html>
<?php } ?>
<!DOCTYPE html><html lang="bn"><head>
<meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Bot Admin Panel</title>
<link href="https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@400;500;600;700&family=Hind+Siliguri:wght@400;500;600&display=swap" rel="stylesheet">
<style>
*{margin:0;padding:0;box-sizing:border-box}
:root{
  --bg:#07071c;--s1:#0d0d26;--s2:#11112e;--bd:rgba(255,255,255,.07);
  --p:#6366f1;--p2:#a855f7;--p3:#06b6d4;
  --tx:#e2e8f0;--mu:#64748b;--ok:#22c55e;--er:#ef4444;--wa:#f59e0b
}
body{font-family:'Hind Siliguri',sans-serif;background:var(--bg);color:var(--tx);min-height:100vh;display:flex}
a{text-decoration:none;color:inherit}

/* ── SIDEBAR ── */
.sb{width:236px;background:var(--s1);border-right:1px solid var(--bd);position:fixed;height:100vh;display:flex;flex-direction:column;overflow-y:auto;z-index:50}
.sb-top{padding:20px 16px 14px;border-bottom:1px solid var(--bd)}
.sb-brand{display:flex;align-items:center;gap:10px}
.sb-emoji{font-size:28px}
.sb-name{font-family:'Space Grotesk',sans-serif;font-size:15px;font-weight:700;color:#fff}
.sb-tag{font-size:10px;color:var(--mu);margin-top:1px}
.sb-ping{display:flex;align-items:center;gap:6px;margin-top:10px;font-size:11px;color:var(--mu)}
.ping-dot{width:6px;height:6px;border-radius:50%;background:var(--ok);box-shadow:0 0 6px var(--ok);animation:blink 2s infinite}
@keyframes blink{0%,100%{opacity:1}50%{opacity:.4}}
.sb-nav{flex:1;padding:10px 10px}
.sb-sep{font-size:10px;color:var(--mu);text-transform:uppercase;letter-spacing:1.5px;padding:10px 8px 4px;font-family:'Space Grotesk',sans-serif}
.sb-a{display:flex;align-items:center;gap:10px;padding:9px 11px;border-radius:10px;color:var(--mu);font-size:13px;margin-bottom:1px;transition:all .2s;position:relative}
.sb-a:hover{background:rgba(99,102,241,.08);color:var(--p)}
.sb-a.on{background:rgba(99,102,241,.13);color:var(--p);border:1px solid rgba(99,102,241,.18)}
.sb-a.on::before{content:'';position:absolute;left:0;top:50%;transform:translateY(-50%);width:3px;height:55%;background:var(--p);border-radius:0 3px 3px 0}
.sb-ico{font-size:17px;width:20px;text-align:center}
.sb-cnt{margin-left:auto;background:var(--p);color:#fff;font-size:10px;font-weight:700;padding:2px 7px;border-radius:20px;font-family:'Space Grotesk',sans-serif}
.sb-bot{padding:12px 10px;border-top:1px solid var(--bd)}
.sb-out{display:flex;align-items:center;gap:10px;padding:9px 11px;border-radius:10px;color:var(--er);font-size:13px;transition:background .2s;cursor:pointer}
.sb-out:hover{background:rgba(239,68,68,.1)}

/* ── MAIN ── */
.main{margin-left:236px;flex:1;padding:26px;min-height:100vh}
.ph{margin-bottom:22px}
.pt{font-family:'Space Grotesk',sans-serif;font-size:22px;font-weight:700;color:#fff}
.ps{color:var(--mu);font-size:13px;margin-top:4px}

/* ── CARD ── */
.card{background:var(--s1);border:1px solid var(--bd);border-radius:16px;padding:20px;margin-bottom:16px}
.ctitle{font-family:'Space Grotesk',sans-serif;font-size:12px;font-weight:700;color:#fff;text-transform:uppercase;letter-spacing:.6px;margin-bottom:16px;display:flex;align-items:center;gap:7px}
.ctitle .i{font-size:17px}

/* ── STATS ── */
.stats{display:grid;grid-template-columns:repeat(4,1fr);gap:13px;margin-bottom:18px}
.stat{background:var(--s1);border:1px solid var(--bd);border-radius:14px;padding:18px;position:relative;overflow:hidden;transition:transform .2s}
.stat:hover{transform:translateY(-2px)}
.stat::after{content:'';position:absolute;bottom:0;left:0;right:0;height:2px}
.sv{font-family:'Space Grotesk',sans-serif;font-size:30px;font-weight:700;color:#fff;line-height:1.1}
.sl{font-size:12px;color:var(--mu);margin-top:5px}
.si{font-size:24px;margin-bottom:10px}
.s1::after{background:linear-gradient(90deg,var(--p),transparent)}
.s2::after{background:linear-gradient(90deg,var(--p2),transparent)}
.s3::after{background:linear-gradient(90deg,#06b6d4,transparent)}
.s4::after{background:linear-gradient(90deg,var(--wa),transparent)}

/* ── INLINE EDIT FIELD ── */
.ief{background:var(--s2);border:1px solid var(--bd);border-radius:12px;padding:14px 16px;margin-bottom:12px;transition:border-color .3s}
.ief:hover{border-color:rgba(99,102,241,.3)}
.ief-label{font-size:11px;color:var(--mu);text-transform:uppercase;letter-spacing:.6px;margin-bottom:6px;font-family:'Space Grotesk',sans-serif;display:flex;justify-content:space-between;align-items:center}
.ief-row{display:flex;align-items:center;gap:8px}
.ief-row input,.ief-row textarea{flex:1;background:transparent;border:none;color:var(--tx);font-family:'Hind Siliguri',sans-serif;font-size:14px;outline:none;padding:0}
.ief-row textarea{resize:none;line-height:1.5}
.ief-row input[type=password]{letter-spacing:2px}
.ief-btn{background:rgba(99,102,241,.15);border:1px solid rgba(99,102,241,.25);color:var(--p);font-size:11px;font-family:'Space Grotesk',sans-serif;font-weight:600;padding:5px 12px;border-radius:8px;cursor:pointer;white-space:nowrap;transition:all .2s}
.ief-btn:hover{background:rgba(99,102,241,.3)}
.ief-saved{color:var(--ok);font-size:11px;display:none}

/* ── TOGGLE CARDS ── */
.tog-group{display:grid;grid-template-columns:repeat(3,1fr);gap:12px;margin-bottom:0}
.tog-card{background:var(--s2);border:1px solid var(--bd);border-radius:12px;padding:15px;display:flex;flex-direction:column;gap:8px;transition:all .3s;cursor:pointer}
.tog-card.on{border-color:rgba(99,102,241,.35);background:rgba(99,102,241,.06)}
.tog-card-top{display:flex;align-items:center;justify-content:space-between}
.tog-card-icon{font-size:24px}
.mini-tog{width:38px;height:21px;position:relative;flex-shrink:0}
.mini-tog input{opacity:0;width:0;height:0}
.mini-sl{position:absolute;inset:0;background:rgba(255,255,255,.1);border-radius:21px;transition:.3s}
.mini-sl::before{content:'';position:absolute;width:15px;height:15px;left:3px;bottom:3px;background:#fff;border-radius:50%;transition:.3s;box-shadow:0 1px 3px rgba(0,0,0,.4)}
input:checked+.mini-sl{background:linear-gradient(135deg,var(--p),var(--p2))}
input:checked+.mini-sl::before{transform:translateX(17px)}
.tog-card-name{font-size:13px;font-weight:600;color:var(--tx)}
.tog-card-desc{font-size:11px;color:var(--mu)}

/* ── UPLOAD ZONE ── */
.uzone{border:2px dashed var(--bd);border-radius:13px;padding:26px;text-align:center;cursor:pointer;transition:all .3s;position:relative;overflow:hidden}
.uzone:hover,.uzone.drag{border-color:var(--p);background:rgba(99,102,241,.04)}
.uzone input[type=file]{position:absolute;inset:0;opacity:0;cursor:pointer;width:100%;height:100%}
.uz-ico{font-size:38px;margin-bottom:9px;display:block}
.uz-main{font-size:13px;color:var(--tx);margin-bottom:3px}
.uz-main strong{color:var(--p)}
.uz-sub{font-size:11px;color:var(--mu)}

/* ── BUTTONS ── */
.btn{display:inline-flex;align-items:center;gap:6px;padding:9px 18px;border-radius:10px;border:none;font-family:'Space Grotesk',sans-serif;font-size:12px;font-weight:600;cursor:pointer;transition:all .2s;letter-spacing:.3px}
.b-p{background:linear-gradient(135deg,var(--p),var(--p2));color:#fff;box-shadow:0 3px 12px rgba(99,102,241,.25)}
.b-p:hover{transform:translateY(-1px);box-shadow:0 5px 20px rgba(99,102,241,.35)}
.b-g{background:rgba(255,255,255,.06);border:1px solid var(--bd);color:var(--tx)}
.b-g:hover{background:rgba(255,255,255,.1)}
.b-d{background:rgba(239,68,68,.15);border:1px solid rgba(239,68,68,.3);color:#fca5a5;padding:6px 12px;font-size:11px}
.b-d:hover{background:rgba(239,68,68,.3)}
.b-w{background:rgba(245,158,11,.15);border:1px solid rgba(245,158,11,.3);color:#fcd34d;padding:6px 12px;font-size:11px}
.b-cyan{background:rgba(6,182,212,.15);border:1px solid rgba(6,182,212,.3);color:#67e8f9;padding:7px 14px;font-size:11px}
.b-cyan:hover{background:rgba(6,182,212,.25)}

/* ── FORM FIELDS ── */
.fg{margin-bottom:14px}
.fg label{display:block;font-size:11px;color:var(--mu);text-transform:uppercase;letter-spacing:.6px;margin-bottom:7px;font-family:'Space Grotesk',sans-serif}
.fc{width:100%;background:rgba(255,255,255,.05);border:1px solid var(--bd);border-radius:10px;padding:11px 14px;color:var(--tx);font-family:'Hind Siliguri',sans-serif;font-size:13px;outline:none;transition:all .3s}
.fc:focus{border-color:var(--p);box-shadow:0 0 0 3px rgba(99,102,241,.1)}
textarea.fc{resize:vertical;min-height:80px;line-height:1.6}
.fc-hint{font-size:11px;color:var(--mu);margin-top:5px}

/* ── ALERTS ── */
.al{display:flex;align-items:center;gap:9px;padding:11px 15px;border-radius:11px;font-size:13px;margin-bottom:18px;animation:sld .3s ease}
@keyframes sld{from{opacity:0;transform:translateY(-8px)}to{opacity:1;transform:translateY(0)}}
.al-ok {background:rgba(34,197,94,.1); border:1px solid rgba(34,197,94,.2);  color:#86efac}
.al-err{background:rgba(239,68,68,.1); border:1px solid rgba(239,68,68,.2);  color:#fca5a5}
.al-inf{background:rgba(99,102,241,.1);border:1px solid rgba(99,102,241,.2);color:#a5b4fc}

/* ── FILE ITEMS ── */
.fi{background:var(--s2);border:1px solid var(--bd);border-radius:13px;padding:14px 16px;display:flex;align-items:center;gap:12px;margin-bottom:9px;transition:all .2s}
.fi:hover{border-color:rgba(255,255,255,.12);background:rgba(255,255,255,.04)}
.fi-ico{font-size:26px;width:38px;text-align:center;flex-shrink:0}
.fi-info{flex:1;min-width:0}
.fi-name{font-size:13px;font-weight:600;color:#fff;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.fi-meta{font-size:11px;color:var(--mu);margin-top:2px}
.fi-cap{font-size:11px;color:rgba(99,102,241,.8);margin-top:2px}
.fi-act{display:flex;gap:7px;align-items:center;flex-shrink:0}
.badge{display:inline-block;padding:2px 9px;border-radius:20px;font-size:10px;font-weight:700;font-family:'Space Grotesk',sans-serif}
.b-on {background:rgba(34,197,94,.12);color:#86efac}
.b-off{background:rgba(255,255,255,.06);color:var(--mu)}
.b-cach{background:rgba(6,182,212,.1);color:#67e8f9}

/* ── VIDEO PREVIEW ── */
#vPrv video{width:100%;border-radius:10px;max-height:190px;margin-top:10px;border:1px solid var(--bd)}
.cur-vid{background:rgba(6,182,212,.07);border:1px solid rgba(6,182,212,.2);border-radius:10px;padding:12px 15px;display:flex;align-items:center;gap:10px;margin-bottom:12px}

/* ── LOG ── */
.logbox{font-family:monospace;font-size:11px;color:#7dd3fc;line-height:1.85;max-height:500px;overflow-y:auto}
.ll{border-bottom:1px solid rgba(255,255,255,.03);padding:2px 0}
.ll:hover{background:rgba(255,255,255,.02)}
.lt{color:var(--mu)}

/* ── TABLE ── */
.tbl{width:100%;border-collapse:collapse}
.tbl th{font-size:10px;color:var(--mu);text-transform:uppercase;letter-spacing:.8px;padding:9px 12px;text-align:left;border-bottom:1px solid var(--bd);font-family:'Space Grotesk',sans-serif}
.tbl td{font-size:13px;padding:10px 12px;border-bottom:1px solid rgba(255,255,255,.035)}
.tbl tr:hover td{background:rgba(255,255,255,.02)}
.av{width:30px;height:30px;border-radius:50%;background:linear-gradient(135deg,var(--p),var(--p2));display:inline-flex;align-items:center;justify-content:center;font-size:12px;font-weight:700;color:#fff;margin-right:7px;font-family:'Space Grotesk',sans-serif}
.mono-box{font-family:monospace;font-size:12px;color:#7dd3fc;background:rgba(0,0,0,.4);border:1px solid rgba(99,102,241,.2);border-radius:10px;padding:12px 16px;word-break:break-all;margin-bottom:12px}

/* ── STEP ── */
.step{display:flex;align-items:flex-start;gap:13px;padding:13px 0;border-bottom:1px solid var(--bd)}
.step:last-child{border-bottom:none}
.sn{width:26px;height:26px;border-radius:50%;background:linear-gradient(135deg,var(--p),var(--p2));display:flex;align-items:center;justify-content:center;font-size:11px;font-weight:700;color:#fff;flex-shrink:0;font-family:'Space Grotesk',sans-serif}
.st{font-size:13px;color:var(--tx);line-height:1.7}
.st code{color:var(--p3);background:rgba(6,182,212,.1);padding:1px 7px;border-radius:5px;font-size:12px}

/* ── BROADCAST ── */
.bcast{background:rgba(99,102,241,.04);border:1px solid rgba(99,102,241,.12);border-radius:14px;padding:18px;margin-bottom:16px}

/* ── RESPONSIVE ── */
@media(max-width:900px){.sb{display:none}.main{margin-left:0}.stats{grid-template-columns:1fr 1fr}.tog-group{grid-template-columns:1fr}}
@media(max-width:500px){.stats{grid-template-columns:1fr}}
::-webkit-scrollbar{width:5px}::-webkit-scrollbar-track{background:transparent}::-webkit-scrollbar-thumb{background:rgba(255,255,255,.1);border-radius:5px}
</style></head>
<body>

<!-- ═══ SIDEBAR ═══ -->
<nav class="sb">
  <div class="sb-top">
    <div class="sb-brand"><div class="sb-emoji">🤖</div><div><div class="sb-name">BOT PANEL</div><div class="sb-tag">Admin Dashboard v2</div></div></div>
    <div class="sb-ping"><span class="ping-dot"></span><?=htmlspecialchars($config['domain']??'Domain set করুন')?></div>
  </div>
  <div class="sb-nav">
    <div class="sb-sep">মেনু</div>
    <a class="sb-a <?=$page==='dashboard'?'on':''?>" href="?page=dashboard"><span class="sb-ico">📊</span>Dashboard</a>
    <a class="sb-a <?=$page==='settings'?'on':''?>" href="?page=settings"><span class="sb-ico">⚙️</span>Bot সেটিংস</a>
    <div class="sb-sep">ফাইল ম্যানেজার</div>
    <a class="sb-a <?=$page==='videos'?'on':''?>" href="?page=videos"><span class="sb-ico">🎬</span>ভিডিও ফাইল
      <?php $vc=count($config['videos']??[]); if($vc):?><span class="sb-cnt"><?=$vc?></span><?php endif?></a>
    <a class="sb-a <?=$page==='apks'?'on':''?>" href="?page=apks"><span class="sb-ico">📱</span>APK ফাইল
      <?php $ac=count($config['apks']??[]); if($ac):?><span class="sb-cnt"><?=$ac?></span><?php endif?></a>
    <a class="sb-a <?=$page==='extra_files'?'on':''?>" href="?page=extra_files"><span class="sb-ico">📄</span>অন্যান্য ফাইল
      <?php $ec=count($config['extra_files']??[]); if($ec):?><span class="sb-cnt"><?=$ec?></span><?php endif?></a>
    <div class="sb-sep">সিস্টেম</div>
    <a class="sb-a <?=$page==='users'?'on':''?>" href="?page=users"><span class="sb-ico">👥</span>ইউজার লিস্ট
      <?php if($totalUsers):?><span class="sb-cnt"><?=$totalUsers?></span><?php endif?></a>
    <a class="sb-a <?=$page==='broadcast'?'on':''?>" href="?page=broadcast"><span class="sb-ico">📢</span>Broadcast</a>
    <a class="sb-a <?=$page==='webhook'?'on':''?>" href="?page=webhook"><span class="sb-ico">🔗</span>Webhook</a>
    <a class="sb-a <?=$page==='logs'?'on':''?>" href="?page=logs"><span class="sb-ico">📋</span>Logs
      <?php if($logLines):?><span class="sb-cnt"><?=$logLines?></span><?php endif?></a>
  </div>
  <div class="sb-bot"><a class="sb-out" href="?logout=1"><span>🚪</span>লগআউট</a></div>
</nav>

<!-- ═══ MAIN ═══ -->
<main class="main">
<?php if($msg):?>
<div class="al al-<?=$msgType==='ok'?'ok':($msgType==='err'?'err':'inf')?>">
  <?=$msgType==='ok'?'✅':($msgType==='err'?'❌':'ℹ️')?> <?=htmlspecialchars($msg)?>
</div>
<?php endif?>

<!-- ════════ DASHBOARD ════════ -->
<?php if($page==='dashboard'):?>
<div class="ph"><div class="pt">📊 Dashboard</div><div class="ps">Bot-এর সার্বিক অবস্থা একনজরে</div></div>

<div class="stats">
  <div class="stat s1"><div class="si">👥</div><div class="sv"><?=$totalUsers?></div><div class="sl">মোট ইউজার</div></div>
  <div class="stat s2"><div class="si">🎬</div><div class="sv"><?=count($config['videos']??[])?></div><div class="sl">ভিডিও</div></div>
  <div class="stat s3"><div class="si">📱</div><div class="sv"><?=count($config['apks']??[])?></div><div class="sl">APK</div></div>
  <div class="stat s4"><div class="si">📄</div><div class="sv"><?=count($config['extra_files']??[])?></div><div class="sl">অন্য ফাইল</div></div>
</div>

<div style="display:grid;grid-template-columns:1.3fr 1fr;gap:16px">
<div>
<div class="card">
  <div class="ctitle"><span class="i">🤖</span>Bot তথ্য</div>
  <?php $bi=$config['bot_token']?tgAPI($config['bot_token'],'getMe'):null; if(!empty($bi['ok'])): ?>
  <div style="display:flex;align-items:center;gap:14px;margin-bottom:14px;padding:12px;background:var(--s2);border-radius:11px">
    <div style="font-size:42px">🤖</div>
    <div>
      <div style="font-size:15px;font-weight:600;color:#fff"><?=htmlspecialchars($bi['result']['first_name']??'')?></div>
      <div style="font-size:12px;color:var(--p)">@<?=htmlspecialchars($bi['result']['username']??'')?></div>
      <div style="font-size:11px;color:var(--mu)">ID: <?=$bi['result']['id']??''?></div>
    </div>
  </div>
  <?php else: ?><div style="color:var(--er);font-size:13px;padding:10px 0">❌ Bot Token সেট করা নেই</div><?php endif?>
  <div style="font-size:12px;color:var(--mu);line-height:2.1">
    <div>🌐 Domain: <strong style="color:var(--tx)"><?=htmlspecialchars($config['domain']??'—')?></strong></div>
    <div>🔗 Group Link: <?php if(!empty($config['group_link'])):?><a href="<?=htmlspecialchars($config['group_link'])?>" target="_blank" style="color:var(--p3);font-size:11px"><?=htmlspecialchars($config['group_link'])?></a><?php else:?><strong style="color:var(--er)">সেট করা নেই</strong><?php endif?></div>
    <div>✅ Auto Approve: <strong style="color:<?=!empty($config['auto_approve'])?'var(--ok)':'var(--er)'?>"><?=!empty($config['auto_approve'])?'চালু':'বন্ধ'?></strong></div>
    <div>📩 Private DM: <strong style="color:<?=!empty($config['send_to_private'])?'var(--ok)':'var(--er)'?>"><?=!empty($config['send_to_private'])?'চালু':'বন্ধ'?></strong></div>
    <div>📣 Group Send: <strong style="color:<?=!empty($config['send_to_group'])?'var(--ok)':'var(--er)'?>"><?=!empty($config['send_to_group'])?'চালু':'বন্ধ'?></strong></div>
  </div>
</div>
<?php if($totalUsers>0):?>
<div class="card">
  <div class="ctitle"><span class="i">👥</span>সর্বশেষ ৫ জন ইউজার</div>
  <table class="tbl">
    <tr><th>নাম</th><th>Username</th><th>সময়</th></tr>
    <?php foreach(array_slice(array_reverse(array_values($users)),0,5) as $u): ?>
    <tr>
      <td><span class="av"><?=mb_substr($u['first_name'],0,1,'UTF-8')?></span><?=htmlspecialchars(trim(($u['first_name']??'').(' '.($u['last_name']??''))))?></td>
      <td style="color:var(--p)"><?=!empty($u['username'])?'@'.htmlspecialchars($u['username']):'—'?></td>
      <td style="color:var(--mu);font-size:11px"><?=htmlspecialchars($u['joined_at']??'')?></td>
    </tr>
    <?php endforeach?>
  </table>
</div>
<?php endif?>
</div>
<div>
<div class="card">
  <div class="ctitle"><span class="i">⚡</span>দ্রুত কাজ</div>
  <div style="display:flex;flex-direction:column;gap:9px">
    <a href="?page=settings" class="btn b-p" style="justify-content:center">⚙️ Bot Token পরিবর্তন</a>
    <a href="?page=videos" class="btn b-g" style="justify-content:center">🎬 ভিডিও আপলোড</a>
    <a href="?page=apks" class="btn b-g" style="justify-content:center">📱 APK আপলোড</a>
    <a href="?page=broadcast" class="btn b-g" style="justify-content:center">📢 Broadcast পাঠান</a>
    <a href="?page=webhook&set_webhook=1" class="btn b-g" style="justify-content:center">🔗 Webhook সেট করুন</a>
  <div class="card" style="margin-top:0">
  <div class="ctitle"><span class="i">🔍</span>Server Diagnostic</div>
  <?php
  $checks = [
    ['uploads/videos/', 'Video ফোল্ডার'],
    ['uploads/apks/',   'APK ফোল্ডার'],
    ['uploads/files/',  'Files ফোল্ডার'],
  ];
  $allOk = true;
  foreach ($checks as [$rel, $lbl]):
    $path = __DIR__.'/../'.$rel;
    $exists   = file_exists($path);
    $writable = $exists && is_writable($path);
    if (!$writable) $allOk = false;
  ?>
  <div style="display:flex;justify-content:space-between;align-items:center;padding:7px 0;border-bottom:1px solid var(--bd);font-size:12px">
    <span style="color:var(--mu)"><?=$lbl?></span>
    <?php if($writable):?>
      <span style="color:var(--ok)">✅ OK</span>
    <?php elseif($exists):?>
      <span style="color:var(--er)">❌ Not Writable</span>
    <?php else:?>
      <span style="color:var(--er)">❌ নেই</span>
    <?php endif?>
  </div>
  <?php endforeach?>
  <?php
  $ul = ini_get('upload_max_filesize');
  $pm = ini_get('post_max_size');
  ?>
  <div style="display:flex;justify-content:space-between;align-items:center;padding:7px 0;border-bottom:1px solid var(--bd);font-size:12px">
    <span style="color:var(--mu)">upload_max_filesize</span>
    <span style="color:<?=in_array($ul,['512M','256M','128M'])?'var(--ok)':'var(--wa)'?>"><?=$ul?></span>
  </div>
  <div style="display:flex;justify-content:space-between;align-items:center;padding:7px 0;font-size:12px">
    <span style="color:var(--mu)">post_max_size</span>
    <span style="color:<?=in_array($pm,['512M','256M','128M'])?'var(--ok)':'var(--wa)'?>"><?=$pm?></span>
  </div>
  <?php if(!$allOk):?>
  <div style="margin-top:12px">
    <a href="../setup.php" target="_blank" class="btn b-p" style="width:100%;justify-content:center">🔧 setup.php রান করুন (ফোল্ডার তৈরি হবে)</a>
  </div>
  <?php endif?>
</div>
</div>
</div>
</div>

<!-- ════════ SETTINGS ════════ -->
<?php elseif($page==='settings'):?>
<div class="ph"><div class="pt">⚙️ Bot সেটিংস</div><div class="ps">প্রতিটি ঘরের পাশের সেভ বাটনে ক্লিক করলেই সাথে সাথে সেভ হয়ে যাবে</div></div>

<div class="card">
  <div class="ctitle"><span class="i">🔑</span>Bot Configuration</div>
  <?php
  $fields = [
    ['bot_token',   'Bot Token',                   'text', '123456:ABCdef...', false],
    ['group_link',  'Group / Channel লিংক',        'text', 'https://t.me/+xxxxxxxxxxxxxx', false],
    ['domain',      'Domain (Webhook-এর জন্য)',    'text', 'example.com', false],
  ];
  foreach($fields as [$k,$lbl,$type,$ph,$ta]):
  ?>
  <div class="ief" id="ief_<?=$k?>">
    <div class="ief-label">
      <span><?=$lbl?></span>
      <span class="ief-saved" id="saved_<?=$k?>">✓ সেভ হয়েছে</span>
    </div>
    <div class="ief-row">
      <?php if($ta):?>
        <textarea rows="2" id="field_<?=$k?>" placeholder="<?=$ph?>"><?=htmlspecialchars($config[$k]??'')?></textarea>
      <?php else:?>
        <input type="<?=$type?>" id="field_<?=$k?>" value="<?=htmlspecialchars($config[$k]??'')?>" placeholder="<?=$ph?>">
      <?php endif?>
      <button class="ief-btn" onclick="saveField('<?=$k?>')">💾 সেভ</button>
    </div>
  </div>
  <?php endforeach?>
</div>

<div class="card">
  <div class="ctitle"><span class="i">💬</span>ওয়েলকাম মেসেজ</div>
  <?php
  $msgFields = [
    ['welcome_caption', 'ভিডিওর নিচে Caption', 'স্বাগতম {name}! 🎉', true],
    ['welcome_text',    'টেক্সট মেসেজ (ভিডিও না থাকলে)', 'স্বাগতম {name}! 👋', true],
    ['welcome_video_url','ভিডিও URL (ঐচ্ছিক)', 'https://example.com/video.mp4', false],
  ];
  foreach($msgFields as [$k,$lbl,$ph,$ta]):?>
  <div class="ief">
    <div class="ief-label"><span><?=$lbl?></span><span class="ief-saved" id="saved_<?=$k?>">✓ সেভ হয়েছে</span></div>
    <div class="ief-row">
      <?php if($ta):?><textarea rows="2" id="field_<?=$k?>" placeholder="<?=$ph?>"><?=htmlspecialchars($config[$k]??'')?></textarea>
      <?php else:?><input type="text" id="field_<?=$k?>" value="<?=htmlspecialchars($config[$k]??'')?>" placeholder="<?=$ph?>"><?php endif?>
      <button class="ief-btn" onclick="saveField('<?=$k?>')">💾 সেভ</button>
    </div>
  </div>
  <?php endforeach?>
  <div class="fc-hint" style="margin-top:4px">💡 <code style="color:var(--p3)">{name}</code> = পুরো নাম &nbsp;|&nbsp; <code style="color:var(--p3)">{username}</code> = @username</div>
</div>

<div class="card">
  <div class="ctitle"><span class="i">🎬</span>Welcome ভিডিও আপলোড</div>
  <?php if(!empty($config['welcome_video_filename'])):?>
  <div class="cur-vid">
    <span style="font-size:24px">🎬</span>
    <div style="flex:1">
      <div style="font-size:13px;font-weight:600;color:#fff"><?=htmlspecialchars($config['welcome_video_filename'])?></div>
      <div style="font-size:11px;color:var(--mu)">Size: <?=sizeStr($config['welcome_video_path']??'')?> · <?=!empty($config['welcome_video_file_id'])?'<span style="color:var(--ok)">✅ Cached</span>':'<span style="color:var(--wa)">⏳ Pending</span>'?></div>
    </div>
    <div style="display:flex;gap:7px">
      <?php if(!empty($config['welcome_video_file_id'])):?><a href="?clear_vid_cache=1" class="btn b-w">🗑 Cache</a><?php endif?>
      <a href="?del_welcome_video=1" class="btn b-d" onclick="return confirm('Welcome ভিডিও ডিলিট করবেন?')">🗑 ডিলিট</a>
    </div>
  </div>
  <?php endif?>
  <form method="POST" enctype="multipart/form-data">
    <div class="fg">
      <div class="uzone" id="wvZone">
        <input type="file" name="welcome_video" accept="video/*" id="wvIn" onchange="prvVid(this,'wvPrv')">
        <span class="uz-ico">🎬</span>
        <div class="uz-main" id="wvLbl">ভিডিও ড্র্যাগ করুন বা <strong>ক্লিক করুন</strong></div>
        <div class="uz-sub">MP4 · MOV · AVI · MKV · WEBM · 3GP</div>
      </div>
      <div id="wvPrv"></div>
    </div>
    <button type="submit" name="save_welcome_video" class="btn b-p">⬆️ Welcome ভিডিও আপলোড</button>
  </form>
</div>

<div class="card">
  <div class="ctitle"><span class="i">🔧</span>Bot অপশন</div>
  <div class="tog-group">
    <?php
    $togs = [
      ['auto_approve',    '🤖', 'Auto Approve',       'Join request স্বয়ংক্রিয়ভাবে approve'],
      ['send_to_private', '💬', 'Private DM',         'User-এর নিজের chat-এ পাঠাবে'],
      ['send_to_group',   '📣', 'Group-এ পাঠান',     'Group বা Channel-এ পাঠাবে'],
    ];
    foreach($togs as [$k,$ico,$name,$desc]):
    $on=!empty($config[$k]);?>
    <div class="tog-card <?=$on?'on':''?>" id="tc_<?=$k?>" onclick="ajaxToggle('<?=$k?>')">
      <div class="tog-card-top">
        <div class="tog-card-icon"><?=$ico?></div>
        <label class="mini-tog" onclick="event.stopPropagation()">
          <input type="checkbox" id="tog_<?=$k?>" <?=$on?'checked':''?> onchange="ajaxToggle('<?=$k?>')">
          <span class="mini-sl"></span>
        </label>
      </div>
      <div class="tog-card-name"><?=$name?></div>
      <div class="tog-card-desc"><?=$desc?></div>
    </div>
    <?php endforeach?>
  </div>
</div>

<div class="card">
  <div class="ctitle"><span class="i">🔐</span>পাসওয়ার্ড পরিবর্তন</div>
  <div class="ief">
    <div class="ief-label"><span>নতুন পাসওয়ার্ড</span><span class="ief-saved" id="saved_admin_password">✓ সেভ হয়েছে</span></div>
    <div class="ief-row">
      <input type="password" id="field_admin_password" placeholder="নতুন পাসওয়ার্ড লিখুন">
      <button class="ief-btn" onclick="saveField('admin_password')">💾 সেভ</button>
    </div>
  </div>
</div>

<!-- ════════ VIDEOS ════════ -->
<?php elseif($page==='videos'):?>
<div class="ph"><div class="pt">🎬 ভিডিও ফাইল</div><div class="ps">এখানের ভিডিও গুলো Join request-এর পর user-কে পাঠানো হবে</div></div>

<div class="card">
  <div class="ctitle"><span class="i">📤</span>নতুন ভিডিও আপলোড</div>
  <form method="POST" enctype="multipart/form-data">
    <div class="fg">
      <div class="uzone" id="vZone">
        <input type="file" name="vfile" accept="video/*" id="vIn" onchange="prvVid(this,'vPrv')" required>
        <span class="uz-ico" id="vIco">🎬</span>
        <div class="uz-main" id="vLbl">ভিডিও ড্র্যাগ করুন বা <strong>ক্লিক করুন</strong></div>
        <div class="uz-sub">MP4 · MOV · AVI · MKV · WEBM · 3GP</div>
      </div>
      <div id="vPrv"></div>
    </div>
    <div class="fg">
      <label>Caption (ঐচ্ছিক)</label>
      <input class="fc" type="text" name="vcap" placeholder="🎬 এই ভিডিওটি দেখুন {name}!">
    </div>
    <button type="submit" name="upload_video" class="btn b-p">⬆️ ভিডিও আপলোড করুন</button>
  </form>
</div>

<div class="card">
  <div class="ctitle"><span class="i">📋</span>আপলোড করা ভিডিও (<?=count($config['videos'])?>টি)</div>
  <?php if(empty($config['videos'])):?>
    <div style="text-align:center;padding:28px;color:var(--mu)"><div style="font-size:36px;margin-bottom:8px">🎬</div><div>কোনো ভিডিও নেই। উপরে আপলোড করুন।</div></div>
  <?php else: foreach($config['videos'] as $i=>$v): $on=$v['enabled']??true; ?>
  <div class="fi" style="<?=!$on?'opacity:.45':''?>">
    <div class="fi-ico">🎬</div>
    <div class="fi-info">
      <div class="fi-name"><?=htmlspecialchars($v['name']??'Video')?></div>
      <div class="fi-meta">MP4/VIDEO · <?=sizeStr($v['path']??'')?> · <?=empty($v['file_id'])?'<span style="color:var(--wa)">⏳ Pending</span>':'<span style="color:var(--ok)">✅ Cached</span>'?></div>
      <?php if(!empty($v['caption'])):?><div class="fi-cap">💬 <?=htmlspecialchars($v['caption'])?></div><?php endif?>
    </div>
    <div class="fi-act">
      <span class="badge <?=$on?'b-on':'b-off'?>"><?=$on?'চালু':'বন্ধ'?></span>
      <a href="?toggle_video=<?=$i?>&page=videos" class="btn b-cyan"><?=$on?'⏸':'▶️'?></a>
      <a href="?del_video=<?=$i?>" class="btn b-d" onclick="return confirm('ডিলিট করবেন?')">🗑</a>
    </div>
  </div>
  <?php endforeach; endif?>
</div>

<!-- ════════ APKs ════════ -->
<?php elseif($page==='apks'):?>
<div class="ph"><div class="pt">📱 APK ফাইল</div><div class="ps">Android APK ফাইল আলাদাভাবে ম্যানেজ করুন</div></div>

<div class="card">
  <div class="ctitle"><span class="i">📤</span>নতুন APK আপলোড</div>
  <form method="POST" enctype="multipart/form-data">
    <div class="fg">
      <div class="uzone" id="aZone">
        <input type="file" name="apkfile" id="aIn" onchange="showFN(this,'aIco','aLbl')" required>
        <span class="uz-ico" id="aIco">📱</span>
        <div class="uz-main" id="aLbl">APK ড্র্যাগ করুন বা <strong>ক্লিক করুন</strong></div>
        <div class="uz-sub">APK · XAPK · OBB · যেকোনো Android ফাইল</div>
      </div>
    </div>
    <div class="fg">
      <label>Caption (ঐচ্ছিক)</label>
      <input class="fc" type="text" name="acap" placeholder="📱 আমাদের অ্যাপ ডাউনলোড করুন {name}!">
    </div>
    <button type="submit" name="upload_apk" class="btn b-p">⬆️ APK আপলোড করুন</button>
  </form>
</div>

<div class="card">
  <div class="ctitle"><span class="i">📋</span>আপলোড করা APK (<?=count($config['apks'])?>টি)</div>
  <?php if(empty($config['apks'])):?>
    <div style="text-align:center;padding:28px;color:var(--mu)"><div style="font-size:36px;margin-bottom:8px">📱</div><div>কোনো APK নেই। উপরে আপলোড করুন।</div></div>
  <?php else: foreach($config['apks'] as $i=>$apk): $on=$apk['enabled']??true; ?>
  <div class="fi" style="<?=!$on?'opacity:.45':''?>">
    <div class="fi-ico">📱</div>
    <div class="fi-info">
      <div class="fi-name"><?=htmlspecialchars($apk['name']??'APK')?></div>
      <div class="fi-meta">APK · <?=sizeStr($apk['path']??'')?> · <?=empty($apk['file_id'])?'<span style="color:var(--wa)">⏳ Pending</span>':'<span style="color:var(--ok)">✅ Cached</span>'?></div>
      <?php if(!empty($apk['caption'])):?><div class="fi-cap">💬 <?=htmlspecialchars($apk['caption'])?></div><?php endif?>
    </div>
    <div class="fi-act">
      <span class="badge <?=$on?'b-on':'b-off'?>"><?=$on?'চালু':'বন্ধ'?></span>
      <a href="?toggle_apk=<?=$i?>&page=apks" class="btn b-cyan"><?=$on?'⏸':'▶️'?></a>
      <a href="?del_apk=<?=$i?>" class="btn b-d" onclick="return confirm('ডিলিট করবেন?')">🗑</a>
    </div>
  </div>
  <?php endforeach; endif?>
</div>

<!-- ════════ EXTRA FILES ════════ -->
<?php elseif($page==='extra_files'):?>
<div class="ph"><div class="pt">📄 অন্যান্য ফাইল</div><div class="ps">PDF, ZIP, Image, Audio এবং অন্যান্য ফাইল</div></div>

<div class="card">
  <div class="ctitle"><span class="i">📤</span>নতুন ফাইল আপলোড</div>
  <form method="POST" enctype="multipart/form-data">
    <div class="fg">
      <div class="uzone" id="fZone">
        <input type="file" name="xfile" id="fIn" onchange="showFN(this,'fIco','fLbl')" required>
        <span class="uz-ico" id="fIco">📂</span>
        <div class="uz-main" id="fLbl">ফাইল ড্র্যাগ করুন বা <strong>ক্লিক করুন</strong></div>
        <div class="uz-sub">PDF · ZIP · JPG · MP3 · যেকোনো ফাইল</div>
      </div>
    </div>
    <div class="fg">
      <label>Caption (ঐচ্ছিক)</label>
      <input class="fc" type="text" name="fcap" placeholder="📄 এই ফাইলটি আপনার জন্য {name}">
    </div>
    <button type="submit" name="upload_file" class="btn b-p">⬆️ ফাইল আপলোড করুন</button>
  </form>
</div>

<div class="card">
  <div class="ctitle"><span class="i">📋</span>আপলোড করা ফাইল (<?=count($config['extra_files'])?>টি)</div>
  <?php if(empty($config['extra_files'])):?>
    <div style="text-align:center;padding:28px;color:var(--mu)"><div style="font-size:36px;margin-bottom:8px">📭</div><div>কোনো ফাইল নেই।</div></div>
  <?php else: foreach($config['extra_files'] as $i=>$ef): $on=$ef['enabled']??true; ?>
  <div class="fi" style="<?=!$on?'opacity:.45':''?>">
    <div class="fi-ico"><?=typeIcon($ef['type']??'document')?></div>
    <div class="fi-info">
      <div class="fi-name"><?=htmlspecialchars($ef['name']??'File')?></div>
      <div class="fi-meta"><?=strtoupper($ef['type']??'DOC')?> · <?=sizeStr($ef['path']??'')?> · <?=empty($ef['file_id'])?'<span style="color:var(--wa)">⏳ Pending</span>':'<span style="color:var(--ok)">✅ Cached</span>'?></div>
      <?php if(!empty($ef['caption'])):?><div class="fi-cap">💬 <?=htmlspecialchars($ef['caption'])?></div><?php endif?>
    </div>
    <div class="fi-act">
      <span class="badge <?=$on?'b-on':'b-off'?>"><?=$on?'চালু':'বন্ধ'?></span>
      <a href="?toggle_file=<?=$i?>&page=extra_files" class="btn b-cyan"><?=$on?'⏸':'▶️'?></a>
      <a href="?del_file=<?=$i?>" class="btn b-d" onclick="return confirm('ডিলিট করবেন?')">🗑</a>
    </div>
  </div>
  <?php endforeach; endif?>
</div>

<!-- ════════ USERS ════════ -->
<?php elseif($page==='users'):?>
<div class="ph"><div class="pt">👥 ইউজার লিস্ট</div><div class="ps">মোট <?=$totalUsers?> জন Join Request করেছেন</div></div>
<div class="card">
  <?php if(empty($users)):?>
    <div style="text-align:center;padding:28px;color:var(--mu)"><div style="font-size:36px;margin-bottom:8px">👤</div><div>এখনো কোনো ইউজার নেই।</div></div>
  <?php else:?>
  <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:14px">
    <div style="font-size:13px;color:var(--mu)">মোট <strong style="color:#fff"><?=$totalUsers?></strong> জন</div>
    <a href="?page=broadcast" class="btn b-p" style="padding:8px 15px">📢 সবাইকে Message</a>
  </div>
  <table class="tbl">
    <tr><th>#</th><th>নাম</th><th>Username</th><th>Telegram ID</th><th>যোগ দিয়েছেন</th></tr>
    <?php $i=1; foreach(array_reverse(array_values($users)) as $u):?>
    <tr>
      <td style="color:var(--mu)"><?=$i++?></td>
      <td><span class="av"><?=mb_substr($u['first_name']??'?',0,1,'UTF-8')?></span><?=htmlspecialchars(trim(($u['first_name']??'').(' '.($u['last_name']??''))))?></td>
      <td style="color:var(--p)"><?=!empty($u['username'])?'@'.htmlspecialchars($u['username']):'—'?></td>
      <td style="font-family:monospace;font-size:11px;color:var(--mu)"><?=$u['id']??''?></td>
      <td style="color:var(--mu);font-size:11px"><?=htmlspecialchars($u['joined_at']??'')?></td>
    </tr>
    <?php endforeach?>
  </table>
  <?php endif?>
</div>

<!-- ════════ BROADCAST ════════ -->
<?php elseif($page==='broadcast'):?>
<div class="ph"><div class="pt">📢 Broadcast</div><div class="ps">সব ইউজারকে একসাথে message পাঠান</div></div>
<div class="card">
  <?php if($totalUsers===0):?>
    <div class="al al-inf">ℹ️ এখনো কোনো ইউজার নেই।</div>
  <?php else:?>
  <div class="bcast">
    <div style="font-size:12px;color:var(--p);margin-bottom:10px;font-family:'Space Grotesk',sans-serif;text-transform:uppercase;letter-spacing:.5px">📊 <?=$totalUsers?> জন ইউজারকে পাঠানো হবে</div>
    <form method="POST">
      <div class="fg">
        <label>মেসেজ লিখুন (HTML চলবে)</label>
        <textarea class="fc" name="btext" rows="6" placeholder="আমাদের নতুন আপডেট! 🎉&#10;&#10;<b>বিস্তারিত:</b>&#10;..."></textarea>
        <div class="fc-hint">💡 &lt;b&gt;bold&lt;/b&gt; · &lt;i&gt;italic&lt;/i&gt; · &lt;a href=&quot;url&quot;&gt;link&lt;/a&gt;</div>
      </div>
      <button type="submit" name="broadcast" class="btn b-p" style="font-size:14px;padding:12px 26px"
        onclick="return confirm('<?=$totalUsers?> জনকে পাঠাবেন?')">📢 সবাইকে পাঠান</button>
    </form>
  </div>
  <?php endif?>
</div>

<!-- ════════ WEBHOOK ════════ -->
<?php elseif($page==='webhook'):?>
<div class="ph"><div class="pt">🔗 Webhook</div><div class="ps">Bot কে সার্ভারের সাথে Connect করুন</div></div>
<div class="card">
  <div class="ctitle"><span class="i">🌐</span>Webhook URL</div>
  <div class="mono-box">https://<?=htmlspecialchars($config['domain']??'yourdomain.com')?>/webhook.php</div>
  <a href="?page=webhook&set_webhook=1" class="btn b-p" style="font-size:14px;padding:12px 24px">⚡ এখনই Webhook সেট করুন</a>
</div>
<div class="card">
  <div class="ctitle"><span class="i">📌</span>সেটআপ গাইড</div>
  <?php $steps=[
    ['সব ফাইল <code>public_html/</code>-এ আপলোড করুন','📂'],
    ['<code>uploads/</code>, <code>uploads/videos/</code>, <code>uploads/apks/</code>, <code>uploads/files/</code> ফোল্ডার chmod <code>755</code> করুন','📁'],
    ['Bot কে Channel/Group-এ <strong>Admin</strong> করুন','👑'],
    ['Settings এ Bot Token, Group Link, Domain সেভ করুন','⚙️'],
    ['উপরের বাটনে Webhook সেট করুন','🔗'],
    ['Telegram থেকে <code>/start</code> পাঠিয়ে test করুন','✅'],
  ]; foreach($steps as $n=>$s):?>
  <div class="step"><div class="sn"><?=$n+1?></div><div class="st"><?=$s[1]?> <?=$s[0]?></div></div>
  <?php endforeach?>
</div>

<!-- ════════ LOGS ════════ -->
<?php elseif($page==='logs'):?>
<div class="ph"><div class="pt">📋 Bot Logs</div><div class="ps">সর্বশেষ Telegram Events</div></div>
<div class="card">
  <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:14px">
    <div style="font-size:13px;color:var(--mu)">মোট <strong style="color:#fff"><?=$logLines?></strong> entries</div>
    <a href="?clear_logs=1" class="btn b-d" onclick="return confirm('সব log মুছে ফেলবেন?')">🗑 Clear</a>
  </div>
  <?php if(file_exists($log_file)&&filesize($log_file)>0):
    $lines=array_slice(array_reverse(array_filter(explode("\n",file_get_contents($log_file)))),0,100);
    echo '<div class="logbox">';
    foreach($lines as $l){ $p=explode(' | ',$l,2); echo '<div class="ll"><span class="lt">['.$p[0].']</span> '.htmlspecialchars($p[1]??'').'</div>'; }
    echo '</div>';
  else:?><div style="text-align:center;padding:28px;color:var(--mu)"><div style="font-size:36px">📭</div><div>কোনো log নেই।</div></div><?php endif?>
</div>
<?php endif?>

</main>

<script>
// ── Inline save ──────────────────────────────────────
async function saveField(key) {
  const el = document.getElementById('field_'+key);
  if (!el) return;
  const val = el.value;
  const res = await fetch('', {
    method:'POST',
    headers:{'Content-Type':'application/x-www-form-urlencoded'},
    body:'ajax_field='+encodeURIComponent(key)+'&ajax_value='+encodeURIComponent(val)
  });
  const data = await res.json();
  const sv = document.getElementById('saved_'+key);
  if (sv) { sv.style.display='inline'; setTimeout(()=>sv.style.display='none', 2000); }
}
// Enter = save in single-line inputs
document.querySelectorAll('.ief-row input').forEach(inp => {
  inp.addEventListener('keydown', e => { if(e.key==='Enter'){ e.preventDefault(); inp.nextElementSibling?.click(); }});
});

// ── Toggle ───────────────────────────────────────────
async function ajaxToggle(key) {
  const res  = await fetch('?ajax_toggle='+key);
  const data = await res.json();
  if (!data.ok) return;
  const inp = document.getElementById('tog_'+key);
  const card= document.getElementById('tc_'+key);
  if (inp)  inp.checked = data.state;
  if (card){ card.classList.toggle('on', data.state); }
}

// ── Video preview ────────────────────────────────────
function prvVid(input, prvId) {
  if (input.files[0]) {
    const u = URL.createObjectURL(input.files[0]);
    document.getElementById(prvId).innerHTML = '<video controls><source src="'+u+'"></video>';
    const lbl = input.closest('.uzone').querySelector('[id$="Lbl"]');
    if (lbl) lbl.innerHTML = '✅ নির্বাচিত: <strong>'+input.files[0].name+'</strong>';
  }
}

// ── Generic file name show ───────────────────────────
function showFN(input, icoId, lblId) {
  if (!input.files[0]) return;
  const icons = {'video':'🎬','image':'🖼️','audio':'🎵','application':'📱'};
  const type  = input.files[0].type.split('/')[0];
  const name  = input.files[0].name;
  const isApk = name.endsWith('.apk') || name.endsWith('.xapk');
  document.getElementById(icoId).textContent = isApk ? '📱' : (icons[type]||'📄');
  document.getElementById(lblId).innerHTML   = '✅ নির্বাচিত: <strong>'+name+'</strong>';
}

// ── Drag highlight ───────────────────────────────────
document.querySelectorAll('.uzone').forEach(z => {
  z.addEventListener('dragover', e => { e.preventDefault(); z.classList.add('drag'); });
  z.addEventListener('dragleave', () => z.classList.remove('drag'));
  z.addEventListener('drop', e => { e.preventDefault(); z.classList.remove('drag'); });
});

// ── Auto-hide alerts ─────────────────────────────────
setTimeout(()=>{ const a=document.querySelector('.al'); if(a){a.style.transition='opacity .5s';a.style.opacity='0';} }, 4000);
</script>
</body></html>
