<?php
require_once 'db.php';

$msg = ''; $msg_type = 'ok';

// ── Handle POST ───────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    if ($action === 'save') {
        $id         = (int)    ($_POST['id']         ?? 0);
        $name       = trim(    $_POST['name']         ?? '');
        $details    = trim(    $_POST['details']      ?? '');
        $account_no = trim(    $_POST['account_no']   ?? '');
        $active     = isset($_POST['active']) ? 1 : 0;
        $sort_order = (int)    ($_POST['sort_order']  ?? 0);
        $icon_url   = trim(    $_POST['icon_url']     ?? '');

        if (empty($name)) { $msg = 'Method name is required.'; $msg_type = 'err'; }
        else {
            $name_e     = $conn->real_escape_string($name);
            $details_e  = $conn->real_escape_string($details);
            $acct_e     = $conn->real_escape_string($account_no);
            $icon_e     = $conn->real_escape_string($icon_url);

            // Handle icon upload
            if (!empty($_FILES['icon_file']['name'])) {
                $ext_ok = ['jpg','jpeg','png','svg','webp'];
                $ext    = strtolower(pathinfo($_FILES['icon_file']['name'], PATHINFO_EXTENSION));
                if (in_array($ext, $ext_ok)) {
                    $dir = '../uploads/method_icons/';
                    if (!is_dir($dir)) mkdir($dir, 0755, true);
                    $fname = 'method_' . time() . '.' . $ext;
                    if (move_uploaded_file($_FILES['icon_file']['tmp_name'], $dir . $fname))
                        $icon_e = $conn->real_escape_string('uploads/method_icons/' . $fname);
                }
            }

            if ($id > 0) {
                $conn->query("UPDATE payment_methods SET name='{$name_e}', details='{$details_e}', account_no='{$acct_e}', icon_url='{$icon_e}', active={$active}, sort_order={$sort_order} WHERE id={$id}");
                $msg = "Payment method updated successfully.";
            } else {
                $conn->query("INSERT INTO payment_methods (name,details,account_no,icon_url,active,sort_order) VALUES ('{$name_e}','{$details_e}','{$acct_e}','{$icon_e}',{$active},{$sort_order})");
                $msg = "Payment method added successfully.";
            }
        }
    }

    elseif ($action === 'toggle') {
        $id = (int)($_POST['id'] ?? 0);
        $conn->query("UPDATE payment_methods SET active = 1 - active WHERE id={$id}");
        $msg = "Payment method toggled.";
    }

    elseif ($action === 'delete') {
        $id = (int)($_POST['id'] ?? 0);
        $conn->query("DELETE FROM payment_methods WHERE id={$id}");
        $msg = "Payment method deleted.";
    }
}

// ── Fetch all methods ─────────────────────────────────────────
$methods = [];
$res = $conn->query("SELECT * FROM payment_methods ORDER BY sort_order ASC, id ASC");
while ($row = $res->fetch_assoc()) $methods[] = $row;

