<?php
session_start();
$page_title  = 'My Wallet';
$active_nav  = 'my_wallet';
include('includes/header.php');

$_paystack_config = __DIR__ . '/config/paystack.php';
if (!file_exists($_paystack_config)) {
    die('<strong>Paystack config missing.</strong> File not found at: ' . htmlspecialchars($_paystack_config));
}
include_once($_paystack_config);

$success = $error = "";

// ── Commission rate from DB ───────────────────────────────────────────────────
$cr_res          = $conn->query("SELECT setting_value FROM platform_settings WHERE setting_key='commission_rate' LIMIT 1");
$commission_rate = $cr_res ? (float)($cr_res->fetch_row()[0] ?? 10) : 10.00;

// ── Ensure super admin wallet exists ─────────────────────────────────────────
$chk = $conn->prepare("SELECT id, balance FROM wallets WHERE user_id=? AND wallet_type='super_admin' LIMIT 1");
$chk->bind_param("i", $uid); $chk->execute();
$wallet = $chk->get_result()->fetch_assoc();
if (!$wallet) {
    $conn->query("INSERT INTO wallets (user_id, wallet_type, balance) VALUES ({$uid}, 'super_admin', 0.00)");
    $wallet = ['id' => $conn->insert_id, 'balance' => 0.00];
}
$wallet_balance = (float)$wallet['balance'];

// ── Handle: Add Bank Account ──────────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'add_bank') {
    $bank_name   = trim($_POST['bank_name']      ?? '');
    $acct_name   = trim($_POST['account_name']   ?? '');
    $acct_number = trim($_POST['account_number'] ?? '');
    $bank_code   = trim($_POST['bank_code']       ?? '');

    if (!$bank_name || !$acct_name || !$acct_number || !$bank_code) {
        $error = "All bank account fields are required.";
    } elseif (!preg_match('/^\d{10}$/', $acct_number)) {
        $error = "Account number must be exactly 10 digits.";
    } else {
        $recipient_code = '';
        $ch = curl_init('https://api.paystack.co/transferrecipient');
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true, CURLOPT_POST => true,
            CURLOPT_POSTFIELDS     => json_encode(['type'=>'nuban','name'=>$acct_name,'account_number'=>$acct_number,'bank_code'=>$bank_code,'currency'=>'NGN']),
            CURLOPT_HTTPHEADER     => ['Authorization: Bearer '.$PAYSTACK_SECRET_KEY,'Content-Type: application/json'],
        ]);
        $ps_resp = json_decode(curl_exec($ch), true); curl_close($ch);
        if (!empty($ps_resp['status']) && $ps_resp['status'] === true) {
            $recipient_code = $ps_resp['data']['recipient_code'] ?? '';
        }
        $is_default = ($conn->query("SELECT COUNT(*) FROM bank_accounts WHERE owner_type='super_admin' AND user_id={$uid}")->fetch_row()[0] == 0) ? 1 : 0;
        $ins = $conn->prepare("INSERT INTO bank_accounts (owner_type,user_id,bank_name,account_name,account_number,bank_code,recipient_code,is_default) VALUES ('super_admin',?,?,?,?,?,?,?)");
        $ins->bind_param("isssssi", $uid, $bank_name, $acct_name, $acct_number, $bank_code, $recipient_code, $is_default);
        $ins->execute();
        $success = "Bank account added successfully!";
    }
}

// ── Handle: Delete Bank Account ───────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'delete_bank') {
    $ba_id = (int)($_POST['bank_account_id'] ?? 0);
    $del = $conn->prepare("DELETE FROM bank_accounts WHERE id=? AND owner_type='super_admin' AND user_id=?");
    $del->bind_param("ii", $ba_id, $uid);
    $del->execute();
    $success = "Bank account removed.";
}

// ── Handle: Set Default Bank ─────────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'set_default_bank') {
    $ba_id = (int)($_POST['bank_account_id'] ?? 0);
    $conn->query("UPDATE bank_accounts SET is_default=0 WHERE owner_type='super_admin' AND user_id={$uid}");
    $upd = $conn->prepare("UPDATE bank_accounts SET is_default=1 WHERE id=? AND owner_type='super_admin' AND user_id=?");
    $upd->bind_param("ii", $ba_id, $uid);
    $upd->execute();
    $success = "Default bank account updated.";
}

