<?php
session_start();
$page_title = 'Bulk Fund';
$active_nav = 'fund_bulk';
require_once __DIR__ . '/includes/header.php';

$success = '';
$error   = '';
$result  = null;

// Ensure org wallet exists and get balance
ensure_org_wallet($conn, $org_id, $uid);
$org_balance = get_org_wallet_balance($conn, $org_id);

// Load all active staff
$all_staff = [];
$st = $conn->prepare(
    "SELECT u.id, u.name, u.email, u.employee_id, u.department, COALESCE(w.balance, 0) AS mt_balance
     FROM users u
     LEFT JOIN wallets w ON w.user_id=u.id AND w.wallet_type='meal_ticket'
     WHERE u.organization_id=? AND u.role='org_staff' AND u.status=1
     ORDER BY u.department, u.name ASC"
);
$st->bind_param("i", $org_id);
$st->execute();
$all_staff = $st->get_result()->fetch_all(MYSQLI_ASSOC);
$staff_count = count($all_staff);

// Group staff by department so organisations can fund a whole department at once.
$by_dept = [];
foreach ($all_staff as $s) {
    $dept = trim((string)($s['department'] ?? '')) !== '' ? $s['department'] : 'Unassigned';
    $by_dept[$dept][] = $s;
}
uksort($by_dept, function ($a, $b) {
    if ($a === 'Unassigned') return 1;
    if ($b === 'Unassigned') return -1;
    return strnatcasecmp($a, $b);
});

// ─── Handle POST ────────────────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!csrf_verify()) { $error = "Security token mismatch."; goto render; }

    $mode         = $_POST['mode'] ?? 'all'; // all | selected
    $amount       = (float)($_POST['amount'] ?? 0);
    $notes        = trim($_POST['notes'] ?? '');
    $selected_ids = array_map('intval', $_POST['staff_ids'] ?? []);

    if ($amount < 100)    { $error = "Minimum amount is ₦100 per staff."; goto render; }
    if ($amount > 500000) { $error = "Maximum is ₦500,000 per staff."; goto render; }

    if ($mode === 'all') {
        $ids = array_column($all_staff, 'id');
    } else {
        $ids = $selected_ids;
    }

    if (empty($ids)) { $error = "Please select at least one staff member."; goto render; }

    $total_required = $amount * count($ids);
    if ($total_required > $org_balance) {
        $error = "Insufficient wallet balance. Available: " . fmt_money($org_balance) . ", Required: " . fmt_money($total_required) . " (" . count($ids) . " staff × " . fmt_money($amount) . "). <a href='wallet.php' style='font-weight:700;text-decoration:underline'>Top up your wallet →</a>";
        goto render;
    }

    try {
        $result = fund_staff_batch($conn, $org_id, $uid, $ids, $amount, 'manual_bulk', $notes);
        $success = sprintf(
            "Batch funding complete. <strong>%d staff</strong> credited %s each. Total disbursed: <strong>%s</strong>.%s",
            $result['funded'],
            fmt_money($amount),
            fmt_money($amount * $result['funded']),
            $result['failed'] > 0 ? " ({$result['failed']} failed — check transactions for details)" : ''
        );
    } catch (Exception $e) {
        $error = "Bulk funding failed: " . $e->getMessage();
    }
}

render:
?>

<div class="anim-up">

