<?php
ob_start(); // buffer output so header() redirects always work even if an include emits stray whitespace
session_start();

// ── All redirecting actions BEFORE any HTML output ────────────────────────────
include_once("config/db.php");

$allowed = ['restaurant_admin','staff','waiter'];
if (!isset($_SESSION['user_id']) || !in_array($_SESSION['role'] ?? '', $allowed)) {
    header("Location: login.php"); exit;
}

$uid   = (int)$_SESSION['user_id'];
$rid   = (int)($_SESSION['rest_id'] ?? 0);
if (!$rid) { header("Location: login.php"); exit; }

// Load Paystack keys
$_ps_config = 'config/paystack.php';
if (file_exists($_ps_config)) include_once($_ps_config);
// Support both variable and constant style
if (!isset($PAYSTACK_SECRET_KEY)) {
    $PAYSTACK_SECRET_KEY = defined('PAYSTACK_SECRET_KEY') ? PAYSTACK_SECRET_KEY : '';
}

// ── 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 && preg_match('/^\d{10}$/', $acct_number)) {
        // Create Paystack recipient
        $recipient_code = '';
        if ($PAYSTACK_SECRET_KEY) {
            $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 = json_decode(curl_exec($ch), true);
            curl_close($ch);
            if (!empty($ps['data']['recipient_code'])) $recipient_code = $ps['data']['recipient_code'];
        }
        $is_default = ($conn->query("SELECT COUNT(*) FROM bank_accounts WHERE owner_type='restaurant' AND restaurant_id={$rid}")->fetch_row()[0] == 0) ? 1 : 0;
        $ins = $conn->prepare("INSERT INTO bank_accounts (owner_type,restaurant_id,bank_name,account_name,account_number,bank_code,recipient_code,is_default) VALUES ('restaurant',?,?,?,?,?,?,?)");
        $ins->bind_param("isssssi", $rid, $bank_name, $acct_name, $acct_number, $bank_code, $recipient_code, $is_default);
        $ins->execute();
    }
    header("Location: wallet.php?msg=bank_added"); exit;
}

// ── 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='restaurant' AND restaurant_id=?");
    $del->bind_param("ii", $ba_id, $rid); $del->execute();
    header("Location: wallet.php?msg=bank_deleted"); exit;
}

// ── Handle: Set Default Bank Account ─────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'set_default') {
    $ba_id = (int)($_POST['bank_account_id'] ?? 0);
    $conn->query("UPDATE bank_accounts SET is_default=0 WHERE owner_type='restaurant' AND restaurant_id={$rid}");
    $upd = $conn->prepare("UPDATE bank_accounts SET is_default=1 WHERE id=? AND owner_type='restaurant' AND restaurant_id=?");
    $upd->bind_param("ii", $ba_id, $rid); $upd->execute();
    header("Location: wallet.php?msg=default_set"); exit;
}

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

    // Get current wallet balance
    $wb = $conn->query("SELECT balance FROM wallets WHERE restaurant_id={$rid} AND wallet_type='restaurant' LIMIT 1")->fetch_row();
    $wallet_balance = $wb ? (float)$wb[0] : 0.00;

    $wd_error = '';
    if ($amount < 500)                { $wd_error = 'Minimum withdrawal is ₦500.'; }
    elseif ($amount > $wallet_balance) { $wd_error = 'Insufficient balance. Available: ₦'.number_format($wallet_balance,2); }
    elseif (!$ba_id)                  { $wd_error = 'Please select a bank account.'; }

    if (!$wd_error) {
        $ba_stmt = $conn->prepare("SELECT * FROM bank_accounts WHERE id=? AND owner_type='restaurant' AND restaurant_id=? LIMIT 1");
        $ba_stmt->bind_param("ii", $ba_id, $rid); $ba_stmt->execute();
        $ba = $ba_stmt->get_result()->fetch_assoc();

        if (!$ba) {
            $wd_error = 'Bank account not found.';
        } else {
            $recipient_code = $ba['recipient_code'];

            // Try to get recipient code if missing
            if (!$recipient_code && $PAYSTACK_SECRET_KEY) {
                $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 = json_decode(curl_exec($ch), true);
                curl_close($ch);
                if (!empty($ps['data']['recipient_code'])) {
                    $recipient_code = $ps['data']['recipient_code'];
                    $conn->query("UPDATE bank_accounts SET recipient_code='{$recipient_code}' WHERE id={$ba_id}");
                }
            }

            if (!$recipient_code) {
                $wd_error = 'Could not verify bank account with Paystack. Please re-add it.';
            }
        }
    }

    if (!$wd_error) {
        $ref         = 'WD_REST_'.$rid.'_'.time();
        $amount_kobo = (int)($amount * 100);

        // Initiate Paystack transfer
        $transfer_code = '';
        $ps_ok         = false;
        if ($PAYSTACK_SECRET_KEY) {
            $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'=>'Restaurant wallet 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 {
            // Deduct from restaurant wallet
            $conn->query("UPDATE wallets SET balance=balance-{$amount}, updated_at=NOW() WHERE restaurant_id={$rid} AND wallet_type='restaurant'");

            // Wallet transaction record
            $wt_status = $ps_ok ? 'success' : 'pending';
            $wt = $conn->prepare("INSERT INTO wallet_transactions (user_id, wallet_type, restaurant_id, amount, type, reference, description, status) VALUES (?, 'restaurant', ?, ?, 'debit', ?, 'Withdrawal to bank account', ?)");
            $wt->bind_param("iidss", $uid, $rid, $amount, $ref, $wt_status); $wt->execute();

            // Withdrawal record
            $wr = $conn->prepare("INSERT INTO withdrawals (user_id, wallet_type, restaurant_id, amount, reference, recipient_code, transfer_code, bank_account_id, status) VALUES (?, 'restaurant', ?, ?, ?, ?, ?, ?, ?)");
            $wd_status = $ps_ok ? 'success' : 'pending';
            $wr->bind_param("iidsssis", $uid, $rid, $amount, $ref, $recipient_code, $transfer_code, $ba_id, $wd_status);
            $wr->execute();

            $conn->commit();
            header("Location: wallet.php?msg=withdrawn&amount=".urlencode(number_format($amount,2))); exit;
        } catch (Exception $e) {
            $conn->rollback();
            header("Location: wallet.php?msg=wd_failed"); exit;
        }
    } else {
        // Pass error through URL
        header("Location: wallet.php?msg=wd_error&err=".urlencode($wd_error)); exit;
    }
}

