<?php
require_once 'db.php';

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

// ── Handle POST ───────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $fields = [
        'min_deposit'       => (float)($_POST['min_deposit']      ?? 0),
        'max_deposit'       => (float)($_POST['max_deposit']      ?? 0),
        'min_withdraw'      => (float)($_POST['min_withdraw']     ?? 0),
        'max_withdraw'      => (float)($_POST['max_withdraw']     ?? 0),
        'withdraw_fee_pct'  => (float)($_POST['withdraw_fee_pct'] ?? 0),
        'currency_symbol'   => trim(   $_POST['currency_symbol']  ?? 'TZS'),
    ];

    // Validate
    if ($fields['min_deposit'] <= 0 || $fields['max_deposit'] <= 0)
        { $msg = 'Deposit limits must be greater than 0.'; $msg_type='err'; }
    elseif ($fields['min_deposit'] >= $fields['max_deposit'])
        { $msg = 'Min deposit must be less than Max deposit.'; $msg_type='err'; }
    elseif ($fields['min_withdraw'] <= 0 || $fields['max_withdraw'] <= 0)
        { $msg = 'Withdrawal limits must be greater than 0.'; $msg_type='err'; }
    elseif ($fields['min_withdraw'] >= $fields['max_withdraw'])
        { $msg = 'Min withdraw must be less than Max withdraw.'; $msg_type='err'; }
    elseif ($fields['withdraw_fee_pct'] < 0 || $fields['withdraw_fee_pct'] > 50)
        { $msg = 'Withdrawal fee must be between 0% and 50%.'; $msg_type='err'; }
    else {
        foreach ($fields as $key => $val) {
            $key_e = $conn->real_escape_string($key);
            $val_e = $conn->real_escape_string((string)$val);
            // Upsert
            $conn->query("INSERT INTO settings (key_name, key_value) VALUES ('{$key_e}','{$val_e}')
                          ON DUPLICATE KEY UPDATE key_value='{$val_e}'");
        }
        $msg = 'Finance settings saved successfully.';
    }
}

// ── Load current settings ─────────────────────────────────────
function gs($conn, $k, $d='') {
    $r = $conn->query("SELECT key_value FROM settings WHERE key_name='" . $conn->real_escape_string($k) . "' LIMIT 1")->fetch_assoc();
    return $r['key_value'] ?? $d;
}

$s = [
    'min_deposit'      => gs($conn,'min_deposit',     '1000'),
    'max_deposit'      => gs($conn,'max_deposit',     '10000000'),
    'min_withdraw'     => gs($conn,'min_withdraw',    '500'),
    'max_withdraw'     => gs($conn,'max_withdraw',    '5000000'),
    'withdraw_fee_pct' => gs($conn,'withdraw_fee_pct','2'),
    'currency_symbol'  => gs($conn,'currency_symbol', 'TZS'),
];

// ── Live stats ────────────────────────────────────────────────
$total_security = (float)($conn->query("SELECT COALESCE(SUM(security_deposit),0) as s FROM users")->fetch_assoc()['s'] ?? 0);
$total_balance  = (float)($conn->query("SELECT COALESCE(SUM(balance),0) as s FROM users")->fetch_assoc()['s'] ?? 0);
$pending_deps   = (int)($conn->query("SELECT COUNT(*) as c FROM deposits WHERE status='pending'")->fetch_assoc()['c'] ?? 0);
$pending_wds    = (int)($conn->query("SELECT COUNT(*) as c FROM withdrawals WHERE status='pending'")->fetch_assoc()['c'] ?? 0);
$pending_dep_amt= (float)($conn->query("SELECT COALESCE(SUM(amount),0) as s FROM deposits WHERE status='pending'")->fetch_assoc()['s'] ?? 0);
$pending_wd_amt = (float)($conn->query("SELECT COALESCE(SUM(net_amount),0) as s FROM withdrawals WHERE status='pending'")->fetch_assoc()['s'] ?? 0);
$total_dep_approved = (float)($conn->query("SELECT COALESCE(SUM(amount),0) as s FROM deposits WHERE status='approved'")->fetch_assoc()['s'] ?? 0);
$total_wd_approved  = (float)($conn->query("SELECT COALESCE(SUM(net_amount),0) as s FROM withdrawals WHERE status='approved'")->fetch_assoc()['s'] ?? 0);
$total_fees_earned  = (float)($conn->query("SELECT COALESCE(SUM(fee),0) as s FROM withdrawals WHERE status='approved'")->fetch_assoc()['s'] ?? 0);

