<?php
session_start();
$page_title = 'Organisation Wallet';
$active_nav = 'wallet';
require_once __DIR__ . '/includes/header.php';
require_once __DIR__ . '/paystack.php';

// Ensure org wallet exists
ensure_org_wallet($conn, $org_id, $uid);

$balance = get_org_wallet_balance($conn, $org_id);

// Handle messages from verify_payment redirect
$success = !empty($_GET['funded']) ? "Wallet funded successfully! ₦" . number_format((float)($_GET['amount'] ?? 0), 2) . " has been added to your wallet." : '';
$error   = match($_GET['error'] ?? '') {
    'verify_failed'  => 'Payment verification failed. Please contact support if funds were deducted.',
    'already_used'   => 'This payment reference has already been processed.',
    'amount_mismatch'=> 'Payment amount mismatch. Please contact support.',
    default          => ''
};

// Recent org wallet transactions (last 20)
$txns = [];
$t = $conn->prepare(
    "SELECT wt.*, u.name AS actor_name
     FROM wallet_transactions wt
     LEFT JOIN users u ON wt.user_id = u.id
     WHERE wt.organization_id = ? AND wt.wallet_type = 'organization'
     ORDER BY wt.created_at DESC LIMIT 20"
);
$t->bind_param("i", $org_id);
$t->execute();
$txns = $t->get_result()->fetch_all(MYSQLI_ASSOC);

// Totals
$r_funded = $conn->prepare(
    "SELECT COALESCE(SUM(amount),0) FROM wallet_transactions
     WHERE organization_id=? AND wallet_type='organization' AND type='credit'"
);
$r_funded->bind_param("i", $org_id);
$r_funded->execute();
$total_funded = (float)$r_funded->get_result()->fetch_row()[0];

$r_spent = $conn->prepare(
    "SELECT COALESCE(SUM(amount),0) FROM wallet_transactions
     WHERE organization_id=? AND wallet_type='organization' AND type='debit'"
);
$r_spent->bind_param("i", $org_id);
$r_spent->execute();
$total_spent = (float)$r_spent->get_result()->fetch_row()[0];
?>

<div class="anim-up">