<div style="max-width:760px">

  <!-- Page header -->
  <div style="margin-bottom:20px">
    <h2 style="font-size:1.4rem;font-weight:800;letter-spacing:-.03em">Bulk Fund Staff</h2>
    <p style="font-size:.84rem;color:var(--text-muted);margin-top:3px">Credit meal ticket wallets for multiple staff in one batch</p>
  </div>

  <!-- Org wallet balance banner -->
  <div style="display:flex;align-items:center;justify-content:space-between;background:<?php echo $org_balance < 100 ? 'var(--error-bg)' : 'var(--org-accent-bg)'; ?>;border:1px solid <?php echo $org_balance < 100 ? 'rgba(239,68,68,.3)' : 'rgba(34,90,227,.2)'; ?>;border-radius:12px;padding:12px 18px;margin-bottom:20px">
    <div style="display:flex;align-items:center;gap:10px">
      <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="<?php echo $org_balance < 100 ? 'var(--error)' : '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>
      <span style="font-size:.82rem;font-weight:600;color:<?php echo $org_balance < 100 ? 'var(--error)' : 'var(--org-accent)'; ?>">
        Organisation Wallet: <strong><?php echo fmt_money($org_balance); ?></strong>
        <?php if ($org_balance < 100): ?> — Balance too low to fund staff<?php endif; ?>
      </span>
    </div>
    <a href="wallet.php" class="btn btn-sm <?php echo $org_balance < 100 ? 'btn-danger' : 'btn-secondary'; ?>" style="font-size:.72rem">
      <?php echo $org_balance < 100 ? 'Top Up Now →' : 'Manage Wallet'; ?>
    </a>
  </div>

  <?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>
    <span><?php echo $success; ?> <a href="transactions.php" style="text-decoration:underline;font-weight:700">View Transactions →</a></span>
  </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; ?>

  <?php if (empty($all_staff)): ?>
  <div class="card card-body" style="text-align:center;padding:48px 24px">
    <p style="font-weight:700;margin-bottom:6px">No active staff members</p>
    <p style="font-size:.82rem;color:var(--text-muted);margin-bottom:16px">Add staff before funding meal tickets.</p>
    <a href="staff.php?action=add" class="btn btn-org btn-md">Add Staff Member</a>
  </div>
  <?php else: ?>

  <form method="POST" id="bulkForm">
    <?php echo csrf_field(); ?>
    <input type="hidden" name="mode" id="modeInput" value="selected">

    <div style="display:grid;grid-template-columns:1fr 300px;gap:20px;align-items:start">

      <!-- Left: staff selection -->
      <div class="card">
        <div class="card-header">
          <h3>Staff Selection</h3>
          <div style="display:flex;gap:8px">
            <button type="button" onclick="selectAll(true)" class="btn btn-secondary btn-sm">All</button>
            <button type="button" onclick="selectAll(false)" class="btn btn-secondary btn-sm">None</button>
          </div>
        </div>

        <!-- Department filter -->
        <div style="padding:12px 18px;border-bottom:1px solid var(--border);display:flex;gap:10px;align-items:center;flex-wrap:wrap">
          <label style="font-size:.8rem;color:var(--text-muted);font-weight:600">Show:</label>
          <select id="deptFilter" onchange="filterDept()" class="form-control" style="max-width:240px;height:36px;padding:0 10px;font-size:.82rem">
            <option value="__all">All departments (<?php echo $staff_count; ?>)</option>
            <?php foreach ($by_dept as $dept => $rows): ?>
            <option value="<?php echo h($dept); ?>"><?php echo h($dept); ?> (<?php echo count($rows); ?>)</option>
            <?php endforeach; ?>
          </select>
          <span style="font-size:.76rem;color:var(--text-light)">Tick a department row to fund everyone in it.</span>
        </div>

        <!-- Staff list, grouped by department -->
        <div style="max-height:440px;overflow-y:auto">
          <table class="data-table" id="staffTable">
            <thead>
              <tr>
                <th style="width:40px"><input type="checkbox" id="checkAll" onchange="selectAll(this.checked)" checked></th>
                <th>Name</th>
                <th>Department</th>
                <th>Current MT</th>
              </tr>
            </thead>
            <tbody>
              <?php foreach ($by_dept as $dept => $rows): $dk = h($dept); ?>
              <tr class="dept-group" data-dept="<?php echo $dk; ?>" style="background:var(--bg)">
                <td><input type="checkbox" class="dept-cb" data-dept="<?php echo $dk; ?>" onchange="toggleDept(this)" checked></td>
                <td colspan="3" style="font-weight:800;font-size:.82rem;letter-spacing:-.01em">
                  <?php echo $dk; ?> <span style="color:var(--text-muted);font-weight:600">· <?php echo count($rows); ?> staff</span>
                </td>
              </tr>
              <?php foreach ($rows as $s): ?>
              <tr class="staff-row" data-dept="<?php echo $dk; ?>">
                <td>
                  <input type="checkbox" name="staff_ids[]" value="<?php echo $s['id']; ?>"
                         class="staff-cb" data-dept="<?php echo $dk; ?>" checked onchange="onStaffToggle(this)">
                </td>
                <td>
                  <div style="font-weight:600;font-size:.84rem;padding-left:8px"><?php echo h($s['name']); ?></div>
                  <?php if ($s['employee_id']): ?>
                  <div style="font-size:.72rem;color:var(--text-muted);font-family:monospace;padding-left:8px"><?php echo h($s['employee_id']); ?></div>
                  <?php endif; ?>
                </td>
                <td style="font-size:.8rem;color:var(--text-muted)"><?php echo h($s['department'] ?: '—'); ?></td>
                <td style="font-size:.8rem;font-weight:700;color:var(--org-accent)"><?php echo fmt_money($s['mt_balance']); ?></td>
              </tr>
              <?php endforeach; ?>
              <?php endforeach; ?>
            </tbody>
          </table>
        </div>
      </div>

      <!-- Right: amount + summary -->
      <div style="display:flex;flex-direction:column;gap:14px">

        <div class="card card-body" style="padding:18px 20px">
          <div class="form-group">
            <label>Amount Per Staff (₦) <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" name="amount" id="amountInput" class="form-control" style="padding-left:30px"
                     placeholder="0.00" min="100" max="500000" step="0.01"
                     oninput="updateTotals()" required>
            </div>
            <div style="display:flex;gap:6px;margin-top:8px;flex-wrap:wrap">
              <?php foreach ([5000, 10000, 20000, 50000] as $a): ?>
              <button type="button" onclick="setAmount(<?php echo $a; ?>)" class="btn btn-secondary btn-sm" style="font-size:.72rem"><?php echo fmt_money($a); ?></button>
              <?php endforeach; ?>
            </div>
          </div>

          <div class="form-group">
            <label>Notes (Optional)</label>
            <textarea name="notes" class="form-control" rows="2" placeholder="e.g. June 2026 meal allowance…"></textarea>
          </div>
        </div>

        <!-- Live summary -->
        <div class="card card-body" style="padding:18px 20px;background:var(--org-accent-bg);border:1px solid rgba(34,90,227,.15)">
          <div style="font-size:.72rem;font-weight:700;text-transform:uppercase;letter-spacing:.08em;color:var(--org-accent);margin-bottom:12px">Funding Summary</div>

          <div style="display:flex;justify-content:space-between;margin-bottom:8px;font-size:.84rem">
            <span style="color:var(--text-muted)">Wallet Balance</span>
            <span style="font-weight:700;color:var(--org-accent)"><?php echo fmt_money($org_balance); ?></span>
          </div>
          <div style="display:flex;justify-content:space-between;margin-bottom:8px;font-size:.84rem">
            <span style="color:var(--text-muted)">Staff Selected</span>
            <span style="font-weight:700" id="summaryCount"><?php echo $staff_count; ?></span>
          </div>
          <div style="display:flex;justify-content:space-between;margin-bottom:8px;font-size:.84rem">
            <span style="color:var(--text-muted)">Amount Each</span>
            <span style="font-weight:700" id="summaryPerStaff">₦0.00</span>
          </div>
          <div style="border-top:1px solid rgba(34,90,227,.2);padding-top:10px;margin-top:4px;margin-bottom:8px">
            <div style="display:flex;justify-content:space-between;font-size:1rem">
              <span style="font-weight:700;color:var(--org-accent)">Total Disbursement</span>
              <span style="font-size:1.2rem;font-weight:800;color:var(--org-accent)" id="summaryTotal">₦0.00</span>
            </div>
          </div>
          <!-- Remaining balance row — hidden until amount entered -->
          <div id="remainingRow" style="display:none;border-top:1px solid rgba(34,90,227,.15);padding-top:8px">
            <div style="display:flex;justify-content:space-between;font-size:.82rem">
              <span style="color:var(--text-muted)">Remaining Balance</span>
              <span id="summaryRemaining" style="font-weight:700"></span>
            </div>
          </div>
          <!-- Insufficient balance warning -->
          <div id="insufficientWarn" style="display:none;background:var(--error-bg);border:1px solid rgba(239,68,68,.3);border-radius:8px;padding:10px 12px;margin-top:10px;font-size:.78rem;color:var(--error);font-weight:600">
            ⚠ Insufficient wallet balance.
            <a href="wallet.php" style="color:var(--error);text-decoration:underline">Top up wallet →</a>
          </div>
        </div>
        
  



        <button type="submit" class="btn btn-org btn-lg btn-block" onclick="return confirmBulk()" id="submitBtn">
          <svg viewBox="0 0 24 24" stroke-width="2" fill="none" stroke="currentColor" stroke-linecap="round"><path d="M12 2v20M17 5H9.5a3.5 3.5 0 100 7h5a3.5 3.5 0 010 7H6"/></svg>
          Confirm Bulk Funding
        </button>

        <a href="fund_staff.php" style="text-align:center;font-size:.82rem;color:var(--text-muted)">
          Fund a single staff member instead →
        </a>
      </div>

    </div>
  </form>

  <?php endif; ?>