$currency = $s['currency_symbol'];
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Admin – Finance Settings</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 360px;gap:20px;align-items:start}
.btn{display:inline-flex;align-items:center;gap:6px;padding:9px 20px;border-radius:var(--r-sm);font-family:'Outfit',sans-serif;font-size:14px;font-weight:700;border:none;cursor:pointer;text-decoration:none;transition:opacity .18s}
.btn:hover{opacity:.85}
.btn-green{background:var(--green);color:#fff}
.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:22px;box-shadow:var(--shadow);margin-bottom:16px}
.section-title{font-size:15px;font-weight:700;color:var(--text);margin-bottom:18px;
  padding-bottom:10px;border-bottom:1px solid var(--border);
  display:flex;align-items:center;gap:8px}
.section-title .icon{font-size:18px}
.field{margin-bottom:16px}
.field label{display:block;font-size:11px;font-weight:700;color:var(--muted);margin-bottom:6px;text-transform:uppercase;letter-spacing:.5px}
.field .input-wrap{position:relative}
.field .input-wrap .prefix{position:absolute;left:13px;top:50%;transform:translateY(-50%);
  font-size:13px;font-weight:700;color:var(--muted);pointer-events:none}
.field input{width:100%;padding:12px 14px;border:1.5px solid var(--border);border-radius:var(--r-sm);
  font-family:'Outfit',sans-serif;font-size:14px;color:var(--text);background:#fff;outline:none;transition:border-color .2s}
.field input.has-prefix{padding-left:42px}
.field input:focus{border-color:var(--green-lt)}
.field .hint{font-size:11px;color:var(--muted);margin-top:5px;line-height:1.5}
.field input.suffix-field{padding-right:46px}
.suffix-wrap{position:relative}
.suffix-wrap .sfx{position:absolute;right:13px;top:50%;transform:translateY(-50%);
  font-size:13px;font-weight:700;color:var(--muted)}
.field-row{display:grid;grid-template-columns:1fr 1fr;gap:12px}
.save-bar{display:flex;gap:10px;align-items:center;margin-top:4px}
.save-bar .note{font-size:12px;color:var(--muted)}

/* Stats sidebar */
.stat-block{background:var(--card);border-radius:var(--r);padding:18px;box-shadow:var(--shadow);margin-bottom:14px}
.stat-block-title{font-size:12px;font-weight:700;color:var(--muted);text-transform:uppercase;letter-spacing:.5px;margin-bottom:14px}
.stat-row{display:flex;justify-content:space-between;align-items:center;padding:8px 0;border-bottom:1px solid #f4f8f4}
.stat-row:last-child{border-bottom:none}
.stat-row .lbl{font-size:13px;color:var(--muted);font-weight:500}
.stat-row .val{font-size:13px;font-weight:800;color:var(--text)}
.stat-row .val.green{color:var(--green)}
.stat-row .val.red{color:var(--red)}
.stat-row .val.gold{color:var(--gold2,#c9960a)}
.alert-pending{background:#fff8e0;border:1px solid var(--gold);border-radius:var(--r-sm);padding:12px 14px;font-size:13px;color:#7a5000;font-weight:500;margin-bottom:14px}
.alert-pending a{color:var(--green);font-weight:700;text-decoration:none}
</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">
      <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 active">
      <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>⚙️ Finance Settings</h1>
    <span style="font-size:12px;color:var(--muted)">Last updated: <?= date('d M Y H:i') ?></span>
  </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: Settings Form -->
      <form method="POST">
        <!-- Currency -->
        <div class="card">
          <div class="section-title"><span class="icon">🏦</span> Currency & System</div>
          <div class="field">
            <label>Currency Symbol</label>
            <input type="text" name="currency_symbol" value="<?= htmlspecialchars($s['currency_symbol']) ?>"
                   placeholder="TZS" maxlength="10">
            <p class="hint">Used across all user-facing pages (e.g. TZS, KES, USD, USDT).</p>
          </div>
        </div>

        <!-- Deposit Limits -->
        <div class="card">
          <div class="section-title"><span class="icon">⬆️</span> Deposit Limits</div>
          <div class="field-row">
            <div class="field">
              <label>Minimum Deposit</label>
              <div class="input-wrap">
                <span class="prefix"><?= htmlspecialchars($s['currency_symbol']) ?></span>
                <input type="number" name="min_deposit" class="has-prefix"
                       value="<?= $s['min_deposit'] ?>" min="0" step="1" required>
              </div>
              <p class="hint">Smallest amount user can deposit.</p>
            </div>
            <div class="field">
              <label>Maximum Deposit</label>
              <div class="input-wrap">
                <span class="prefix"><?= htmlspecialchars($s['currency_symbol']) ?></span>
                <input type="number" name="max_deposit" class="has-prefix"
                       value="<?= $s['max_deposit'] ?>" min="0" step="1" required>
              </div>
              <p class="hint">Largest single deposit request.</p>
            </div>
          </div>
          <div style="background:#f0f8f0;border:1px solid #c0e0c0;border-radius:var(--r-sm);padding:10px 12px;font-size:12px;color:var(--muted)">
            📌 Deposits go to user's <strong style="color:var(--green)">Security Deposit</strong> after admin approval.
          </div>
        </div>

        <!-- Withdrawal Limits -->
        <div class="card">
          <div class="section-title"><span class="icon">⬇️</span> Withdrawal Limits & Fees</div>
          <div class="field-row">
            <div class="field">
              <label>Minimum Withdrawal</label>
              <div class="input-wrap">
                <span class="prefix"><?= htmlspecialchars($s['currency_symbol']) ?></span>
                <input type="number" name="min_withdraw" class="has-prefix"
                       value="<?= $s['min_withdraw'] ?>" min="0" step="1" required>
              </div>
            </div>
            <div class="field">
              <label>Maximum Withdrawal</label>
              <div class="input-wrap">
                <span class="prefix"><?= htmlspecialchars($s['currency_symbol']) ?></span>
                <input type="number" name="max_withdraw" class="has-prefix"
                       value="<?= $s['max_withdraw'] ?>" min="0" step="1" required>
              </div>
            </div>
          </div>

          <div class="field">
            <label>Withdrawal Fee (%)</label>
            <div class="suffix-wrap">
              <input type="number" name="withdraw_fee_pct" class="suffix-field"
                     value="<?= $s['withdraw_fee_pct'] ?>" min="0" max="50" step="0.01" required>
              <span class="sfx">%</span>
            </div>
            <p class="hint">
              Fee is deducted from the withdrawal amount. Example: user withdraws
              <strong>10,000</strong> with <strong><?= $s['withdraw_fee_pct'] ?>%</strong> fee →
              receives <strong><?= number_format(10000 * (1 - $s['withdraw_fee_pct']/100), 0) ?></strong>,
              fee = <strong><?= number_format(10000 * $s['withdraw_fee_pct']/100, 0) ?></strong>.
              Set <strong>0</strong> for no fee.
            </p>
          </div>

          <div style="background:#fff8e0;border:1px solid #f5d080;border-radius:var(--r-sm);padding:10px 12px;font-size:12px;color:#7a5000">
            📌 Withdrawals are from user's <strong>Account Balance only</strong> (earnings, commissions, referrals, bonuses). Security Deposit is not withdrawable.
          </div>
        </div>

        <div class="save-bar">
          <button type="submit" class="btn btn-green">
            <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>
            Save All Settings
          </button>
          <span class="note">Changes apply immediately to all users.</span>
        </div>
      </form>

      <!-- Right: Live Stats Sidebar -->
      <div>
        <?php if ($pending_deps > 0 || $pending_wds > 0): ?>
        <div class="alert-pending">
          ⏳ You have
          <?php if ($pending_deps > 0): ?>
          <a href="admin_deposits.php?status=pending"><?= $pending_deps ?> pending deposit<?= $pending_deps>1?'s':'' ?></a>
          (<?= number_format($pending_dep_amt,0) ?> <?= $currency ?>)
          <?php endif; ?>
          <?php if ($pending_deps && $pending_wds): ?> and <?php endif; ?>
          <?php if ($pending_wds > 0): ?>
          <a href="admin_withdrawals.php?status=pending"><?= $pending_wds ?> pending withdrawal<?= $pending_wds>1?'s':'' ?></a>
          (<?= number_format($pending_wd_amt,0) ?> <?= $currency ?> to pay out)
          <?php endif; ?>
          awaiting action.
        </div>
        <?php endif; ?>

        <div class="stat-block">
          <div class="stat-block-title">📊 Platform Overview</div>
          <div class="stat-row">
            <span class="lbl">Total Security Deposits</span>
            <span class="val green"><?= number_format($total_security,0) ?> <?= $currency ?></span>
          </div>
          <div class="stat-row">
            <span class="lbl">Total Account Balances</span>
            <span class="val green"><?= number_format($total_balance,0) ?> <?= $currency ?></span>
          </div>
          <div class="stat-row">
            <span class="lbl">Total Deposited (approved)</span>
            <span class="val"><?= number_format($total_dep_approved,0) ?> <?= $currency ?></span>
          </div>
          <div class="stat-row">
            <span class="lbl">Total Paid Out (approved)</span>
            <span class="val red"><?= number_format($total_wd_approved,0) ?> <?= $currency ?></span>
          </div>
          <div class="stat-row">
            <span class="lbl">Total Fees Earned</span>
            <span class="val gold"><?= number_format($total_fees_earned,0) ?> <?= $currency ?></span>
          </div>
        </div>

        <div class="stat-block">
          <div class="stat-block-title">⏳ Pending Actions</div>
          <div class="stat-row">
            <span class="lbl">Pending Deposits</span>
            <a href="admin_deposits.php?status=pending" style="text-decoration:none">
              <span class="val" style="color:var(--gold2,#c9960a)"><?= $pending_deps ?> · <?= number_format($pending_dep_amt,0) ?> <?= $currency ?></span>
            </a>
          </div>
          <div class="stat-row">
            <span class="lbl">Pending Withdrawals</span>
            <a href="admin_withdrawals.php?status=pending" style="text-decoration:none">
              <span class="val red"><?= $pending_wds ?> · <?= number_format($pending_wd_amt,0) ?> <?= $currency ?></span>
            </a>
          </div>
        </div>

        <div class="stat-block" style="background:#f8fdf8;border:1px solid #d0e8d0">
          <div class="stat-block-title" style="color:var(--green)">💡 How Balances Work</div>
          <div style="font-size:12px;color:var(--muted);line-height:1.9">
            <div>⬆️ <strong>Deposit</strong> → Security Deposit</div>
            <div>📋 <strong>Join Plan / Tasks</strong> → uses Security Deposit</div>
            <div>💰 <strong>Earnings / Referrals / Bonuses</strong> → Account Balance</div>
            <div>⬇️ <strong>Withdraw</strong> → from Account Balance only</div>
            <div>🔒 <strong>Security Deposit</strong> → not withdrawable</div>
          </div>
        </div>
      </div>

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

<script>
// Live fee example preview
document.querySelector('[name=withdraw_fee_pct]').addEventListener('input', function() {
  const fee = parseFloat(this.value) || 0;
  const net = Math.round(10000 * (1 - fee/100));
  const feeAmt = Math.round(10000 * fee/100);
  this.closest('.field').querySelector('.hint').innerHTML =
    `Fee is deducted from the withdrawal amount. Example: user withdraws <strong>10,000</strong> with <strong>${fee}%</strong> fee → receives <strong>${net.toLocaleString()}</strong>, fee = <strong>${feeAmt.toLocaleString()}</strong>. Set <strong>0</strong> for no fee.`;
});
</script>
</body>
</html>