// ── Safe to output HTML now ───────────────────────────────────────────────────
$page_title = htmlspecialchars($__rest_name) . ' Wallet';
$active_nav = 'wallet';
include("includes/header.php");
// header.php sets: $uid, $__rid, $__rest_name, $is_admin, $conn

// Use $__rid from header if available (it may differ from session in edge cases)
$rid = $__rid ?? $rid;

// Flash messages
$success = $error = '';
$msg = $_GET['msg'] ?? '';
if ($msg === 'bank_added')   $success = 'Bank account added successfully!';
if ($msg === 'bank_deleted') $success = 'Bank account removed.';
if ($msg === 'default_set')  $success = 'Default bank account updated.';
if ($msg === 'withdrawn')    $success = 'Withdrawal of ₦'.htmlspecialchars($_GET['amount'] ?? '').' initiated successfully!';
if ($msg === 'wd_failed')    $error   = 'Withdrawal failed. Please try again.';
if ($msg === 'wd_error')     $error   = htmlspecialchars($_GET['err'] ?? 'Withdrawal error.');
if ($msg === 'bank_error')   $error   = 'Please fill all bank account fields correctly.';

// Ensure restaurant wallet exists
$wb = $conn->query("SELECT balance FROM wallets WHERE restaurant_id={$rid} AND wallet_type='restaurant' LIMIT 1")->fetch_row();
if (!$wb) {
    $conn->query("INSERT INTO wallets (user_id, wallet_type, restaurant_id, balance) VALUES ({$rid}, 'restaurant', {$rid}, 0.00)");
    $wallet_balance = 0.00;
} else {
    $wallet_balance = (float)$wb[0];
}

// Stats
$stats = $conn->query("SELECT
    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,
    COUNT(*) as total_txns
    FROM wallet_transactions WHERE restaurant_id={$rid} AND wallet_type='restaurant'")->fetch_assoc();

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

// Recent 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.restaurant_id={$rid} AND wd.wallet_type='restaurant' ORDER BY wd.created_at DESC LIMIT 15");

// Transactions
$txn_filter  = $_GET['txn'] ?? 'all';
$txn_q       = "SELECT * FROM wallet_transactions WHERE restaurant_id={$rid} AND wallet_type='restaurant'";
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);

