<?php
// edit_account.php — smooth UI, level + gmail, image replace, buyer info

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

require __DIR__ . '/../db.php';
$config = require __DIR__ . '/../config.php';

// ensure account id
$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
if (!$id) { header('Location: accounts_list.php'); exit; }

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

// csrf-ish token
if (!isset($_SESSION['edit_token'])) {
    $_SESSION['edit_token'] = bin2hex(random_bytes(16));
}
$token = $_SESSION['edit_token'];

// fetch account
try {
    $stmt = $pdo->prepare("SELECT * FROM accounts WHERE id = ?");
    $stmt->execute([$id]);
    $acc = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!$acc) {
        $err = "Account not found.";
    }
} catch (PDOException $e) {
    $acc = null;
    $err = "DB error: " . $e->getMessage();
}

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

// helper: latest buyer (paid)
function getLatestBuyer($pdo, $account_id) {
    try {
        $stmt = $pdo->prepare("
            SELECT u.username, u.telegram_id
            FROM orders o
            JOIN users u ON o.user_id = u.id
            WHERE o.account_id = ? AND o.status = 'paid'
            ORDER BY o.created_at DESC
            LIMIT 1
        ");
        $stmt->execute([$account_id]);
        return $stmt->fetch(PDO::FETCH_ASSOC);
    } catch (PDOException $e) {
        return false;
    }
}

// handle update
if (
    $_SERVER['REQUEST_METHOD'] === 'POST' &&
    isset($_POST['token']) &&
    hash_equals($token, (string)$_POST['token']) &&
    $acc
) {
    $title          = trim($_POST['title'] ?? '');
    $caption        = trim($_POST['caption'] ?? '');
    $username_value = trim($_POST['username_value'] ?? '');
    $password_value = trim($_POST['password_value'] ?? '');
    $price          = ($_POST['price'] !== '' && $_POST['price'] !== null) ? (float)$_POST['price'] : null;
    $category_id    = ($_POST['category_id'] === '' ? null : (int)$_POST['category_id']);
    $level          = trim($_POST['level'] ?? '');
    $gmail          = trim($_POST['gmail'] ?? '');

    if ($title === '') {
        $err = "⚠️ Title is required.";
    } else {
        $image_path = $acc['image_path'] ?? null;

        // image replace logic
        if (isset($_FILES['image']) && $_FILES['image']['error'] === UPLOAD_ERR_OK) {
            $f   = $_FILES['image'];
            $ext = strtolower(pathinfo($f['name'], PATHINFO_EXTENSION));
            $allowed = ['jpg','jpeg','png','webp','gif'];
            if (!in_array($ext, $allowed, true)) {
                $err = "⚠️ Invalid image type. Allowed: jpg, jpeg, png, webp, gif.";
            } else {
                $newName = time() . '_' . bin2hex(random_bytes(6)) . '.' . $ext;
                $destDir = __DIR__ . '/../uploads/';
                if (!is_dir($destDir)) @mkdir($destDir, 0755, true);
                $dest = $destDir . $newName;

                if (!move_uploaded_file($f['tmp_name'], $dest)) {
                    $err = "⚠️ Could not move uploaded file.";
                } else {
                    // kill old file if exists
                    if (!empty($acc['image_path']) && file_exists($destDir . $acc['image_path'])) {
                        @unlink($destDir . $acc['image_path']);
                    }
                    $image_path = $newName;
                }
            }
        }

        if (!$err) {
            try {
                $stmt = $pdo->prepare("
                    UPDATE accounts SET
                        category_id    = :cat,
                        title          = :title,
                        caption        = :caption,
                        username_value = :u,
                        password_value = :p,
                        price          = :price,
                        image_path     = :img,
                        level          = :level,
                        gmail          = :gmail,
                        updated_at     = NOW()
                    WHERE id = :id
                ");
                $stmt->execute([
                    ':cat'   => $category_id,
                    ':title' => $title,
                    ':caption' => $caption,
                    ':u' => $username_value,
                    ':p' => $password_value,
                    ':price' => $price,
                    ':img' => $image_path,
                    ':level' => $level !== '' ? $level : null,
                    ':gmail' => $gmail !== '' ? $gmail : null,
                    ':id' => $id,
                ]);

                $msg = "✅ Account updated.";
                header("Location: edit_account.php?id={$id}");
                exit;
            } catch (PDOException $e) {
                $err = "❌ DB Error: " . $e->getMessage();
            }
        }
    }
}

// re-get buyer info if sold
$buyer = ($acc && (int)($acc['is_sold'] ?? 0) === 1) ? getLatestBuyer($pdo, $id) : null;
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Edit Account — Admin</title>
<meta name="viewport" content="width=device-width,initial-scale=1">
<style>
  :root{
    --bg:#050510;
    --card:#101018;
    --card-inner:#fbfbff;
    --accent:#6c5ce7;
    --accent-soft:#a29bfe;
    --border-soft:rgba(255,255,255,0.08);
    --text-main:#ffffff;
    --text-muted:#a4a7b3;
  }
  *{box-sizing:border-box}

  body{
    margin:0;
    font-family:system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;
    background:radial-gradient(circle at top,#1b1b33 0,#050510 55%);
    color:var(--text-main);
    -webkit-font-smoothing:antialiased;
  }
  .shell{
    max-width:980px;
    margin:0 auto;
    padding:18px 14px 40px;
  }

  .top-bar{
    display:flex;
    justify-content:space-between;
    align-items:flex-start;
    gap:12px;
    margin-bottom:16px;
  }
  .title-wrap h1{
    margin:0;
    font-size:22px;
    letter-spacing:.02em;
  }
  .subtitle{
    margin-top:4px;
    font-size:13px;
    color:var(--text-muted);
  }
  .nav-pill{
    display:inline-flex;
    align-items:center;
    gap:8px;
    padding:4px;
    border-radius:999px;
    background:rgba(0,0,0,0.55);
    backdrop-filter:blur(12px);
  }
  .nav-pill a{
    text-decoration:none;
    padding:8px 14px;
    border-radius:999px;
    font-size:13px;
    font-weight:600;
    display:inline-flex;
    align-items:center;
    gap:6px;
    background:linear-gradient(135deg,#ffffff,#f3f1ff);
    color:#181820;
    box-shadow:0 6px 18px rgba(0,0,0,0.32);
    border:1px solid rgba(255,255,255,0.85);
    transition:transform .12s ease, box-shadow .12s ease;
  }
  .nav-pill a:hover{
    transform:translateY(-1px);
    box-shadow:0 10px 26px rgba(0,0,0,0.4);
  }

  .card{
    background:var(--card);
    border-radius:18px;
    border:1px solid var(--border-soft);
    box-shadow:0 18px 50px rgba(0,0,0,0.6);
    padding:14px;
  }
  .inner{
    background:var(--card-inner);
    border-radius:14px;
    padding:18px 16px 20px;
    color:#050510;
  }
  .notice{
    padding:10px 12px;
    border-radius:10px;
    font-size:13px;
    margin-bottom:10px;
  }
  .notice.ok{
    background:rgba(46,213,115,0.14);
    border:1px solid rgba(46,213,115,0.6);
    color:#065f46;
  }
  .notice.err{
    background:rgba(255,71,87,0.14);
    border:1px solid rgba(255,71,87,0.7);
    color:#b91c1c;
  }

  form{
    display:flex;
    gap:18px;
    flex-wrap:wrap;
  }
  .col-left{flex:1 1 0;min-width:260px;}
  .col-right{width:320px;min-width:240px;}

  label{
    display:block;
    font-size:13px;
    font-weight:700;
    margin-bottom:6px;
    color:#050510;
  }
  input[type=text],
  input[type=number],
  textarea,
  select{
    width:100%;
    padding:10px 11px;
    border-radius:10px;
    border:1px solid rgba(15,23,42,0.08);
    font-size:14px;
    background:#ffffff;
    color:#050510;
    outline:none;
  }
  input:focus, textarea:focus, select:focus{
    border-color:rgba(108,92,231,0.8);
    box-shadow:0 0 0 1px rgba(108,92,231,0.15);
  }
  textarea{min-height:140px;resize:vertical;}

  .row{
    display:flex;
    gap:10px;
    flex-wrap:wrap;
  }
  .row .col{
    flex:1 1 0;
    min-width:140px;
  }

  .small{
    font-size:12px;
    color:#6b7280;
    margin-top:4px;
  }

  .img-wrap{
    border-radius:12px;
    background:#0b0b12;
    overflow:hidden;
    height:220px;
    display:flex;
    align-items:center;
    justify-content:center;
    margin-bottom:8px;
  }
  .img-wrap img{
    width:100%;
    height:100%;
    object-fit:cover;
    display:block;
  }

  .meta-row{
    display:flex;
    flex-wrap:wrap;
    gap:8px;
    margin-top:8px;
  }
  .meta-pill{
    padding:6px 10px;
    border-radius:999px;
    background:rgba(15,23,42,0.04);
    border:1px solid rgba(15,23,42,0.08);
    font-size:12px;
    font-weight:600;
    color:#111827;
  }

  .buyer-box{
    margin-top:10px;
    padding:9px 10px;
    border-radius:10px;
    background:#f3f4ff;
    border:1px solid rgba(79,70,229,0.14);
  }
  .buyer-box a{
    color:#4f46e5;
    font-weight:600;
    text-decoration:none;
  }

  .actions{
    display:flex;
    flex-wrap:wrap;
    gap:10px;
    margin-top:14px;
  }
  .btn{
    border:none;
    border-radius:999px;
    padding:10px 16px;
    font-size:13px;
    font-weight:700;
    cursor:pointer;
    display:inline-flex;
    align-items:center;
    gap:6px;
    text-decoration:none;
  }
  .btn-primary{
    background:linear-gradient(120deg,var(--accent),var(--accent-soft));
    color:#ffffff;
    box-shadow:0 12px 30px rgba(108,92,231,0.28);
  }
  .btn-ghost{
    background:transparent;
    border:1px solid rgba(15,23,42,0.12);
    color:#111827;
  }

  footer{
    margin-top:18px;
    text-align:center;
    font-size:13px;
    color:rgba(255,255,255,0.75);
  }

  /* MOBILE FIXES: stack rows so inputs don't overflow */
  @media (max-width:780px){
    .top-bar{flex-direction:column;align-items:flex-start}
    .col-right{width:100%;}
    .img-wrap{height:200px;}
  }
  @media (max-width:640px){
    .row{
      flex-direction:column;
      gap:8px;
    }
    .row .col{
      min-width:100%;
    }
  }
</style>
</head>
<body>
<div class="shell">
  <div class="top-bar">
    <div class="title-wrap">
      <h1>Edit Account</h1>
      <div class="subtitle">Update title, creds, price, level, Gmail, category or image. Changes reflect instantly in the bot.</div>
    </div>
    <div class="nav-pill">
      <a href="accounts_list.php">📂 Accounts</a>
      <a href="upload_account.php">📤 Upload</a>
    </div>
  </div>

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

      <?php if($acc): ?>
      <form method="post" enctype="multipart/form-data" novalidate>
        <input type="hidden" name="token" value="<?= htmlspecialchars($token) ?>">

        <div class="col-left">
          <label for="title">Title</label>
          <input id="title" name="title" value="<?= htmlspecialchars($acc['title'] ?? '') ?>" required>

          <label for="caption" style="margin-top:10px;">Caption</label>
          <textarea id="caption" name="caption"><?= htmlspecialchars($acc['caption'] ?? '') ?></textarea>
          <div class="small">First line shows at top in Telegram, keep key info there.</div>

          <div class="row" style="margin-top:12px;">
            <div class="col">
              <label for="username_value">Username</label>
              <input id="username_value" name="username_value" value="<?= htmlspecialchars($acc['username_value'] ?? '') ?>">
            </div>
            <div class="col">
              <label for="password_value">Password</label>
              <input id="password_value" name="password_value" value="<?= htmlspecialchars($acc['password_value'] ?? '') ?>">
            </div>
          </div>

          <div class="row" style="margin-top:10px;">
            <div class="col">
              <label for="level">Level</label>
              <input id="level" name="level" value="<?= htmlspecialchars($acc['level'] ?? '') ?>" placeholder="e.g. 20">
            </div>
            <div class="col">
              <label for="gmail">Gmail</label>
              <input id="gmail" name="gmail" value="<?= htmlspecialchars($acc['gmail'] ?? '') ?>" placeholder="example@gmail.com">
            </div>
          </div>

          <label for="price" style="margin-top:10px;">Price (optional)</label>
          <input id="price" type="number" step="0.01" name="price"
                 value="<?= ($acc['price'] !== null && $acc['price'] !== '') ? htmlspecialchars($acc['price']) : '' ?>">
          <div class="small">Use decimals (e.g. 100.00). Leave blank if you don't want to show price.</div>

          <label for="category_id" style="margin-top:12px;">Category</label>
          <select id="category_id" name="category_id">
            <option value="">Uncategorized</option>
            <?php foreach($cats as $c): ?>
              <option value="<?= (int)$c['id'] ?>" <?= ($acc['category_id'] == $c['id']) ? 'selected' : '' ?>>
                <?= htmlspecialchars($c['title']) ?>
              </option>
            <?php endforeach; ?>
          </select>

          <div class="actions">
            <button class="btn btn-primary" type="submit">💾 Save changes</button>
            <a class="btn btn-ghost" href="accounts_list.php">← Back to accounts</a>
          </div>
        </div>

        <div class="col-right">
          <label>Current image</label>
          <div class="img-wrap" id="imgWrap">
            <?php if(!empty($acc['image_path'])): ?>
              <img src="../uploads/<?= htmlspecialchars($acc['image_path']) ?>" id="previewImg" alt="Account image">
            <?php else: ?>
              <span class="small" style="color:#9ca3af;">No image uploaded yet</span>
            <?php endif; ?>
          </div>

          <label for="fileInput" style="margin-top:8px;">Replace image</label>
          <input id="fileInput" type="file" name="image" accept="image/*">
          <div class="small">Wide images (~1200×600) look best. Old image file is removed after upload.</div>

          <div class="meta-row">
            <div class="meta-pill">ID: <?= (int)$acc['id'] ?></div>
            <?php if((int)($acc['is_sold'] ?? 0) === 1): ?>
              <div class="meta-pill">SOLD</div>
            <?php endif; ?>
            <?php if($acc['price'] !== null && $acc['price'] !== ''): ?>
              <div class="meta-pill">₹<?= number_format((float)$acc['price'],2) ?></div>
            <?php endif; ?>
          </div>

          <?php if($buyer):
              $raw = $buyer['username'] ?: $buyer['telegram_id'];
              $tgLink = $buyer['username']
                  ? "https://t.me/".urlencode($buyer['username'])
                  : "https://t.me/".urlencode($buyer['telegram_id']);
          ?>
            <div class="buyer-box">
              <div style="font-size:13px;font-weight:700;margin-bottom:4px;">Recent buyer</div>
              <div class="small" style="margin-top:0;">
                🧾 Purchased by
                <a href="<?= $tgLink ?>" target="_blank" rel="noopener">@<?= htmlspecialchars($raw) ?></a>
              </div>
            </div>
          <?php endif; ?>
        </div>
      </form>
      <?php else: ?>
        <div class="small">Account not available.</div>
      <?php endif; ?>
    </div>
  </div>

  <footer>⚡ Managed by your bot admin panel</footer>
</div>

<script>
  // image preview on replace
  const fileInput = document.getElementById('fileInput');
  const imgWrap   = document.getElementById('imgWrap');
  const previewImg = document.getElementById('previewImg');

  if (fileInput) {
    fileInput.addEventListener('change', e => {
      const f = e.target.files && e.target.files[0];
      if (!f) return;
      if (!f.type.startsWith('image/')) {
        alert('Please choose an image file');
        return;
      }
      const reader = new FileReader();
      reader.onload = ev => {
        if (previewImg) {
          previewImg.src = ev.target.result;
        } else {
          imgWrap.innerHTML = '';
          const img = document.createElement('img');
          img.id = 'previewImg';
          img.src = ev.target.result;
          img.style.width = '100%';
          img.style.height = '100%';
          img.style.objectFit = 'cover';
          imgWrap.appendChild(img);
        }
      };
      reader.readAsDataURL(f);
    });
  }
</script>
</body>
</html>