</div>
</div>

<script>
const totalStaff  = <?php echo $staff_count; ?>;
const orgBalance  = <?php echo (float)$org_balance; ?>;

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

function setAmount(v) {
  document.getElementById('amountInput').value = v;
  updateTotals();
}

function selectAll(state) {
  document.querySelectorAll('.staff-cb').forEach(cb => cb.checked = state);
  document.querySelectorAll('.dept-cb').forEach(cb => { cb.checked = state; cb.indeterminate = false; });
  document.getElementById('checkAll').checked = state;
  document.getElementById('checkAll').indeterminate = false;
  updateTotals();
}

// Tick/untick every staff member in a department.
function toggleDept(deptCb) {
  const dept = deptCb.dataset.dept;
  document.querySelectorAll('.staff-cb[data-dept="' + CSS.escape(dept) + '"]').forEach(cb => cb.checked = deptCb.checked);
  deptCb.indeterminate = false;
  syncHeader();
  updateTotals();
}

// After an individual staff toggle, keep the department + master checkboxes in sync.
function onStaffToggle(cb) {
  const dept  = cb.dataset.dept;
  const inDept = document.querySelectorAll('.staff-cb[data-dept="' + CSS.escape(dept) + '"]');
  const checked = document.querySelectorAll('.staff-cb[data-dept="' + CSS.escape(dept) + '"]:checked');
  const deptCb = document.querySelector('.dept-cb[data-dept="' + CSS.escape(dept) + '"]');
  if (deptCb) {
    deptCb.checked = checked.length === inDept.length;
    deptCb.indeterminate = checked.length > 0 && checked.length < inDept.length;
  }
  syncHeader();
  updateTotals();
}