<?php if ($success): ?>
<div class="alert alert-success" style="margin-bottom:20px">
  <svg viewBox="0 0 24 24" stroke-width="2"><polyline points="20 6 9 17 4 12"/></svg>
  <?php echo h($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"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg>
  <?php echo $error; ?>
</div>
<?php endif; ?>

<!-- Wallet Balance Banner -->
<div style="background:linear-gradient(135deg,#225AE3 0%,#4f79ea 55%,#7491ee 100%);border-radius:20px;padding:28px 32px;margin-bottom:24px;position:relative;overflow:hidden">
  <div style="position:absolute;top:-24px;right:-16px;width:180px;height:180px;background:rgba(255,255,255,.07);border-radius:50%"></div>
  <div style="position:absolute;bottom:-40px;left:28%;width:200px;height:200px;background:rgba(255,255,255,.05);border-radius:50%"></div>
  <div style="position:relative;z-index:1;display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:20px">
    <div style="display:flex;align-items:center;gap:18px">
      <div style="width:52px;height:52px;background:rgba(255,255,255,.2);border-radius:16px;display:flex;align-items:center;justify-content:center;flex-shrink:0">
        <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#fff" stroke-width="2" stroke-linecap="round"><path d="M21 12V7H5a2 2 0 010-4h15a1 1 0 011 1v4"/><path d="M3 5v14a2 2 0 002 2h16v-5"/><path d="M18 12a2 2 0 000 4h4v-4z"/></svg>
      </div>
      <div>
        <div style="font-size:.72rem;font-weight:700;color:rgba(255,255,255,.7);text-transform:uppercase;letter-spacing:.12em;margin-bottom:4px">Organisation Wallet Balance</div>
        <div style="font-size:2.4rem;font-weight:800;color:#fff;letter-spacing:-.04em;line-height:1"><?php echo fmt_money($balance); ?></div>
        <div style="font-size:.78rem;color:rgba(255,255,255,.65);margin-top:6px"><?php echo h($__org_name); ?></div>
      </div>
    </div>
    <button onclick="openModal('fundWalletModal')" style="background:rgba(255,255,255,.22);border:1.5px solid rgba(255,255,255,.4);color:#fff;border-radius:12px;padding:12px 24px;font-size:.9rem;font-weight:700;cursor:pointer;display:flex;align-items:center;gap:8px;transition:all .2s;font-family:var(--font)" onmouseover="this.style.background='rgba(255,255,255,.32)'" onmouseout="this.style.background='rgba(255,255,255,.22)'">
      <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
      Fund Wallet
    </button>
  </div>
</div>

<!-- Stats Row -->
<div style="display:grid;grid-template-columns:repeat(3,1fr);gap:16px;margin-bottom:24px">
  <div class="card" style="padding:18px 22px;border-top:3px solid var(--org-accent)">
    <div style="font-size:.7rem;font-weight:700;text-transform:uppercase;letter-spacing:.08em;color:var(--text-muted);margin-bottom:8px">Current Balance</div>
    <div style="font-size:1.5rem;font-weight:800;color:var(--org-accent)"><?php echo fmt_money($balance); ?></div>
    <div style="font-size:.75rem;color:var(--text-muted);margin-top:4px">Available to disburse</div>
  </div>
  <div class="card" style="padding:18px 22px;border-top:3px solid var(--success)">
    <div style="font-size:.7rem;font-weight:700;text-transform:uppercase;letter-spacing:.08em;color:var(--text-muted);margin-bottom:8px">Total Funded</div>
    <div style="font-size:1.5rem;font-weight:800;color:var(--success)"><?php echo fmt_money($total_funded); ?></div>
    <div style="font-size:.75rem;color:var(--text-muted);margin-top:4px">All time deposits</div>
  </div>
  <div class="card" style="padding:18px 22px;border-top:3px solid var(--warning)">
    <div style="font-size:.7rem;font-weight:700;text-transform:uppercase;letter-spacing:.08em;color:var(--text-muted);margin-bottom:8px">Total Disbursed</div>
    <div style="font-size:1.5rem;font-weight:800;color:var(--warning)"><?php echo fmt_money($total_spent); ?></div>
    <div style="font-size:.75rem;color:var(--text-muted);margin-top:4px">Sent to staff wallets</div>
  </div>
</div>

<!-- Transaction History -->
<div class="card">
  <div class="card-header">
    <h3>Wallet History</h3>
    <a href="transactions.php" style="font-size:.78rem;color:var(--org-accent);font-weight:600">All Transactions →</a>
  </div>

  <?php if (empty($txns)): ?>
  <div style="text-align:center;padding:56px 24px">
    <div style="width:48px;height:48px;border-radius:50%;background:var(--org-accent-bg);display:flex;align-items:center;justify-content:center;margin:0 auto 14px">
      <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="var(--org-accent)" stroke-width="2" stroke-linecap="round"><path d="M21 12V7H5a2 2 0 010-4h15a1 1 0 011 1v4"/><path d="M3 5v14a2 2 0 002 2h16v-5"/><path d="M18 12a2 2 0 000 4h4v-4z"/></svg>
    </div>
    <p style="font-weight:700;margin-bottom:6px">No transactions yet</p>
    <p style="font-size:.82rem;color:var(--text-muted);margin-bottom:16px">Fund your wallet to get started.</p>
    <button onclick="openModal('fundWalletModal')" class="btn btn-org btn-md">Fund Wallet Now</button>
  </div>
  <?php else: ?>
  <div style="overflow-x:auto">
  <table class="data-table">
    <thead>
      <tr>
        <th>Type</th>
        <th>Description</th>
        <th>Reference</th>
        <th>Amount</th>
        <th>Date</th>
      </tr>
    </thead>
    <tbody>
    <?php foreach ($txns as $tx):
      $is_credit = $tx['type'] === 'credit';
      $color = $is_credit ? 'var(--success)' : 'var(--warning)';
      $bg    = $is_credit ? 'var(--success-bg)' : 'var(--warning-bg)';
      $icon  = $is_credit
        ? 'M12 19V5m0 0l-7 7m7-7l7 7'
        : 'M12 5v14m0 0l7-7m-7 7l-7-7';
    ?>
    <tr>
      <td>
        <div style="display:flex;align-items:center;gap:8px">
          <div style="width:30px;height:30px;border-radius:8px;background:<?php echo $bg; ?>;display:flex;align-items:center;justify-content:center;flex-shrink:0">
            <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="<?php echo $color; ?>" stroke-width="2.5" stroke-linecap="round"><path d="<?php echo $icon; ?>"/></svg>
          </div>
          <span class="badge <?php echo $is_credit ? 'badge-success' : 'badge-warning'; ?>"><?php echo $is_credit ? 'Deposit' : 'Disbursement'; ?></span>
        </div>
      </td>
      <td style="font-size:.83rem;max-width:260px"><?php echo h($tx['description'] ?? '—'); ?></td>
      <td style="font-family:monospace;font-size:.75rem;color:var(--text-muted)"><?php echo h($tx['reference'] ?? '—'); ?></td>
      <td style="font-weight:800;color:<?php echo $color; ?>"><?php echo ($is_credit ? '+' : '−') . fmt_money($tx['amount']); ?></td>
      <td style="font-size:.78rem;color:var(--text-muted);white-space:nowrap"><?php echo fmt_datetime($tx['created_at']); ?></td>
    </tr>
    <?php endforeach; ?>
    </tbody>
  </table>
  </div>
  <?php endif; ?>
</div>

</div><!-- .anim-up -->

<!-- Fund Wallet Modal -->
<div class="modal-backdrop" id="fundWalletModal">
  <div class="modal">
    <div class="modal-header">
      <h3>Fund Organisation Wallet</h3>
      <button class="modal-close" onclick="closeModal('fundWalletModal')">
        <svg viewBox="0 0 24 24" stroke-width="2"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
      </button>
    </div>
    <div class="modal-body">
      <p style="font-size:.85rem;color:var(--text-muted);margin-bottom:20px">
        Add funds to your organisation wallet. You can then use this balance to credit staff meal ticket wallets.
      </p>

      <div class="form-group">
        <label>Amount (₦) <span style="color:var(--error)">*</span></label>
        <div style="position:relative">
          <span style="position:absolute;left:14px;top:50%;transform:translateY(-50%);font-weight:700;color:var(--text-muted)">₦</span>
          <input type="number" id="fundAmount" class="form-control" style="padding-left:30px"
                 placeholder="0.00" min="100" step="0.01" oninput="updateFundPreview()">
        </div>
        <p style="font-size:.73rem;color:var(--text-muted);margin-top:5px">Minimum: ₦100</p>
      </div>

      <!-- Quick amounts -->
      <div style="display:flex;gap:8px;flex-wrap:wrap;margin-bottom:18px">
        <?php foreach ([10000, 25000, 50000, 100000, 250000, 500000] as $amt): ?>
        <button type="button" onclick="setFundAmount(<?php echo $amt; ?>)" class="btn btn-secondary btn-sm" style="font-size:.72rem">
          <?php echo fmt_money($amt); ?>
        </button>
        <?php endforeach; ?>
      </div>

      <!-- Preview -->
      <div id="fundPreview" style="display:none;background:var(--org-accent-bg);border:1px solid rgba(34,90,227,.2);border-radius:12px;padding:14px 16px;margin-bottom:4px">
        <div style="font-size:.72rem;font-weight:700;text-transform:uppercase;letter-spacing:.08em;color:var(--org-accent);margin-bottom:8px">After Funding</div>
        <div style="display:flex;justify-content:space-between;font-size:.84rem;margin-bottom:4px">
          <span style="color:var(--text-muted)">Current Balance</span>
          <span style="font-weight:700"><?php echo fmt_money($balance); ?></span>
        </div>
        <div style="display:flex;justify-content:space-between;font-size:.84rem;margin-bottom:4px">
          <span style="color:var(--text-muted)">You're Adding</span>
          <span style="font-weight:700;color:var(--success)" id="previewAdd">₦0.00</span>
        </div>
        <div style="border-top:1px solid rgba(34,90,227,.2);padding-top:8px;margin-top:4px;display:flex;justify-content:space-between">
          <span style="font-weight:700;color:var(--org-accent)">New Balance</span>
          <span style="font-weight:800;font-size:1.05rem;color:var(--org-accent)" id="previewNew">₦0.00</span>
        </div>
      </div>
    </div>
    <div class="modal-footer">
      <button type="button" class="btn btn-secondary btn-md" onclick="closeModal('fundWalletModal')">Cancel</button>
      <button type="button" id="payBtn" class="btn btn-org btn-md" onclick="initPaystack()" disabled>
        <svg viewBox="0 0 24 24" stroke-width="2" fill="none" stroke="currentColor" stroke-linecap="round" width="15" height="15"><rect x="1" y="4" width="22" height="16" rx="2"/><line x1="1" y1="10" x2="23" y2="10"/></svg>
        Pay with Paystack
      </button>
    </div>
  </div>
</div>

<!-- Hidden form: submitted after Paystack confirms payment -->
<form method="POST" action="verify_payment.php" id="verifyForm">
  <?php echo csrf_field(); ?>
  <input type="hidden" name="reference"      id="psRef">
  <input type="hidden" name="amount_kobo"    id="psAmountKobo">
</form>

<script src="https://js.paystack.co/v1/inline.js"></script>
<script>
const currentBalance = <?php echo $balance; ?>;

function fmt(n) {
  return '₦' + Number(n).toLocaleString('en-NG', {minimumFractionDigits:2, maximumFractionDigits:2});
}

function setFundAmount(v) {
  document.getElementById('fundAmount').value = v;
  updateFundPreview();
}

function updateFundPreview() {
  const amount = parseFloat(document.getElementById('fundAmount').value) || 0;
  const btn    = document.getElementById('payBtn');
  const prev   = document.getElementById('fundPreview');

  if (amount >= 100) {
    document.getElementById('previewAdd').textContent = fmt(amount);
    document.getElementById('previewNew').textContent = fmt(currentBalance + amount);
    prev.style.display = 'block';
    btn.disabled = false;
  } else {
    prev.style.display = 'none';
    btn.disabled = true;
  }
}

function initPaystack() {
  const amount = parseFloat(document.getElementById('fundAmount').value);
  if (!amount || amount < 100) {
    alert('Please enter a minimum amount of ₦100');
    return;
  }

  const amountKobo = Math.round(amount * 100);
  const ref = 'ORG_<?php echo $org_id; ?>_' + Date.now() + '_' + Math.random().toString(36).substr(2, 6).toUpperCase();

  const handler = PaystackPop.setup({
    key:      '<?php echo PAYSTACK_PUBLIC; ?>',
    email:    '<?php echo h($__email); ?>',
    amount:   amountKobo,
    currency: 'NGN',
    ref:      ref,
    metadata: {
      org_id:    <?php echo $org_id; ?>,
      org_name:  '<?php echo h(addslashes($__org_name)); ?>',
      funded_by: <?php echo $uid; ?>,
      type:      'org_wallet_funding'
    },
    callback: function(response) {
      document.getElementById('psRef').value        = response.reference;
      document.getElementById('psAmountKobo').value = amountKobo;
      document.getElementById('verifyForm').submit();
    },
    onClose: function() {
      // User closed popup — do nothing
    }
  });
  handler.openIframe();
}

// Re-open modal if there was a validation error on page load
<?php if (isset($_GET['reopen'])): ?>
window.addEventListener('load', function(){ openModal('fundWalletModal'); });
<?php endif; ?>
</script>

<?php require_once __DIR__ . '/includes/footer.php'; ?>