// ── Handle: Withdraw ──────────────────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'withdraw') {
    $amount = (float)($_POST['amount'] ?? 0);
    $ba_id  = (int)($_POST['bank_account_id'] ?? 0);

    if ($amount < 500)               { $error = "Minimum withdrawal is ₦500."; }
    elseif ($amount > $wallet_balance){ $error = "Insufficient balance. Your balance is ₦".number_format($wallet_balance,2)."."; }
    elseif (!$ba_id)                 { $error = "Please select a bank account."; }
    else {
        $ba_stmt = $conn->prepare("SELECT * FROM bank_accounts WHERE id=? AND owner_type='super_admin' AND user_id=? LIMIT 1");
        $ba_stmt->bind_param("ii",$ba_id,$uid); $ba_stmt->execute();
        $ba = $ba_stmt->get_result()->fetch_assoc();

        if (!$ba) { $error = "Bank account not found."; }
        else {
            $recipient_code = $ba['recipient_code'];
            if (!$recipient_code) {
                $ch = curl_init('https://api.paystack.co/transferrecipient');
                curl_setopt_array($ch,[CURLOPT_RETURNTRANSFER=>true,CURLOPT_POST=>true,
                    CURLOPT_POSTFIELDS=>json_encode(['type'=>'nuban','name'=>$ba['account_name'],'account_number'=>$ba['account_number'],'bank_code'=>$ba['bank_code'],'currency'=>'NGN']),
                    CURLOPT_HTTPHEADER=>['Authorization: Bearer '.$PAYSTACK_SECRET_KEY,'Content-Type: application/json']]);
                $ps_resp = json_decode(curl_exec($ch),true); curl_close($ch);
                if (!empty($ps_resp['data']['recipient_code'])) {
                    $recipient_code = $ps_resp['data']['recipient_code'];
                    $conn->query("UPDATE bank_accounts SET recipient_code='" . $conn->real_escape_string($recipient_code) . "' WHERE id={$ba_id}");
                } else { $error = "Could not verify bank account with Paystack. Please re-add it."; }
            }

            if (!$error) {
                $ref         = 'WD_SA_'.$uid.'_'.time();
                $amount_kobo = (int)($amount * 100);
                $ch = curl_init('https://api.paystack.co/transfer');
                curl_setopt_array($ch,[CURLOPT_RETURNTRANSFER=>true,CURLOPT_POST=>true,
                    CURLOPT_POSTFIELDS=>json_encode(['source'=>'balance','reason'=>'Super Admin withdrawal','amount'=>$amount_kobo,'recipient'=>$recipient_code,'reference'=>$ref]),
                    CURLOPT_HTTPHEADER=>['Authorization: Bearer '.$PAYSTACK_SECRET_KEY,'Content-Type: application/json']]);
                $ps_resp = json_decode(curl_exec($ch),true); curl_close($ch);
                $transfer_code = $ps_resp['data']['transfer_code'] ?? '';
                $ps_ok         = !empty($ps_resp['status']) && $ps_resp['status'] === true;

                $conn->begin_transaction();
                try {
                    $conn->query("UPDATE wallets SET balance=balance-{$amount},updated_at=NOW() WHERE user_id={$uid} AND wallet_type='super_admin'");
                    $wt = $conn->prepare("INSERT INTO wallet_transactions (user_id,wallet_type,amount,type,reference,description,status) VALUES (?,'super_admin',?,'debit',?,'Withdrawal to bank account',?)");
                    $wt_status = $ps_ok ? 'success' : 'pending';
                    $wt->bind_param("idss",$uid,$amount,$ref,$wt_status); $wt->execute();
                    $wr = $conn->prepare("INSERT INTO withdrawals (user_id,wallet_type,amount,reference,recipient_code,transfer_code,bank_account_id,status) VALUES (?,'super_admin',?,?,?,?,?,?)");
                    $wd_status = $ps_ok ? 'success' : 'pending';
                    $wr->bind_param("idsssis",$uid,$amount,$ref,$recipient_code,$transfer_code,$ba_id,$wd_status); $wr->execute();
                    $conn->commit();
                    $wallet_balance -= $amount;
                    $success = "₦".number_format($amount,2)." withdrawal ".($ps_ok ? "initiated! Transfer: {$transfer_code}" : "recorded — processing shortly.");
                } catch (Exception $e) {
                    $conn->rollback();
                    $error = "Withdrawal failed: ".$e->getMessage();
                }
            }
        }
    }
}