function syncHeader() {
  const all = document.querySelectorAll('.staff-cb');
  const on  = document.querySelectorAll('.staff-cb:checked');
  const head = document.getElementById('checkAll');
  head.checked = on.length === all.length;
  head.indeterminate = on.length > 0 && on.length < all.length;
}

// Show only the chosen department (selection is preserved across filters).
function filterDept() {
  const val = document.getElementById('deptFilter').value;
  document.querySelectorAll('#staffTable tbody tr').forEach(tr => {
    const d = tr.dataset.dept;
    tr.style.display = (val === '__all' || d === val) ? '' : 'none';
  });
}

function selectedCount() {
  return document.querySelectorAll('.staff-cb:checked').length;
}

function updateTotals() {
  const count     = selectedCount();
  const amount    = parseFloat(document.getElementById('amountInput').value) || 0;
  const total     = count * amount;
  const remaining = orgBalance - total;
  const isOver    = total > orgBalance && amount > 0 && count > 0;

  document.getElementById('summaryCount').textContent    = count;
  document.getElementById('summaryPerStaff').textContent = fmt(amount);
  document.getElementById('summaryTotal').textContent    = fmt(total);

  const remRow  = document.getElementById('remainingRow');
  const remSpan = document.getElementById('summaryRemaining');
  const warn    = document.getElementById('insufficientWarn');
  const btn     = document.getElementById('submitBtn');

  if (amount >= 100 && count > 0) {
    remRow.style.display  = 'block';
    remSpan.textContent   = fmt(Math.max(0, remaining));
    remSpan.style.color   = isOver ? 'var(--error)' : 'var(--success)';
    warn.style.display    = isOver ? 'block' : 'none';
    btn.disabled          = isOver;
    btn.style.opacity     = isOver ? '0.5' : '1';
  } else {
    remRow.style.display  = 'none';
    warn.style.display    = 'none';
    btn.disabled          = false;
    btn.style.opacity     = '1';
  }
}

function confirmBulk() {
  const count  = selectedCount();
  const amount = parseFloat(document.getElementById('amountInput').value) || 0;
  if (count === 0 || amount < 100) return false;
  const total = count * amount;
  if (total > orgBalance) { return false; }
  return confirm(`Fund ${count} staff member${count!==1?'s':''} at ${fmt(amount)} each?\n\nTotal disbursement: ${fmt(total)}\nRemaining wallet balance: ${fmt(orgBalance - total)}`);
}

// Init — everyone selected by default (fund all); tweak per department or per staff.
updateTotals();
</script>

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