// Edit mode
$editing = null;
if (isset($_GET['edit'])) {
    $eid = (int)$_GET['edit'];
    foreach ($methods as $m) if ($m['id'] === $eid) { $editing = $m; break; }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Admin – Payment Methods</title>
<link href="https://fonts.googleapis.com/css2?family=Outfit:wght@400;500;600;700;800&display=swap" rel="stylesheet">
<style>
:root{--bg:#f0f4f0;--sidebar:#1a2e1a;--green:#2d7a3a;--green-lt:#3eaabb;--gold:#f5c518;--red:#e53935;--red-lt:#fdecea;--text:#1a2a1a;--muted:#6a7a6a;--border:#dde8dd;--card:#fff;--r:12px;--r-sm:8px;--shadow:0 2px 12px rgba(0,40,0,.08)}
*{margin:0;padding:0;box-sizing:border-box}
body{font-family:'Outfit',sans-serif;background:var(--bg);color:var(--text);min-height:100vh;display:flex}
.sidebar{width:220px;background:var(--sidebar);min-height:100vh;flex-shrink:0;display:flex;flex-direction:column;position:sticky;top:0;height:100vh;overflow-y:auto}
.sb-logo{padding:22px 18px 16px;border-bottom:1px solid rgba(255,255,255,.08)}
.sb-logo h2{font-size:16px;font-weight:800;color:#fff}
.sb-logo p{font-size:11px;color:rgba(255,255,255,.4);margin-top:2px}
.sb-nav{padding:12px 0;flex:1}
.sb-section{font-size:10px;font-weight:700;color:rgba(255,255,255,.3);text-transform:uppercase;letter-spacing:.8px;padding:10px 18px 4px}
.sb-link{display:flex;align-items:center;gap:10px;padding:10px 18px;text-decoration:none;color:rgba(255,255,255,.65);font-size:13px;font-weight:500;transition:all .18s;border-left:3px solid transparent}
.sb-link svg{width:18px;height:18px;fill:currentColor;flex-shrink:0}
.sb-link:hover{color:#fff;background:rgba(255,255,255,.06)}
.sb-link.active{color:#fff;background:rgba(255,255,255,.1);border-left-color:var(--gold)}
.main{flex:1;display:flex;flex-direction:column;min-width:0}
.topbar{background:#fff;padding:14px 24px;border-bottom:1px solid var(--border);display:flex;align-items:center;justify-content:space-between;position:sticky;top:0;z-index:100;box-shadow:0 1px 4px rgba(0,0,0,.04)}
.topbar h1{font-size:18px;font-weight:800}
.content{padding:20px 24px;flex:1}
.layout{display:grid;grid-template-columns:1fr 420px;gap:20px;align-items:start}
.btn{display:inline-flex;align-items:center;gap:6px;padding:9px 18px;border-radius:var(--r-sm);font-family:'Outfit',sans-serif;font-size:13px;font-weight:700;border:none;cursor:pointer;text-decoration:none;transition:opacity .18s;white-space:nowrap}
.btn:hover{opacity:.85}
.btn-green{background:var(--green);color:#fff}
.btn-red{background:var(--red);color:#fff}
.btn-ghost{background:transparent;color:var(--muted);border:1.5px solid var(--border)}
.btn svg{width:16px;height:16px;fill:currentColor}
.alert{padding:13px 16px;border-radius:var(--r-sm);font-size:13px;font-weight:500;margin-bottom:16px;display:flex;align-items:center;gap:8px}
.alert svg{width:18px;height:18px;fill:currentColor;flex-shrink:0}
.alert-ok{background:#eafaf0;border:1px solid #a0ddb8;color:#145c30}
.alert-err{background:var(--red-lt);border:1px solid #f5b0b0;color:#7f1d1d}
.card{background:var(--card);border-radius:var(--r);padding:20px;box-shadow:var(--shadow);margin-bottom:16px}
.card-head{font-size:15px;font-weight:700;margin-bottom:18px;display:flex;align-items:center;justify-content:space-between}
.field{margin-bottom:14px}
.field label{display:block;font-size:11px;font-weight:700;color:var(--muted);margin-bottom:6px;text-transform:uppercase;letter-spacing:.5px}
.field input,.field textarea,.field select{width:100%;padding:11px 13px;border:1.5px solid var(--border);border-radius:var(--r-sm);font-family:'Outfit',sans-serif;font-size:13px;color:var(--text);background:#fff;outline:none;transition:border-color .2s}
.field input:focus,.field textarea:focus,.field select:focus{border-color:var(--green-lt)}
.field textarea{resize:vertical;min-height:90px}
.field .hint{font-size:11px;color:var(--muted);margin-top:5px;line-height:1.5}
.toggle-row{display:flex;align-items:center;justify-content:space-between;padding:10px 0}
.toggle-label{font-size:13px;font-weight:600;color:var(--text)}
.toggle-switch{position:relative;width:46px;height:26px;flex-shrink:0}
.toggle-switch input{opacity:0;width:0;height:0}
.toggle-slider{position:absolute;inset:0;background:#ccc;border-radius:26px;cursor:pointer;transition:background .2s}
.toggle-slider::before{content:'';position:absolute;width:18px;height:18px;left:4px;top:4px;background:#fff;border-radius:50%;transition:transform .2s}
.toggle-switch input:checked + .toggle-slider{background:var(--green)}
.toggle-switch input:checked + .toggle-slider::before{transform:translateX(20px)}
.sort-field{display:flex;align-items:center;gap:8px}
.sort-field input{width:80px;flex-shrink:0}

/* Method cards list */
.method-cards{display:flex;flex-direction:column;gap:10px}
.method-card{background:var(--card);border-radius:var(--r);padding:16px 18px;box-shadow:var(--shadow);
  display:flex;align-items:center;gap:14px;border-left:4px solid var(--border);transition:border-color .2s}
.method-card.active-card{border-left-color:var(--green)}
.method-card.inactive-card{border-left-color:#ccc;opacity:.7}
.method-icon{width:46px;height:46px;border-radius:10px;object-fit:contain;border:1.5px solid var(--border);background:#f8fbf8;flex-shrink:0}
.method-icon-ph{width:46px;height:46px;border-radius:10px;background:var(--green);display:flex;align-items:center;justify-content:center;flex-shrink:0}
.method-icon-ph svg{width:24px;height:24px;fill:#fff}
.method-info{flex:1;min-width:0}
.method-name{font-size:15px;font-weight:700;color:var(--text)}
.method-acct{font-size:12px;color:var(--muted);margin-top:3px;word-break:break-all}
.method-detail-prev{font-size:11px;color:var(--muted);margin-top:4px;
  white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:300px}
.status-pill{padding:3px 10px;border-radius:20px;font-size:10px;font-weight:700;text-transform:uppercase;white-space:nowrap}
.pill-active{background:#e6f9ef;color:#145c30}
.pill-inactive{background:#f5f5f5;color:#999}
.method-actions{display:flex;gap:6px;flex-shrink:0}
.act-sm{padding:6px 12px;border-radius:var(--r-sm);font-size:12px;font-weight:700;
  border:none;cursor:pointer;font-family:'Outfit',sans-serif;text-decoration:none;display:inline-block;transition:opacity .18s}
.act-sm:hover{opacity:.8}
.act-edit{background:#f0f7ff;color:#1565c0}
.act-toggle-on{background:#fff8e0;color:#a07000}
.act-toggle-off{background:#eafaf0;color:var(--green)}
.act-del{background:var(--red-lt);color:var(--red)}
.drag-handle{color:#ccc;cursor:grab;font-size:18px;margin-right:4px;user-select:none}
.sort-badge{background:#f0f5f0;color:var(--muted);font-size:11px;font-weight:700;
  padding:2px 8px;border-radius:20px;margin-left:6px}
.empty-state{text-align:center;padding:40px;color:var(--muted)}
.icon-preview{margin-top:8px;display:none;align-items:center;gap:8px}
.icon-preview img{width:40px;height:40px;border-radius:8px;object-fit:contain;border:1.5px solid var(--border)}
</style>
</head>
<body>

<!-- Sidebar -->
<aside class="sidebar">
  <div class="sb-logo"><h2>WFM Admin</h2><p>Finance Panel</p></div>
  <nav class="sb-nav">
    <div class="sb-section">Finance</div>
    <a href="admin_deposits.php" class="sb-link">
      <svg viewBox="0 0 24 24"><path d="M12 4l-1.41 1.41L16.17 11H4v2h12.17l-5.58 5.59L12 20l8-8z" transform="rotate(-90,12,12)"/></svg>Deposits</a>
    <a href="admin_withdrawals.php" class="sb-link">
      <svg viewBox="0 0 24 24"><path d="M20 12l-1.41-1.41L13 16.17V4h-2v12.17l-5.58-5.59L4 12l8 8 8-8z"/></svg>Withdrawals</a>
    <a href="admin_payment_methods.php" class="sb-link active">
      <svg viewBox="0 0 24 24"><path d="M20 4H4c-1.11 0-2 .89-2 2v12c0 1.11.89 2 2 2h16c1.11 0 2-.89 2-2V6c0-1.11-.89-2-2-2zm0 14H4v-6h16v6zm0-10H4V6h16v2z"/></svg>Payment Methods</a>
    <a href="admin_finance_settings.php" class="sb-link">
      <svg viewBox="0 0 24 24"><path d="M19.14 12.94c.04-.3.06-.61.06-.94s-.02-.64-.07-.94l2.03-1.58c.18-.14.23-.41.12-.61l-1.92-3.32c-.12-.22-.37-.29-.59-.22l-2.39.96c-.5-.38-1.03-.7-1.62-.94l-.36-2.54c-.04-.24-.24-.41-.48-.41h-3.84c-.24 0-.43.17-.47.41l-.36 2.54c-.59.24-1.13.57-1.62.94l-2.39-.96c-.22-.08-.47 0-.59.22L2.74 8.87c-.12.21-.08.47.12.61l2.03 1.58c-.05.3-.09.63-.09.94s.02.64.07.94l-2.03 1.58c-.18.14-.23.41-.12.61l1.92 3.32c.12.22.37.29.59.22l2.39-.96c.5.38 1.03.7 1.62.94l.36 2.54c.05.24.24.41.48.41h3.84c.24 0 .44-.17.47-.41l.36-2.54c.59-.24 1.13-.56 1.62-.94l2.39.96c.22.08.47 0 .59-.22l1.92-3.32c.12-.22.07-.47-.12-.61l-2.01-1.58zM12 15.6c-1.98 0-3.6-1.62-3.6-3.6s1.62-3.6 3.6-3.6 3.6 1.62 3.6 3.6-1.62 3.6-3.6 3.6z"/></svg>Finance Settings</a>
    <div class="sb-section">System</div>
    <a href="../admin_dashboard.php" class="sb-link">
      <svg viewBox="0 0 24 24"><path d="M10 20v-6h4v6h5v-8h3L12 3 2 12h3v8z"/></svg>Dashboard</a>
    <a href="../admin_logout.php" class="sb-link">
      <svg viewBox="0 0 24 24"><path d="M17 7l-1.41 1.41L18.17 11H8v2h10.17l-2.58 2.58L17 17l5-5-5-5zM4 5h8V3H4c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h8v-2H4V5z"/></svg>Logout</a>
  </nav>
</aside>

<div class="main">
  <div class="topbar">
    <h1>💳 Payment Methods</h1>
    <a href="admin_payment_methods.php" class="btn btn-green">
      <svg viewBox="0 0 24 24"><path d="M19 13H13v6h-2v-6H5v-2h6V5h2v6h6v2z"/></svg>
      Add New Method
    </a>
  </div>

  <div class="content">
    <?php if ($msg): ?>
    <div class="alert alert-<?= $msg_type ?>">
      <svg viewBox="0 0 24 24"><path d="<?= $msg_type==='ok'?'M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z':'M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 15h-2v-2h2v2zm0-4h-2V7h2v6z' ?>"/></svg>
      <?= htmlspecialchars($msg) ?>
    </div>
    <?php endif; ?>

    <div class="layout">

      <!-- Left: Methods List -->
      <div>
        <div style="font-size:14px;font-weight:700;margin-bottom:12px;color:var(--text)">
          All Payment Methods (<?= count($methods) ?>)
        </div>
        <?php if (empty($methods)): ?>
        <div class="empty-state">No payment methods yet. Add one using the form →</div>
        <?php else: ?>
        <div class="method-cards">
          <?php foreach ($methods as $m): ?>
          <div class="method-card <?= $m['active'] ? 'active-card' : 'inactive-card' ?>">
            <span class="drag-handle">⠿</span>
            <?php if ($m['icon_url']): ?>
              <img src="../<?= htmlspecialchars($m['icon_url']) ?>" class="method-icon" alt=""
                   onerror="this.style.display='none'">
            <?php else: ?>
              <div class="method-icon-ph">
                <svg viewBox="0 0 24 24"><path d="M20 4H4c-1.11 0-2 .89-2 2v12c0 1.11.89 2 2 2h16c1.11 0 2-.89 2-2V6c0-1.11-.89-2-2-2zm0 14H4v-6h16v6zm0-10H4V6h16v2z"/></svg>
              </div>
            <?php endif; ?>
            <div class="method-info">
              <div class="method-name">
                <?= htmlspecialchars($m['name']) ?>
                <span class="sort-badge">#<?= $m['sort_order'] ?></span>
                <span class="status-pill <?= $m['active'] ? 'pill-active' : 'pill-inactive' ?>">
                  <?= $m['active'] ? 'Active' : 'Hidden' ?>
                </span>
              </div>
              <?php if ($m['account_no']): ?>
              <div class="method-acct">Account: <strong><?= htmlspecialchars($m['account_no']) ?></strong></div>
              <?php endif; ?>
              <?php if ($m['details']): ?>
              <div class="method-detail-prev"><?= strip_tags($m['details']) ?></div>
              <?php endif; ?>
            </div>
            <div class="method-actions">
              <a href="?edit=<?= $m['id'] ?>" class="act-sm act-edit">✏ Edit</a>
              <form method="POST" style="display:inline">
                <input type="hidden" name="action" value="toggle">
                <input type="hidden" name="id" value="<?= $m['id'] ?>">
                <button type="submit" class="act-sm <?= $m['active'] ? 'act-toggle-on' : 'act-toggle-off' ?>">
                  <?= $m['active'] ? '⏸ Hide' : '▶ Show' ?>
                </button>
              </form>
              <form method="POST" style="display:inline" onsubmit="return confirm('Delete this payment method?')">
                <input type="hidden" name="action" value="delete">
                <input type="hidden" name="id" value="<?= $m['id'] ?>">
                <button type="submit" class="act-sm act-del">🗑</button>
              </form>
            </div>
          </div>
          <?php endforeach; ?>
        </div>
        <?php endif; ?>
      </div>

      <!-- Right: Add / Edit Form -->
      <div>
        <div class="card">
          <div class="card-head">
            <?= $editing ? '✏ Edit Method' : '➕ Add Payment Method' ?>
            <?php if ($editing): ?>
            <a href="admin_payment_methods.php" class="btn btn-ghost" style="font-size:12px;padding:5px 12px">+ New</a>
            <?php endif; ?>
          </div>

          <form method="POST" enctype="multipart/form-data">
            <input type="hidden" name="action" value="save">
            <input type="hidden" name="id" value="<?= $editing ? $editing['id'] : 0 ?>">

            <div class="field">
              <label>Method Name *</label>
              <input type="text" name="name" placeholder="e.g. M-Pesa, USDT TRC20, Bank Transfer"
                     value="<?= htmlspecialchars($editing['name'] ?? '') ?>" required>
            </div>

            <div class="field">
              <label>Receiving Account Number / Wallet</label>
              <input type="text" name="account_no"
                     placeholder="e.g. 0712 000 000 or TRC20 wallet address"
                     value="<?= htmlspecialchars($editing['account_no'] ?? '') ?>">
              <p class="hint">This is the account users will send money to. It will show a "Copy" button.</p>
            </div>

            <div class="field">
              <label>Instructions for Users (HTML allowed)</label>
              <textarea name="details" placeholder="e.g. Send to: <strong>0712 000 000</strong><br>Name: WFM Tanzania Ltd<br>Reference: your phone number"><?= htmlspecialchars($editing['details'] ?? '') ?></textarea>
              <p class="hint">Shown to user when they select this method. Use &lt;strong&gt;, &lt;br&gt; tags.</p>
            </div>

            <div class="field">
              <label>Icon URL (optional)</label>
              <input type="text" name="icon_url" id="iconUrlInput"
                     placeholder="https://… or leave blank to upload file below"
                     value="<?= htmlspecialchars($editing['icon_url'] ?? '') ?>"
                     oninput="previewIcon(this.value)">
              <div class="icon-preview" id="iconPreviewUrl">
                <img id="iconPreviewUrlImg" src="" alt="icon preview">
                <span style="font-size:12px;color:var(--muted)">Preview</span>
              </div>
            </div>

            <div class="field">
              <label>Upload Icon File (PNG, SVG, JPG)</label>
              <input type="file" name="icon_file" accept=".jpg,.jpeg,.png,.svg,.webp"
                     onchange="previewUpload(this)">
              <div class="icon-preview" id="iconPreviewFile">
                <img id="iconPreviewFileImg" src="" alt="">
                <span style="font-size:12px;color:var(--muted)">Selected file</span>
              </div>
            </div>

            <div class="field">
              <div class="sort-field">
                <div style="flex:1">
                  <label>Sort Order</label>
                  <input type="number" name="sort_order" value="<?= $editing['sort_order'] ?? 0 ?>" min="0" max="99">
                </div>
              </div>
              <p class="hint">Lower number = shown first to users.</p>
            </div>

            <div class="toggle-row">
              <span class="toggle-label">Active (visible to users)</span>
              <label class="toggle-switch">
                <input type="checkbox" name="active" <?= (!$editing || $editing['active']) ? 'checked' : '' ?>>
                <span class="toggle-slider"></span>
              </label>
            </div>

            <div style="margin-top:18px;display:flex;gap:8px">
              <button type="submit" class="btn btn-green" style="flex:1">
                <svg viewBox="0 0 24 24"><path d="M17 3H5c-1.11 0-2 .9-2 2v14c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V7l-4-4zm-5 16c-1.66 0-3-1.34-3-3s1.34-3 3-3 3 1.34 3 3-1.34 3-3 3zm3-10H5V5h10v4z"/></svg>
                <?= $editing ? 'Update Method' : 'Add Method' ?>
              </button>
              <?php if ($editing): ?>
              <a href="admin_payment_methods.php" class="btn btn-ghost">Cancel</a>
              <?php endif; ?>
            </div>
          </form>
        </div>

        <!-- Tips Card -->
        <div class="card" style="background:#f8fdf8;border:1px solid #d0e8d0">
          <div style="font-size:13px;font-weight:700;color:var(--green);margin-bottom:10px">💡 Tips</div>
          <ul style="font-size:12px;color:var(--muted);line-height:1.8;padding-left:16px">
            <li>The <strong>Account Number</strong> gets a "Copy" button on the user's deposit page.</li>
            <li>Use <code style="background:#eee;padding:1px 5px;border-radius:3px">&lt;strong&gt;</code> in instructions to highlight important info.</li>
            <li>Set <strong>Sort Order</strong> to control display order (0 = first).</li>
            <li>Use <strong>Hide</strong> to temporarily disable a method without deleting it.</li>
            <li>These methods appear in both Deposit and Withdrawal forms.</li>
          </ul>
        </div>
      </div>

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

<script>
function previewIcon(url) {
  const d = document.getElementById('iconPreviewUrl');
  const img = document.getElementById('iconPreviewUrlImg');
  if (url) { img.src = url; d.style.display = 'flex'; }
  else { d.style.display = 'none'; }
}
function previewUpload(input) {
  const d = document.getElementById('iconPreviewFile');
  const img = document.getElementById('iconPreviewFileImg');
  if (input.files && input.files[0]) {
    const reader = new FileReader();
    reader.onload = e => { img.src = e.target.result; d.style.display = 'flex'; };
    reader.readAsDataURL(input.files[0]);
  }
}
// Init preview on edit mode
const existingIcon = document.getElementById('iconUrlInput')?.value;
if (existingIcon) previewIcon(existingIcon);
</script>
</body>
</html>