// ── Stats ─────────────────────────────────────────────────────────────────────
$commission_stats = $conn->query("SELECT
    COUNT(*) as total_txns,
    COALESCE(SUM(CASE WHEN type='credit' AND status='success' THEN amount ELSE 0 END),0) as total_earned,
    COALESCE(SUM(CASE WHEN type='debit' THEN amount ELSE 0 END),0) as total_withdrawn,
    COALESCE(SUM(CASE WHEN type='credit' AND status='success' AND DATE(created_at)=CURDATE() THEN amount ELSE 0 END),0) as today_earned
    FROM wallet_transactions WHERE user_id={$uid} AND wallet_type='super_admin'")->fetch_assoc();

// ── Bank accounts ─────────────────────────────────────────────────────────────
$bank_accounts = $conn->query("SELECT * FROM bank_accounts WHERE owner_type='super_admin' AND user_id={$uid} ORDER BY is_default DESC, created_at DESC");

// ── Own commission transactions ───────────────────────────────────────────────
$txn_filter = $_GET['txn'] ?? 'all';
$txn_q = "SELECT * FROM wallet_transactions WHERE user_id={$uid} AND wallet_type='super_admin'";
if ($txn_filter === 'credit') $txn_q .= " AND type='credit'";
if ($txn_filter === 'debit')  $txn_q .= " AND type='debit'";
$txn_q .= " ORDER BY created_at DESC LIMIT 50";
$transactions = $conn->query($txn_q);

// ── Withdrawals ───────────────────────────────────────────────────────────────
$my_withdrawals = $conn->query("SELECT wd.*,ba.bank_name,ba.account_name,ba.account_number FROM withdrawals wd LEFT JOIN bank_accounts ba ON wd.bank_account_id=ba.id WHERE wd.user_id={$uid} AND wd.wallet_type='super_admin' ORDER BY wd.created_at DESC LIMIT 20");

// ── TODAY'S PLATFORM TRANSACTIONS ─────────────────────────────────────────────
// All customer debits + all restaurant credits today
$daily_tab   = $_GET['daily'] ?? 'customers';
$daily_date  = $_GET['date']  ?? date('Y-m-d');

// Total orders today, total order value today, number of active restaurants today
$platform_today = $conn->query("SELECT
    COUNT(DISTINCT o.id)           as orders_today,
    COALESCE(SUM(o.total_amount),0) as revenue_today,
    COUNT(DISTINCT o.restaurant_id) as restaurants_active
    FROM orders o WHERE DATE(o.created_at)='{$daily_date}' AND o.payment_status='paid'")->fetch_assoc();

// Customer debits today
$cust_daily = $conn->query(
    "SELECT wt.*, u.name as customer_name, u.email as customer_email,
            r.name as restaurant_name
     FROM wallet_transactions wt
     LEFT JOIN users u  ON wt.user_id = u.id
     LEFT JOIN orders o ON wt.order_id = o.id
     LEFT JOIN restaurants r ON o.restaurant_id = r.id
     WHERE wt.wallet_type='customer' AND wt.type='debit'
       AND DATE(wt.created_at)='{$daily_date}'
     ORDER BY wt.created_at DESC"
);

// Restaurant credits today
$rest_daily = $conn->query(
    "SELECT wt.*, r.name as restaurant_name, u.name as owner_name
     FROM wallet_transactions wt
     LEFT JOIN restaurants r ON wt.restaurant_id = r.id
     LEFT JOIN users u ON r.created_by = u.id
     WHERE wt.wallet_type='restaurant' AND wt.type='credit'
       AND DATE(wt.created_at)='{$daily_date}'
     ORDER BY wt.created_at DESC"
);

// Paystack banks
$ps_banks = [];
$ch = curl_init('https://api.paystack.co/bank?currency=NGN&perPage=100');
curl_setopt_array($ch,[CURLOPT_RETURNTRANSFER=>true,CURLOPT_HTTPHEADER=>['Authorization: Bearer '.$PAYSTACK_SECRET_KEY]]);
$banks_resp = json_decode(curl_exec($ch),true); curl_close($ch);
if (!empty($banks_resp['data'])) $ps_banks = $banks_resp['data'];
if (empty($ps_banks)) {
    $ps_banks=[['code'=>'044','name'=>'Access Bank'],['code'=>'050','name'=>'EcoBank'],['code'=>'070','name'=>'Fidelity Bank'],
               ['code'=>'011','name'=>'First Bank'],['code'=>'214','name'=>'FCMB'],['code'=>'058','name'=>'GTBank'],
               ['code'=>'030','name'=>'Heritage Bank'],['code'=>'082','name'=>'Keystone Bank'],['code'=>'526','name'=>'Moniepoint'],
               ['code'=>'076','name'=>'Polaris Bank'],['code'=>'221','name'=>'Stanbic IBTC'],['code'=>'232','name'=>'Sterling Bank'],
               ['code'=>'032','name'=>'Union Bank'],['code'=>'033','name'=>'UBA'],['code'=>'215','name'=>'Unity Bank'],
               ['code'=>'035','name'=>'Wema Bank'],['code'=>'057','name'=>'Zenith Bank'],['code'=>'627','name'=>'Kuda'],
               ['code'=>'090270','name'=>'OPay'],['code'=>'090405','name'=>'PalmPay']];
}
?>

<!-- Page Header -->
<div style="display:flex;align-items:flex-start;justify-content:space-between;margin-bottom:28px;flex-wrap:wrap;gap:16px">
  <div>
    <h1 style="font-size:1.5rem;font-weight:800;letter-spacing:-.03em;margin-bottom:4px">Platform Wallet</h1>
    <p style="color:var(--text-muted);font-size:.875rem">Your <?php echo $commission_rate; ?>% commission accumulates here from every customer order</p>
  </div>
  <div style="display:flex;gap:10px;flex-wrap:wrap">
    <?php if($bank_accounts->num_rows > 0): ?>
    <button class="btn btn-primary btn-md" onclick="openModal('withdrawModal')">
      <svg viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round"><path d="M12 5v14m-7-7l7 7 7-7"/></svg>
      Withdraw Funds
    </button>
    <?php endif; ?>
    <button class="btn btn-secondary btn-md" onclick="openModal('addBankModal')">
      <svg viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round"><path d="M12 5v14M5 12h14"/></svg>
      Add Bank Account
    </button>
  </div>
</div>

<?php if($success): ?>
<div class="alert alert-success" style="margin-bottom:20px">
  <svg viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round"><path d="M22 11.08V12a10 10 0 11-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>
  <?php echo htmlspecialchars($success); ?>
</div>
<?php endif; ?>
<?php if($error): ?>
<div class="alert alert-error" style="margin-bottom:20px">
  <svg viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/></svg>
  <?php echo htmlspecialchars($error); ?>
</div>
<?php endif; ?>

<!-- Wallet Balance Hero -->
<div style="background:linear-gradient(135deg,#225AE3 0%,#4f79ea 60%,#7c9ef0 100%);border-radius:20px;padding:28px 32px;margin-bottom:24px;position:relative;overflow:hidden">
  <div style="position:absolute;top:-20px;right:-20px;width:160px;height:160px;background:rgba(255,255,255,.07);border-radius:50%"></div>
  <div style="position:absolute;bottom:-40px;left:40%;width:200px;height:200px;background:rgba(255,255,255,.04);border-radius:50%"></div>
  <div style="position:relative;z-index:1">
    <div style="display:flex;align-items:flex-start;justify-content:space-between;flex-wrap:wrap;gap:16px">
      <div>
        <div style="font-size:.72rem;font-weight:700;text-transform:uppercase;letter-spacing:.12em;color:rgba(255,255,255,.7);margin-bottom:8px">Commission Balance</div>
        <div style="font-size:2.6rem;font-weight:800;color:#fff;letter-spacing:-.04em;margin-bottom:4px">
          ₦<?php echo number_format($wallet_balance, 2); ?>
        </div>
        <div style="font-size:.8rem;color:rgba(255,255,255,.65)">
          Super Admin Wallet &bull; <?php echo $commission_rate; ?>% of every order
        </div>
      </div>
      <div style="background:rgba(255,255,255,.15);border-radius:14px;padding:14px 20px;backdrop-filter:blur(8px);text-align:center">
        <div style="font-size:.65rem;font-weight:600;color:rgba(255,255,255,.7);text-transform:uppercase;letter-spacing:.1em;margin-bottom:4px">Today's Commission</div>
        <div style="font-size:1.4rem;font-weight:800;color:#fff">+₦<?php echo number_format($commission_stats['today_earned'], 2); ?></div>
      </div>
    </div>
    <div style="display:flex;gap:16px;margin-top:22px;flex-wrap:wrap">
      <div style="background:rgba(255,255,255,.12);border-radius:12px;padding:12px 18px;flex:1;min-width:110px">
        <div style="font-size:.63rem;font-weight:700;color:rgba(255,255,255,.65);text-transform:uppercase;letter-spacing:.1em;margin-bottom:4px">Total Earned</div>
        <div style="font-size:1rem;font-weight:800;color:#fff">₦<?php echo number_format($commission_stats['total_earned'],0); ?></div>
      </div>
      <div style="background:rgba(255,255,255,.12);border-radius:12px;padding:12px 18px;flex:1;min-width:110px">
        <div style="font-size:.63rem;font-weight:700;color:rgba(255,255,255,.65);text-transform:uppercase;letter-spacing:.1em;margin-bottom:4px">Total Withdrawn</div>
        <div style="font-size:1rem;font-weight:800;color:#fff">₦<?php echo number_format($commission_stats['total_withdrawn'],0); ?></div>
      </div>
      <div style="background:rgba(255,255,255,.12);border-radius:12px;padding:12px 18px;flex:1;min-width:110px">
        <div style="font-size:.63rem;font-weight:700;color:rgba(255,255,255,.65);text-transform:uppercase;letter-spacing:.1em;margin-bottom:4px">Transactions</div>
        <div style="font-size:1rem;font-weight:800;color:#fff"><?php echo number_format($commission_stats['total_txns']); ?></div>
      </div>
      <div style="background:rgba(255,255,255,.12);border-radius:12px;padding:12px 18px;flex:1;min-width:110px">
        <div style="font-size:.63rem;font-weight:700;color:rgba(255,255,255,.65);text-transform:uppercase;letter-spacing:.1em;margin-bottom:4px">Orders Today</div>
        <div style="font-size:1rem;font-weight:800;color:#fff"><?php echo $platform_today['orders_today']; ?></div>
      </div>
    </div>
  </div>
</div>

<!-- Bank Accounts + Withdrawals -->
<div style="display:grid;grid-template-columns:1fr 1fr;gap:20px;margin-bottom:24px">

  <!-- Bank Accounts -->
  <div class="card">
    <div class="card-header">
      <h3>Bank Accounts</h3>
      <button class="btn btn-sm btn-secondary" onclick="openModal('addBankModal')">+ Add</button>
    </div>
    <?php $bank_accounts->data_seek(0); if ($bank_accounts->num_rows === 0): ?>
    <div style="padding:40px;text-align:center;color:var(--text-muted)">
      <svg width="38" height="38" viewBox="0 0 24 24" fill="none" stroke="var(--border)" stroke-width="1.5" stroke-linecap="round" style="margin:0 auto 10px;display:block"><path d="M3 9l9-7 9 7v11a2 2 0 01-2 2H5a2 2 0 01-2-2z"/></svg>
      <p style="font-size:.84rem;font-weight:600;margin-bottom:4px">No bank accounts yet</p>
      <p style="font-size:.78rem">Add one to enable withdrawals</p>
    </div>
    <?php else: while($ba=$bank_accounts->fetch_assoc()): ?>
    <div style="display:flex;align-items:center;gap:12px;padding:14px 20px;border-bottom:1px solid var(--border)">
      <div style="width:38px;height:38px;border-radius:10px;background:var(--primary-bg);display:flex;align-items:center;justify-content:center;flex-shrink:0">
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="var(--primary)" stroke-width="2" stroke-linecap="round"><path d="M3 9l9-7 9 7v11a2 2 0 01-2 2H5a2 2 0 01-2-2z"/></svg>
      </div>
      <div style="flex:1;min-width:0">
        <div style="font-size:.84rem;font-weight:700"><?php echo htmlspecialchars($ba['account_name']); ?></div>
        <div style="font-size:.73rem;color:var(--text-muted)"><?php echo htmlspecialchars($ba['bank_name']); ?> &bull; <?php echo htmlspecialchars($ba['account_number']); ?></div>
      </div>
      <div style="display:flex;gap:5px;align-items:center">
        <?php if($ba['is_default']): ?>
          <span class="badge badge-success" style="font-size:.63rem">Default</span>
        <?php else: ?>
          <form method="POST" style="display:inline">
            <input type="hidden" name="action" value="set_default_bank">
            <input type="hidden" name="bank_account_id" value="<?php echo $ba['id']; ?>">
            <button type="submit" class="btn btn-sm btn-secondary" style="font-size:.68rem;padding:4px 8px">Set Default</button>
          </form>
        <?php endif; ?>
        <form method="POST" style="display:inline" onsubmit="return confirm('Remove this bank account?')">
          <input type="hidden" name="action" value="delete_bank">
          <input type="hidden" name="bank_account_id" value="<?php echo $ba['id']; ?>">
          <button type="submit" class="btn btn-danger btn-sm" style="padding:4px 8px">✕</button>
        </form>
      </div>
    </div>
    <?php endwhile; endif; ?>
  </div>

  <!-- Recent Withdrawals -->
  <div class="card">
    <div class="card-header"><h3>Recent Withdrawals</h3></div>
    <?php if ($my_withdrawals->num_rows === 0): ?>
    <div style="padding:40px;text-align:center;color:var(--text-muted);font-size:.84rem">No withdrawals yet.</div>
    <?php else: while($w=$my_withdrawals->fetch_assoc()):
      $sc=['success'=>'badge-success','pending'=>'badge-warning','failed'=>'badge-error'];
    ?>
    <div style="display:flex;align-items:center;gap:12px;padding:12px 20px;border-bottom:1px solid var(--border)">
      <div style="flex:1;min-width:0">
        <div style="font-size:.84rem;font-weight:700">₦<?php echo number_format($w['amount'],2); ?></div>
        <div style="font-size:.7rem;color:var(--text-muted)"><?php echo htmlspecialchars($w['bank_name']??'—'); ?> &bull; <?php echo date('M j, Y',strtotime($w['created_at'])); ?></div>
      </div>
      <span class="badge <?php echo $sc[$w['status']]??'badge-muted'; ?>"><?php echo ucfirst($w['status']); ?></span>
    </div>
    <?php endwhile; endif; ?>
  </div>

</div>

<!-- ── DAILY PLATFORM TRANSACTIONS ─────────────────────────────────────────── -->
<div class="card" style="margin-bottom:24px">
  <div class="card-header">
    <h3>Daily Platform Transactions</h3>
    <div style="display:flex;align-items:center;gap:8px">
      <input type="date" id="dateFilter" value="<?php echo htmlspecialchars($daily_date); ?>"
             onchange="window.location='?daily=<?php echo $daily_tab; ?>&date='+this.value+'&txn=<?php echo $txn_filter; ?>'"
             class="form-control" style="width:auto;padding:5px 10px;font-size:.8rem;height:34px">
    </div>
  </div>

  <!-- Summary row -->
  <div style="display:grid;grid-template-columns:repeat(3,1fr);gap:0;border-bottom:1px solid var(--border)">
    <div style="padding:16px 20px;text-align:center;border-right:1px solid var(--border)">
      <div style="font-size:.68rem;font-weight:700;text-transform:uppercase;letter-spacing:.08em;color:var(--text-muted);margin-bottom:4px">Orders</div>
      <div style="font-size:1.4rem;font-weight:800;color:var(--primary)"><?php echo $platform_today['orders_today']; ?></div>
    </div>
    <div style="padding:16px 20px;text-align:center;border-right:1px solid var(--border)">
      <div style="font-size:.68rem;font-weight:700;text-transform:uppercase;letter-spacing:.08em;color:var(--text-muted);margin-bottom:4px">Total Revenue</div>
      <div style="font-size:1.4rem;font-weight:800;color:var(--success)">₦<?php echo number_format($platform_today['revenue_today'],0); ?></div>
    </div>
    <div style="padding:16px 20px;text-align:center">
      <div style="font-size:.68rem;font-weight:700;text-transform:uppercase;letter-spacing:.08em;color:var(--text-muted);margin-bottom:4px">Active Restaurants</div>
      <div style="font-size:1.4rem;font-weight:800;color:var(--warning)"><?php echo $platform_today['restaurants_active']; ?></div>
    </div>
  </div>

  <!-- Tab switcher -->
  <div style="display:flex;gap:0;border-bottom:1px solid var(--border)">
    <a href="?daily=customers&date=<?php echo $daily_date; ?>&txn=<?php echo $txn_filter; ?>"
       style="flex:1;padding:12px 20px;text-align:center;font-size:.82rem;font-weight:700;border-bottom:3px solid <?php echo $daily_tab==='customers'?'var(--primary)':'transparent'; ?>;color:<?php echo $daily_tab==='customers'?'var(--primary)':'var(--text-muted)'; ?>;transition:all .2s">
      <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" style="vertical-align:middle;margin-right:5px"><path d="M17 21v-2a4 4 0 00-4-4H5a4 4 0 00-4 4v2"/><circle cx="9" cy="7" r="4"/></svg>
      Customer Payments (<?php echo $cust_daily->num_rows; ?>)
    </a>
    <a href="?daily=restaurants&date=<?php echo $daily_date; ?>&txn=<?php echo $txn_filter; ?>"
       style="flex:1;padding:12px 20px;text-align:center;font-size:.82rem;font-weight:700;border-bottom:3px solid <?php echo $daily_tab==='restaurants'?'var(--primary)':'transparent'; ?>;color:<?php echo $daily_tab==='restaurants'?'var(--primary)':'var(--text-muted)'; ?>;transition:all .2s">
      <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" style="vertical-align:middle;margin-right:5px"><path d="M3 9l9-7 9 7v11a2 2 0 01-2 2H5a2 2 0 01-2-2z"/></svg>
      Restaurant Credits (<?php echo $rest_daily->num_rows; ?>)
    </a>
  </div>

  <?php if ($daily_tab === 'customers'): ?>
  <!-- Customer Payments -->
  <?php if ($cust_daily->num_rows === 0): ?>
  <div style="padding:48px;text-align:center;color:var(--text-muted);font-size:.84rem">No customer payments on <?php echo date('M j, Y', strtotime($daily_date)); ?></div>
  <?php else: ?>
  <div style="overflow-x:auto">
  <table class="data-table">
    <thead><tr><th>Time</th><th>Customer</th><th>Restaurant</th><th>Order #</th><th>Amount</th><th>Commission</th><th>Status</th></tr></thead>
    <tbody>
    <?php while($t=$cust_daily->fetch_assoc()): ?>
    <tr>
      <td style="font-size:.75rem;color:var(--text-muted);white-space:nowrap"><?php echo date('g:i A',strtotime($t['created_at'])); ?></td>
      <td style="font-size:.83rem;font-weight:600"><?php echo htmlspecialchars($t['customer_name']??'Guest'); ?></td>
      <td style="font-size:.82rem"><?php echo htmlspecialchars($t['restaurant_name']??'—'); ?></td>
      <td style="font-weight:700;color:var(--primary)">
        <?php echo $t['order_id'] ? '#'.str_pad($t['order_id'],4,'0',STR_PAD_LEFT) : '—'; ?>
      </td>
      <td style="font-weight:700;color:var(--error)">−₦<?php echo number_format($t['amount'],2); ?></td>
      <td style="font-weight:700;color:var(--success)">+₦<?php echo number_format($t['amount'] * $commission_rate / 100, 2); ?></td>
      <td><span class="badge <?php echo $t['status']==='success'?'badge-success':'badge-warning'; ?>"><?php echo ucfirst($t['status']); ?></span></td>
    </tr>
    <?php endwhile; ?>
    </tbody>
  </table>
  </div>
  <?php endif; ?>

  <?php else: ?>
  <!-- Restaurant Credits -->
  <?php if ($rest_daily->num_rows === 0): ?>
  <div style="padding:48px;text-align:center;color:var(--text-muted);font-size:.84rem">No restaurant credits on <?php echo date('M j, Y', strtotime($daily_date)); ?></div>
  <?php else: ?>
  <div style="overflow-x:auto">
  <table class="data-table">
    <thead><tr><th>Time</th><th>Restaurant</th><th>Order #</th><th>Credited (<?php echo 100-$commission_rate; ?>%)</th><th>Status</th><th>Reference</th></tr></thead>
    <tbody>
    <?php while($t=$rest_daily->fetch_assoc()): ?>
    <tr>
      <td style="font-size:.75rem;color:var(--text-muted);white-space:nowrap"><?php echo date('g:i A',strtotime($t['created_at'])); ?></td>
      <td style="font-size:.83rem;font-weight:600"><?php echo htmlspecialchars($t['restaurant_name']??'—'); ?></td>
      <td style="font-weight:700;color:var(--primary)">
        <?php echo $t['order_id'] ? '#'.str_pad($t['order_id'],4,'0',STR_PAD_LEFT) : '—'; ?>
      </td>
      <td style="font-weight:700;color:var(--success)">+₦<?php echo number_format($t['amount'],2); ?></td>
      <td><span class="badge <?php echo $t['status']==='success'?'badge-success':'badge-warning'; ?>"><?php echo ucfirst($t['status']); ?></span></td>
      <td style="font-size:.7rem;color:var(--text-muted);max-width:130px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap"><?php echo htmlspecialchars($t['reference']??'—'); ?></td>
    </tr>
    <?php endwhile; ?>
    </tbody>
  </table>
  </div>
  <?php endif; ?>
  <?php endif; ?>
</div>

<!-- My Commission Transaction History -->
<div class="card">
  <div class="card-header">
    <h3>My Commission History</h3>
    <div style="display:flex;gap:6px">
      <?php foreach(['all'=>'All','credit'=>'Credits','debit'=>'Debits'] as $k=>$l): ?>
      <a href="?txn=<?php echo $k; ?>&daily=<?php echo $daily_tab; ?>&date=<?php echo $daily_date; ?>"
         class="btn btn-sm <?php echo $txn_filter===$k?'btn-primary':'btn-secondary'; ?>"><?php echo $l; ?></a>
      <?php endforeach; ?>
    </div>
  </div>
  <?php if ($transactions->num_rows === 0): ?>
  <div style="padding:56px;text-align:center;color:var(--text-muted)">
    <svg width="44" height="44" viewBox="0 0 24 24" fill="none" stroke="var(--border)" stroke-width="1.5" stroke-linecap="round" style="margin:0 auto 12px;display:block"><path d="M7 20V4l10 16V4M4 10h16M4 14h16"/></svg>
    <p style="font-weight:700;margin-bottom:4px">No transactions yet</p>
    <p style="font-size:.83rem">Commission will appear here as customers place orders</p>
  </div>
  <?php else: ?>
  <div style="overflow-x:auto">
  <table class="data-table">
    <thead><tr><th>Date</th><th>Type</th><th>Amount</th><th>Description</th><th>Reference</th><th>Status</th></tr></thead>
    <tbody>
    <?php while($t=$transactions->fetch_assoc()):
      $is_credit=$t['type']==='credit';
      $tc=$is_credit?'var(--success)':'var(--error)';
      $sc=['success'=>'badge-success','pending'=>'badge-warning','failed'=>'badge-error'];
    ?>
    <tr>
      <td style="font-size:.78rem;color:var(--text-muted);white-space:nowrap"><?php echo date('M j, Y g:i A',strtotime($t['created_at'])); ?></td>
      <td><span style="font-size:.76rem;font-weight:700;color:<?php echo $tc; ?>;text-transform:uppercase;letter-spacing:.06em"><?php echo $is_credit?'↑ Credit':'↓ Debit'; ?></span></td>
      <td style="font-weight:800;color:<?php echo $tc; ?>"><?php echo $is_credit?'+':'-'; ?>₦<?php echo number_format($t['amount'],2); ?></td>
      <td style="font-size:.82rem;max-width:220px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap"><?php echo htmlspecialchars($t['description']??'—'); ?></td>
      <td style="font-size:.7rem;color:var(--text-muted);max-width:130px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap"><?php echo htmlspecialchars($t['reference']??'—'); ?></td>
      <td><span class="badge <?php echo $sc[$t['status']]??'badge-muted'; ?>"><?php echo ucfirst($t['status']); ?></span></td>
    </tr>
    <?php endwhile; ?>
    </tbody>
  </table>
  </div>
  <?php endif; ?>
</div>

<!-- ── ADD BANK MODAL ─────────────────────────────────────────────────────── -->
<div class="modal-backdrop" id="addBankModal">
  <div class="modal" style="max-width:480px">
    <div class="modal-header">
      <h3>Add Bank Account</h3>
      <button class="modal-close" onclick="closeModal('addBankModal')"><svg viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg></button>
    </div>
    <form method="POST">
      <input type="hidden" name="action" value="add_bank">
      <div class="modal-body">
        <div class="form-group">
          <label>Bank *</label>
          <select name="bank_code" id="bankSelect" class="form-control" required onchange="setBankName(this)">
            <option value="">— Select Bank —</option>
            <?php foreach($ps_banks as $b): ?>
            <option value="<?php echo htmlspecialchars($b['code']); ?>" data-name="<?php echo htmlspecialchars($b['name']); ?>">
              <?php echo htmlspecialchars($b['name']); ?>
            </option>
            <?php endforeach; ?>
          </select>
          <input type="hidden" name="bank_name" id="bankNameHidden">
        </div>
        <div class="form-group">
          <label>Account Number * <span style="font-weight:400;color:var(--text-light)">(10 digits)</span></label>
          <input type="text" name="account_number" class="form-control" placeholder="0123456789"
                 maxlength="10" pattern="\d{10}" required oninput="this.value=this.value.replace(/\D/g,'')">
        </div>
        <div class="form-group" style="margin-bottom:0">
          <label>Account Name *</label>
          <input type="text" name="account_name" class="form-control" placeholder="As it appears on your bank statement" required>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary btn-md" onclick="closeModal('addBankModal')">Cancel</button>
        <button type="submit" class="btn btn-primary btn-md">Save Account</button>
      </div>
    </form>
  </div>
</div>

<!-- ── WITHDRAW MODAL ─────────────────────────────────────────────────────── -->
<div class="modal-backdrop" id="withdrawModal">
  <div class="modal" style="max-width:420px">
    <div class="modal-header">
      <h3>Withdraw Commission</h3>
      <button class="modal-close" onclick="closeModal('withdrawModal')"><svg viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg></button>
    </div>
    <form method="POST">
      <input type="hidden" name="action" value="withdraw">
      <div class="modal-body">

        <!-- Balance display -->
        <div style="background:var(--primary-bg);border:1px solid rgba(34,90,227,.15);border-radius:12px;padding:14px 18px;margin-bottom:20px;display:flex;align-items:center;justify-content:space-between">
          <span style="font-size:.8rem;color:var(--text-muted);font-weight:600">Available Balance</span>
          <span style="font-size:1.1rem;font-weight:800;color:var(--primary)">₦<?php echo number_format($wallet_balance, 2); ?></span>
        </div>

        <!-- Amount — pre-filled with full balance, readonly -->
        <div class="form-group">
          <label>Amount (₦)</label>
          <input type="number" name="amount"
                 class="form-control"
                 value="<?php echo number_format($wallet_balance, 2, '.', ''); ?>"
                 min="500"
                 max="<?php echo floor($wallet_balance); ?>"
                 step="0.01"
                 readonly
                 style="background:var(--bg);cursor:not-allowed;color:var(--primary);font-weight:700;font-size:1.05rem">
          <div style="font-size:.72rem;color:var(--text-muted);margin-top:4px">
            Full balance will be withdrawn &bull; Minimum: ₦500
          </div>
        </div>

        <!-- Bank selector -->
        <div class="form-group" style="margin-bottom:0">
          <label>Pay to Bank Account *</label>
          <select name="bank_account_id" class="form-control" required>
            <option value="">— Select Bank Account —</option>
            <?php
            $bank_accounts->data_seek(0);
            while($ba=$bank_accounts->fetch_assoc()): ?>
            <option value="<?php echo $ba['id']; ?>" <?php echo $ba['is_default']?'selected':''; ?>>
              <?php echo htmlspecialchars($ba['account_name']); ?> — <?php echo htmlspecialchars($ba['bank_name']); ?> (<?php echo htmlspecialchars($ba['account_number']); ?>)
            </option>
            <?php endwhile; ?>
          </select>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary btn-md" onclick="closeModal('withdrawModal')">Cancel</button>
        <button type="submit" class="btn btn-primary btn-md"
                onclick="return confirm('Withdraw ₦<?php echo number_format($wallet_balance,2); ?> to selected bank account?')">
          <svg viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round"><path d="M12 5v14m-7-7l7 7 7-7"/></svg>
          Withdraw
        </button>
      </div>
    </form>
  </div>
</div>

<script>
function setBankName(sel) {
  document.getElementById('bankNameHidden').value = sel.options[sel.selectedIndex].dataset.name || '';
}
<?php if($error && strpos($error,'alance')!==false): ?>
document.addEventListener('DOMContentLoaded',()=>openModal('withdrawModal'));
<?php endif; ?>
</script>

<?php include("includes/footer.php"); ?>