// Fetch Paystack banks list
$ps_banks = [];
if (!empty($PAYSTACK_SECRET_KEY)) {
    $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'];
}
// Fallback Nigerian banks if API unavailable
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'=>'Guaranty Trust Bank'],
        ['code'=>'030','name'=>'Heritage Bank'],['code'=>'082','name'=>'Keystone Bank'],
        ['code'=>'526','name'=>'Moniepoint'],['code'=>'076','name'=>'Polaris Bank'],
        ['code'=>'221','name'=>'Stanbic IBTC Bank'],['code'=>'232','name'=>'Sterling Bank'],
        ['code'=>'032','name'=>'Union Bank'],['code'=>'033','name'=>'United Bank for Africa'],
        ['code'=>'215','name'=>'Unity Bank'],['code'=>'035','name'=>'Wema Bank'],
        ['code'=>'057','name'=>'Zenith Bank'],['code'=>'627','name'=>'Kuda Bank'],
        ['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.4rem;font-weight:800;letter-spacing:-.03em;margin-bottom:3px"><?php echo htmlspecialchars($__rest_name); ?> Wallet</h1>
    <p style="color:var(--text-muted);font-size:.875rem"><?php echo htmlspecialchars($__rest_name); ?> — wallet balance &amp; withdrawals</p>
  </div>
  <?php if ($is_admin): ?>
  <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>
  <?php endif; ?>
</div>

<?php if ($success): ?>
<div class="alert alert-success"><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 $success; ?></div>
<?php endif; ?>
<?php if ($error): ?>
<div class="alert alert-error"><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 $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">Available 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,.6)"><?php echo htmlspecialchars($__rest_name); ?> Wallet </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 Earnings</div>
        <div style="font-size:1.35rem;font-weight:800;color:#fff">+₦<?php echo number_format($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:.62rem;font-weight:700;color:rgba(255,255,255,.65);text-transform:uppercase;letter-spacing:.1em;margin-bottom:4px">Total Received</div>
        <div style="font-size:1rem;font-weight:800;color:#fff">₦<?php echo number_format($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:.62rem;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($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:.62rem;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($stats['total_txns']); ?></div>
      </div>
    </div>
  </div>
</div>

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

  <!-- Bank Accounts -->
  <div class="card">
    <div class="card-header">
      <h3>Bank Accounts</h3>
      <?php if ($is_admin): ?>
      <button class="btn btn-sm btn-secondary" onclick="openModal('addBankModal')">+ Add</button>
      <?php endif; ?>
    </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="40" height="40" 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="M3 9l9-7 9 7v11a2 2 0 01-2 2H5a2 2 0 01-2-2z"/></svg>
        <p style="font-size:.85rem;font-weight:600;margin-bottom:5px">No bank accounts yet</p>
        <p style="font-size:.78rem">Add one to enable withdrawals</p>
      </div>
    <?php else: ?>
      <?php 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="17" height="17" 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:.85rem;font-weight:700"><?php echo htmlspecialchars($ba['account_name']); ?></div>
          <div style="font-size:.74rem;color:var(--text-muted)"><?php echo htmlspecialchars($ba['bank_name']); ?> • <?php echo htmlspecialchars($ba['account_number']); ?></div>
        </div>
        <?php if ($is_admin): ?>
        <div style="display:flex;gap:5px;align-items:center;flex-shrink:0">
          <?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">
              <input type="hidden" name="bank_account_id" value="<?php echo $ba['id']; ?>">
              <button type="submit" class="btn btn-secondary btn-sm" 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;font-size:.75rem">✕</button>
          </form>
        </div>
        <?php endif; ?>
      </div>
      <?php endwhile; ?>
    <?php endif; ?>
  </div>

  <!-- Recent Withdrawals -->
  <div class="card">
    <div class="card-header">
      <h3>Withdrawal History</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: ?>
      <?php 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:.72rem;color:var(--text-muted)"><?php echo htmlspecialchars($w['bank_name'] ?? '—'); ?> • <?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; ?>
    <?php endif; ?>
  </div>

</div>

<!-- Transaction History -->
<div class="card">
  <div class="card-header">
    <h3>Transaction 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; ?>" 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="M12 2v20M17 5H9.5a3.5 3.5 0 000 7h5a3.5 3.5 0 010 7H6"/></svg>
      <p style="font-weight:700;margin-bottom:5px">No transactions yet</p>
      <p style="font-size:.83rem">Earnings from customer orders will appear here</p>
    </div>
  <?php else: ?>
    <div class="table-scroll">
<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 ACCOUNT MODAL ─────────────────────────────────────────────── -->
<div class="modal-backdrop" id="addBankModal">
  <div class="modal" style="max-width:460px">
    <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;text-transform:none;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 Funds</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">
        <div style="background:var(--primary-bg);border:1px solid rgba(34,90,227,.15);border-radius:12px;padding:14px 18px;margin-bottom:22px;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>
        <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:5px">
            Full balance will be withdrawn — Minimum: ₦500
          </div>
        </div>
        <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('Confirm withdrawal 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 || '';
}
// Auto-open withdraw modal if there was a withdrawal error
<?php if ($msg === 'wd_error'): ?>
document.addEventListener('DOMContentLoaded', function(){ openModal('withdrawModal'); });
<?php endif; ?>
</script>

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