<?php
// upload_account.php — smooth UI uploader for accounts + FakeMail bridge
// Path: /bot/admin/upload_account.php

session_start();
if (!isset($_SESSION['admin'])) { header('Location: index.php'); exit; }

require __DIR__ . '/../db.php';
$config = require __DIR__ . '/../config.php';
require __DIR__ . '/../bot_functions.php'; // for sendMessage / apiRequest

$msg = '';
$err = '';

// fetch categories (all)
try {
    $cats = $pdo->query("SELECT id, title FROM categories ORDER BY sort_order, id")->fetchAll();
} catch (PDOException $e) {
    $cats = [];
    $err = "DB error: " . $e->getMessage();
}

// defaults for repopulate
$category_id     = (int)($_POST['category_id'] ?? 0);
$title           = trim($_POST['title'] ?? '');
$caption         = trim($_POST['caption'] ?? '');
$username_value  = trim($_POST['username_value'] ?? '');
$password_value  = trim($_POST['password_value'] ?? '');
$gmail           = trim($_POST['gmail'] ?? '');
$level           = trim($_POST['level'] ?? '');
$level_custom    = trim($_POST['level_custom'] ?? '');
$price_raw       = $_POST['price'] ?? '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // compute real level (dropdown + optional custom)
    if ($level === 'other' && $level_custom !== '') {
        $final_level = $level_custom;
    } else {
        $final_level = $level !== '' ? $level : null;
    }

    $price = ($price_raw !== '') ? (float)$price_raw : null;

    // basic validation
    if ($title === '') {
        $err = "⚠️ Title is required.";
    } elseif ($category_id <= 0) {
        $err = "⚠️ Please choose a category.";
    } elseif (!isset($_FILES['image']) || $_FILES['image']['error'] !== UPLOAD_ERR_OK) {
        $err = "⚠️ Please choose an image to upload.";
    } else {
        $file = $_FILES['image'];
        $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
        $allowed = ['jpg','jpeg','png','gif','webp'];
        if (!in_array($ext, $allowed)) {
            $err = "⚠️ Invalid image type. Allowed: jpg, jpeg, png, gif, webp.";
        } else {
            $name = time() . "_" . bin2hex(random_bytes(6)) . "." . $ext;
            $dest_dir = __DIR__ . '/../uploads/';
            if (!is_dir($dest_dir)) @mkdir($dest_dir, 0755, true);
            $dest = $dest_dir . $name;

            if (!move_uploaded_file($file['tmp_name'], $dest)) {
                $err = "⚠️ Upload failed (server).";
            } else {
                // insert into DB
                try {
                    $stmt = $pdo->prepare(
                        "INSERT INTO accounts (category_id, title, caption, username_value, password_value, gmail, level, image_path, price)
                         VALUES (?,?,?,?,?,?,?,?,?)"
                    );
                    $stmt->execute([
                        $category_id,
                        $title,
                        $caption,
                        $username_value,
                        $password_value,
                        $gmail !== '' ? $gmail : null,
                        $final_level,
                        $name,
                        $price
                    ]);

                    $account_id = $pdo->lastInsertId();

                    // ----- FakeMail bridge: send hi2.in / telegmail.com to userbot -----
                    if ($gmail !== '' && preg_match('/@(hi2\.in|telegmail\.com)$/i', $gmail)) {
                        try {
                            // mark as pending so panel / other pages know it's waiting for Gen ID
                            $up = $pdo->prepare("
                                UPDATE accounts
                                SET gmail_status = 'pending',
                                    gmail_error = NULL,
                                    gmail_gen_id = NULL,
                                    gmail_delete_cmd = NULL
                                WHERE id = ?
                            ");
                            $up->execute([$account_id]);
                        } catch (PDOException $e) {
                            error_log('DB ERROR set gmail_status pending: ' . $e->getMessage());
                        }

                        // send the raw gmail to your Telethon userbot chat
                        if (!empty($config['mail_userbot_chat_id'])) {
                            // bot_functions.php -> sendMessage()
                            @sendMessage($config['mail_userbot_chat_id'], $gmail);
                        }
                    }

                    $msg = "✅ Account uploaded successfully.";
                    // clear fields after success
                    $category_id = 0;
                    $title = $caption = $username_value = $password_value = $gmail = $level = $level_custom = $price_raw = '';
                } catch (PDOException $e) {
                    $err = "❌ DB error: " . $e->getMessage();
                    @unlink($dest);
                }
            }
        }
    }
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Upload Account — Admin</title>
<meta name="viewport" content="width=device-width,initial-scale=1">

<style>
  :root{
    --bg:#050510;
    --bg-grid:#060614;
    --card:#101018;
    --card-soft:#151525;
    --accent:#7c5cff;
    --accent-soft:#a29bfe;
    --danger:#ff7675;
    --ok:#2ecc71;
    --text-main:#f8f9ff;
    --text-muted:#8f93aa;
    --border-soft:rgba(255,255,255,0.08);
  }
  *{box-sizing:border-box}
  body{
    margin:0;
    font-family:system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;
    background:
      radial-gradient(circle at top,#252547 0,#050510 55%),
      repeating-linear-gradient(90deg,rgba(255,255,255,0.02) 0,rgba(255,255,255,0.02) 1px,transparent 1px,transparent 18px),
      repeating-linear-gradient(180deg,rgba(255,255,255,0.02) 0,rgba(255,255,255,0.02) 1px,transparent 1px,transparent 18px);
    color:var(--text-main);
    -webkit-font-smoothing:antialiased;
  }
  .shell{
    max-width:980px;
    margin:0 auto;
    padding:18px 14px 40px;
  }
  .top-bar{
    display:flex;
    align-items:center;
    justify-content:space-between;
    gap:12px;
    margin-bottom:16px;
  }
  .title-wrap h1{
    margin:0;
    font-size:22px;
    letter-spacing:.06em;
    text-transform:uppercase;
  }
  .subtitle{
    margin-top:4px;
    font-size:13px;
    color:var(--text-muted);
  }
  .nav{
    display:inline-flex;
    align-items:center;
    gap:8px;
    padding:4px;
    border-radius:999px;
    background:rgba(0,0,0,0.65);
    backdrop-filter:blur(14px);
  }
  .nav a{
    text-decoration:none;
    padding:8px 14px;
    border-radius:999px;
    font-size:12px;
    font-weight:600;
    display:inline-flex;
    align-items:center;
    gap:6px;
    background:linear-gradient(135deg,#ffffff,#e4e3ff);
    color:#181820;
    box-shadow:0 6px 18px rgba(0,0,0,0.32);
    border:1px solid rgba(255,255,255,0.85);
    text-transform:uppercase;
    letter-spacing:.08em;
    transition:transform .12s ease, box-shadow .12s ease, background .12s ease;
  }
  .nav a:hover{
    transform:translateY(-1px);
    box-shadow:0 10px 26px rgba(0,0,0,0.38);
  }
  .nav a:active{
    transform:translateY(0);
    box-shadow:0 3px 10px rgba(0,0,0,0.25);
  }

  .card{
    background:rgba(7,7,16,0.96);
    border-radius:18px;
    padding:18px 16px 20px;
    border:1px solid var(--border-soft);
    box-shadow:0 18px 50px rgba(0,0,0,0.6);
    position:relative;
    overflow:hidden;
  }
  .card::before{
    content:'';
    position:absolute;
    inset:-60%;
    background:radial-gradient(circle at top left,rgba(124,92,255,0.15),transparent 55%);
    opacity:0.9;
    pointer-events:none;
  }
  .card > *{position:relative;z-index:1;}

  .notice{padding:10px 12px;border-radius:10px;font-size:13px;margin-bottom:10px}
  .notice.ok{background:rgba(46,213,115,0.08);border:1px solid rgba(46,213,115,0.6);color:#b7ffce}
  .notice.err{background:rgba(255,71,87,0.08);border:1px solid rgba(255,71,87,0.7);color:#ffd4d8}

  .layout{
    display:flex;
    gap:18px;
    flex-wrap:wrap;
    align-items:flex-start;
  }
  .col-main{flex:1 1 320px}
  .col-side{width:280px;min-width:220px}

  .uploader{
    border-radius:14px;
    border:1px dashed rgba(255,255,255,0.22);
    padding:14px 12px;
    background:linear-gradient(145deg,#050510,#101019);
    display:flex;
    flex-direction:column;
    gap:10px;
    align-items:center;
    cursor:pointer;
  }
  .uploader.dragover{
    border-style:solid;
    border-color:rgba(124,92,255,0.95);
    box-shadow:0 0 0 1px rgba(124,92,255,0.85),0 0 20px rgba(124,92,255,0.45);
  }
  .img-preview{
    width:100%;
    max-height:360px;
    border-radius:12px;
    overflow:hidden;
    background:radial-gradient(circle at top,#1f2933,#050512);
    display:flex;
    align-items:center;
    justify-content:center;
  }
  .img-preview img{
    width:100%;
    height:100%;
    object-fit:cover;
    display:block;
  }
  .hint{color:var(--text-muted);font-size:13px;text-align:center;padding:16px 8px}

  .file-btn{
    border:none;
    border-radius:999px;
    padding:9px 16px;
    font-size:12px;
    font-weight:600;
    background:linear-gradient(120deg,var(--accent),var(--accent-soft));
    color:white;
    box-shadow:0 8px 22px rgba(108,92,231,0.55);
    cursor:pointer;
    text-transform:uppercase;
    letter-spacing:.08em;
  }

  label{
    display:block;
    font-size:12px;
    color:#d6d8ff;
    margin-top:12px;
    margin-bottom:4px;
    text-transform:uppercase;
    letter-spacing:.08em;
  }

  input[type=text],input[type=number],input[type=email],textarea,select{
    width:100%;
    padding:9px 10px;
    border-radius:10px;
    border:1px solid rgba(255,255,255,0.09);
    background:#050510;
    color:var(--text-main);
    font-size:13px;
    font-family: "JetBrains Mono", ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
  }
  textarea{min-height:110px;resize:vertical}
  input::placeholder,textarea::placeholder{
    color:rgba(143,147,170,0.8);
  }
  input:focus,textarea:focus,select:focus{
    outline:none;
    border-color:var(--accent);
    box-shadow:0 0 0 1px rgba(124,92,255,0.75);
  }
  select{
    background-image:linear-gradient(45deg,transparent 50%,#d1d5ff 50%),linear-gradient(135deg,#d1d5ff 50%,transparent 50%);
    background-position:calc(100% - 16px) 14px,calc(100% - 12px) 14px;
    background-size:4px 4px,4px 4px;
    background-repeat:no-repeat;
    padding-right:30px;
  }
  .muted{font-size:11px;color:var(--text-muted);margin-top:3px}
  .field-row{display:flex;gap:10px;flex-wrap:wrap}
  .field-row .col{flex:1 1 140px}

  .btn{
    border:none;
    border-radius:999px;
    padding:10px 16px;
    font-size:13px;
    font-weight:600;
    cursor:pointer;
    display:inline-flex;
    align-items:center;
    gap:6px;
    text-decoration:none;
    text-transform:uppercase;
    letter-spacing:.08em;
  }
  .btn-primary{
    background:linear-gradient(120deg,var(--accent),var(--accent-soft));
    color:white;
    box-shadow:0 10px 26px rgba(108,92,231,0.55);
  }
  .btn-soft{
    background:rgba(255,255,255,0.04);
    color:var(--text-main);
    border:1px solid rgba(255,255,255,0.12);
  }
  .actions{display:flex;gap:10px;flex-wrap:wrap;margin-top:16px}

  .summary{
    background:var(--card-soft);
    border-radius:14px;
    padding:12px 12px 14px;
    border:1px solid var(--border-soft);
    font-size:12px;
  }
  .summary-title{font-weight:700;margin-bottom:6px;text-transform:uppercase;letter-spacing:.08em}
  .summary-row{margin-top:4px;color:var(--text-muted);display:flex;justify-content:space-between;gap:8px}
  .summary-row span{color:var(--text-main);font-family:"JetBrains Mono",ui-monospace,monospace;font-size:12px}

  .pill{
    display:inline-flex;
    align-items:center;
    gap:4px;
    padding:2px 8px;
    border-radius:999px;
    font-size:10px;
    text-transform:uppercase;
    letter-spacing:.08em;
  }
  .pill-ok{
    background:rgba(46,204,113,0.12);
    color:#b9f7d0;
    border:1px solid rgba(46,204,113,0.55);
  }
  .pill-warn{
    background:rgba(255,152,0,0.12);
    color:#ffe1b5;
    border:1px solid rgba(255,152,0,0.6);
  }

  footer{
    margin-top:16px;
    text-align:center;
    font-size:11px;
    color:rgba(255,255,255,0.75);
    text-transform:uppercase;
    letter-spacing:.12em;
  }

  @media(max-width:720px){
    .top-bar{flex-direction:column;align-items:flex-start}
    .nav{align-self:flex-end}
  }
</style>
</head>
<body>
<div class="shell">
  <div class="top-bar">
    <div class="title-wrap">
      <h1>Account Uploader</h1>
      <div class="subtitle">Drop creds, art & Gmail — bot will handle the rest like a terminal script.</div>
    </div>
    <div class="nav">
      <a href="manage_categories.php">⚙️ Categories</a>
      <a href="accounts_list.php">📂 Accounts</a>
    </div>
  </div>

  <div class="card">
    <?php if ($msg): ?>
      <div class="notice ok"><?= htmlspecialchars($msg) ?></div>
    <?php endif; ?>
    <?php if ($err): ?>
      <div class="notice err"><?= htmlspecialchars($err) ?></div>
    <?php endif; ?>

    <form method="post" enctype="multipart/form-data" id="uploadForm" novalidate>
      <div class="layout">
        <!-- LEFT: image + fields -->
        <div class="col-main">
          <!-- uploader -->
          <div id="uploader" class="uploader">
            <div id="imgPreview" class="img-preview">
              <div class="hint">No artwork yet — drop a screenshot or tap “Choose image”.</div>
            </div>

            <div style="display:flex;gap:10px;flex-wrap:wrap;align-items:center;justify-content:center;margin-top:8px">
              <button type="button" class="file-btn" id="fileBtn">Choose image</button>
              <input id="fileInput" name="image" type="file" accept="image/*" style="display:none" required>
              <span class="muted">Supports JPG / PNG / WEBP — auto-resize for Telegram.</span>
            </div>
          </div>

          <!-- fields -->
          <label for="category_id">Category</label>
          <select name="category_id" id="category_id" required>
            <option value="">— select slot —</option>
            <?php foreach($cats as $c): ?>
              <option value="<?= (int)$c['id'] ?>" <?= $category_id == (int)$c['id'] ? 'selected' : '' ?>>
                <?= htmlspecialchars($c['title']) ?>
              </option>
            <?php endforeach; ?>
          </select>
          <div class="muted">Where this account will appear inside the Telegram shop.</div>

          <label for="title">Title</label>
          <input type="text" name="title" id="title"
                 value="<?= htmlspecialchars($title) ?>"
                 placeholder="e.g. BGMI God Tier — Level 70 | Full Skins" required>

          <div class="field-row">
            <div class="col">
              <label for="level">Level</label>
              <select name="level" id="level">
                <option value="">— not shown —</option>
                <?php for($i=1;$i<=100;$i++): ?>
                  <option value="<?= $i ?>" <?= ($level == (string)$i) ? 'selected' : '' ?>>Level <?= $i ?></option>
                <?php endfor; ?>
                <option value="other" <?= $level === 'other' ? 'selected' : '' ?>>Custom label</option>
              </select>
            </div>
            <div class="col">
              <label for="level_custom">Custom level (optional)</label>
              <input type="text" name="level_custom" id="level_custom"
                     value="<?= htmlspecialchars($level_custom) ?>"
                     placeholder="e.g. LVL 125 • Asia • Max skins">
            </div>
          </div>
          <div class="muted">Use dropdown for simple levels or type anything you want.</div>

          <label for="caption">Caption (under image)</label>
          <textarea name="caption" id="caption"
                    placeholder="Add gun skins, region, login method, extra notes..."><?= htmlspecialchars($caption) ?></textarea>

          <div class="field-row">
            <div class="col">
              <label for="username_value">Login username</label>
              <input type="text" name="username_value" id="username_value"
                     value="<?= htmlspecialchars($username_value) ?>"
                     placeholder="Account username / handle">
            </div>
            <div class="col">
              <label for="password_value">Login password</label>
              <input type="text" name="password_value" id="password_value"
                     value="<?= htmlspecialchars($password_value) ?>"
                     placeholder="Account password / token">
            </div>
          </div>

          <label for="gmail">Gmail (optional)</label>
          <input type="email" name="gmail" id="gmail"
                 value="<?= htmlspecialchars($gmail) ?>"
                 placeholder="xyz@hi2.in or xyz@telegmail.com">
          <div class="muted" id="gmailHint">
            Normal Gmail mode — OTPs will <b>not</b> be auto-forwarded.
          </div>

          <label for="price">Price (optional)</label>
          <input type="text" name="price" id="price"
                 value="<?= htmlspecialchars($price_raw) ?>"
                 placeholder="e.g. 199.00">
          <div class="muted">Leave empty if you don't want to show a price in the bot.</div>

          <div class="actions">
            <button type="submit" class="btn btn-primary">➕ Push to bot</button>
            <a href="accounts_list.php" class="btn btn-soft">← Back to accounts</a>
          </div>
        </div>

        <!-- RIGHT: summary -->
        <div class="col-side">
          <div class="summary">
            <div class="summary-title">Telegram preview</div>
            <div class="summary-row"><span>Category</span><span id="sumCategory">—</span></div>
            <div class="summary-row"><span>Title</span><span id="sumTitle">—</span></div>
            <div class="summary-row"><span>Level</span><span id="sumLevel">—</span></div>
            <div class="summary-row"><span>Price</span><span id="sumPrice">—</span></div>
            <div class="summary-row"><span>Gmail</span><span id="sumGmail">—</span></div>
            <div class="muted" style="margin-top:8px">
              Approximate info layout — final card uses your bot's caption template.
            </div>

            <div style="margin-top:10px">
              <span id="gmailModePill" class="pill pill-warn">
                • Gmail status: local only
              </span>
            </div>
          </div>
        </div>
      </div>
    </form>
  </div>

  <footer>bgmi / idstore • admin console</footer>
</div>

<script>
  // elements
  const uploader   = document.getElementById('uploader');
  const fileInput  = document.getElementById('fileInput');
  const fileBtn    = document.getElementById('fileBtn');
  const imgPreview = document.getElementById('imgPreview');

  const catSel     = document.getElementById('category_id');
  const titleInput = document.getElementById('title');
  const priceInput = document.getElementById('price');
  const levelSel   = document.getElementById('level');
  const levelCustom= document.getElementById('level_custom');
  const gmailInput = document.getElementById('gmail');
  const gmailHint  = document.getElementById('gmailHint');
  const gmailModePill = document.getElementById('gmailModePill');

  const sumCategory= document.getElementById('sumCategory');
  const sumTitle   = document.getElementById('sumTitle');
  const sumPrice   = document.getElementById('sumPrice');
  const sumLevel   = document.getElementById('sumLevel');
  const sumGmail   = document.getElementById('sumGmail');

  function setPreviewFromURL(url){
    imgPreview.innerHTML = '<img src="'+url+'" alt="preview">';
  }
  function setPreviewFromFile(file){
    const reader = new FileReader();
    reader.onload = e => setPreviewFromURL(e.target.result);
    reader.readAsDataURL(file);
  }

  // drag & drop
  ['dragenter','dragover'].forEach(ev=>{
    uploader.addEventListener(ev, e=>{
      e.preventDefault(); e.stopPropagation();
      uploader.classList.add('dragover');
    });
  });
  ['dragleave','drop'].forEach(ev=>{
    uploader.addEventListener(ev, e=>{
      e.preventDefault(); e.stopPropagation();
      uploader.classList.remove('dragover');
    });
  });
  uploader.addEventListener('drop', e=>{
    const f = e.dataTransfer.files && e.dataTransfer.files[0];
    if (!f) return;
    if (!f.type.startsWith('image/')) { alert('Please drop an image file.'); return; }
    handleFile(f);
  });

  fileBtn.addEventListener('click', ()=> fileInput.click());
  fileInput.addEventListener('change', e=>{
    const f = e.target.files && e.target.files[0];
    if (!f) return;
    handleFile(f);
  });

  async function handleFile(file){
    setPreviewFromFile(file);
    // optional resize to max width 1200
    try{
      const imgBitmap = await createImageBitmap(file);
      const maxW = 1200;
      let w = imgBitmap.width, h = imgBitmap.height;
      if (w > maxW){
        const r = maxW / w;
        w = Math.round(w * r);
        h = Math.round(h * r);
      }
      if (w !== imgBitmap.width){
        const canvas = document.createElement('canvas');
        canvas.width = w; canvas.height = h;
        const ctx = canvas.getContext('2d');
        ctx.drawImage(imgBitmap,0,0,w,h);
        const type = file.type === 'image/png' ? 'image/png' : 'image/jpeg';
        const blob = await new Promise(res=>canvas.toBlob(res,type,0.9));
        if (blob && blob.size > 0){
          const newFile = new File([blob], file.name, {type: blob.type});
          const dt = new DataTransfer();
          dt.items.add(newFile);
          fileInput.files = dt.files;
          const url = URL.createObjectURL(newFile);
          setPreviewFromURL(url);
          setTimeout(()=>URL.revokeObjectURL(url),30000);
          return;
        }
      }
      const dt = new DataTransfer();
      dt.items.add(file);
      fileInput.files = dt.files;
    }catch(err){
      const dt = new DataTransfer();
      dt.items.add(file);
      fileInput.files = dt.files;
      console.warn('resize failed', err);
    }
  }

  // summary updates
  function updateCategorySummary(){
    if (!catSel || catSel.selectedIndex < 0) { sumCategory.textContent = '—'; return; }
    sumCategory.textContent = catSel.options[catSel.selectedIndex].text || '—';
  }
  function updateTitleSummary(){
    sumTitle.textContent = titleInput.value.trim() || '—';
  }
  function updatePriceSummary(){
    const v = priceInput.value.trim();
    sumPrice.textContent = v ? ('₹'+v) : '—';
  }
  function updateLevelSummary(){
    if (levelSel.value === 'other') {
      sumLevel.textContent = levelCustom.value.trim() || 'Custom';
    } else if (levelSel.value){
      sumLevel.textContent = levelSel.options[levelSel.selectedIndex].text;
    } else {
      sumLevel.textContent = '—';
    }
  }
  function updateGmailSummary(){
    const v = gmailInput.value.trim();
    sumGmail.textContent = v || '—';

    const isFake = /@(hi2\.in|telegmail\.com)$/i.test(v);
    if (isFake){
      gmailHint.innerHTML = "FakeMail mode: this Gmail will auto-connect to the VPS userbot for OTP & delete.";
      gmailModePill.textContent = "• Gmail status: queued to userbot";
      gmailModePill.classList.remove('pill-warn');
      gmailModePill.classList.add('pill-ok');
    } else if (v){
      gmailHint.innerHTML = "Normal Gmail — fine to use, but OTPs are not auto-forwarded.";
      gmailModePill.textContent = "• Gmail status: regular";
      gmailModePill.classList.remove('pill-ok');
      gmailModePill.classList.add('pill-warn');
    } else {
      gmailHint.innerHTML = "Optional. Use hi2.in / telegmail.com to unlock auto OTP system.";
      gmailModePill.textContent = "• Gmail status: empty";
      gmailModePill.classList.remove('pill-ok');
      gmailModePill.classList.add('pill-warn');
    }
  }

  if (catSel)    { catSel.addEventListener('change', updateCategorySummary); updateCategorySummary(); }
  if (titleInput){ titleInput.addEventListener('input', updateTitleSummary); updateTitleSummary(); }
  if (priceInput){ priceInput.addEventListener('input', updatePriceSummary); updatePriceSummary(); }
  if (levelSel)  { levelSel.addEventListener('change', updateLevelSummary); updateLevelSummary(); }
  if (levelCustom){ levelCustom.addEventListener('input', updateLevelSummary); }
  if (gmailInput){ gmailInput.addEventListener('input', updateGmailSummary); updateGmailSummary(); }
</script>
</body>
</html>