<?php
session_start();
$page_title = 'Fund Staff';
$active_nav = 'fund_staff';
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);

// Pre-select staff if arriving from staff_view
$preselect_staff_id = (int)($_GET['staff_id'] ?? 0);

// Load active staff for dropdown
$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.name ASC"
);
$st->bind_param("i", $org_id);
$st->execute();
$all_staff = $st->get_result()->fetch_all(MYSQLI_ASSOC);

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

    $staff_id = (int)($_POST['staff_id'] ?? 0);
    $amount   = (float)($_POST['amount'] ?? 0);
    $notes    = trim($_POST['notes'] ?? '');

    if (!$staff_id)       { $error = "Please select a staff member."; goto render; }
    if ($amount < 100)    { $error = "Minimum funding amount is ₦100."; goto render; }
    if ($amount > 500000) { $error = "Maximum single funding is ₦500,000."; goto render; }
    if ($amount > $org_balance) {
        $error = "Insufficient wallet balance. Available: " . fmt_money($org_balance) . ", Required: " . 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, [$staff_id], $amount, 'manual_single', $notes);

        // Get staff name for confirmation
        $sn = $conn->prepare("SELECT name FROM users WHERE id=? LIMIT 1");
        $sn->bind_param("i", $staff_id);
        $sn->execute();
        $staff_name = $sn->get_result()->fetch_row()[0] ?? 'Staff';

        $success = "Successfully credited " . fmt_money($amount) . " to <strong>" . h($staff_name) . "</strong>'s meal ticket wallet.";
    } catch (Exception $e) {
        $error = "Funding failed: " . $e->getMessage();
    }
}

render:
?>

<div class="anim-up">

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

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

  <!-- Org wallet balance pill -->
  <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): ?> — Insufficient balance<?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="fund_staff.php" style="text-decoration:underline;font-weight:700">Fund Another</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: ?>

  <div class="card">
    <div class="card-header"><h3>Funding Details</h3></div>
    <div class="card-body">
      <form method="POST" id="fundForm">
        <?php echo csrf_field(); ?>

        <div class="form-group">
          <label>Select Staff Member <span style="color:var(--error)">*</span></label>
          <select name="staff_id" id="staffSelect" class="form-control" required onchange="updatePreview()">
            <option value="">— Choose staff member —</option>
            <?php foreach ($all_staff as $s): ?>
            <option value="<?php echo $s['id']; ?>"
                    data-balance="<?php echo $s['mt_balance']; ?>"
                    data-name="<?php echo h($s['name']); ?>"
                    data-dept="<?php echo h($s['department'] ?: 'No department'); ?>"
                    <?php echo ($preselect_staff_id === $s['id'] || ($_POST['staff_id'] ?? 0) == $s['id']) ? 'selected' : ''; ?>>
              <?php echo h($s['name']); ?><?php if($s['employee_id']): ?> (<?php echo h($s['employee_id']); ?>)<?php endif; ?> — <?php echo fmt_money($s['mt_balance']); ?>
            </option>
            <?php endforeach; ?>
          </select>
        </div>

        <!-- Staff preview card -->
        <div id="staffPreview" style="display:none;background:var(--org-accent-bg);border-radius:12px;padding:14px 16px;margin-bottom:18px;border:1px solid rgba(34,90,227,.15)">
          <div style="display:flex;align-items:center;gap:12px">
            <div style="width:40px;height:40px;border-radius:50%;background:var(--org-accent);display:flex;align-items:center;justify-content:center;font-size:.8rem;font-weight:800;color:#fff;flex-shrink:0" id="previewInitials"></div>
            <div>
              <div style="font-weight:700;font-size:.9rem" id="previewName"></div>
              <div style="font-size:.78rem;color:var(--text-muted)" id="previewDept"></div>
              <div style="font-size:.8rem;font-weight:700;color:var(--org-accent);margin-top:3px">Current: <span id="previewBalance"></span></div>
            </div>
          </div>
        </div>

        <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" name="amount" id="amountInput" class="form-control" style="padding-left:30px"
                   placeholder="0.00" min="100" max="500000" step="0.01"
                   value="<?php echo h($_POST['amount'] ?? ''); ?>"
                   oninput="updatePreview()" required>
          </div>
          <div style="display:flex;gap:8px;margin-top:8px;flex-wrap:wrap">
            <?php foreach ([5000, 10000, 20000, 50000] as $amt): ?>
            <button type="button" onclick="setAmount(<?php echo $amt; ?>)" class="btn btn-secondary btn-sm" style="font-size:.72rem">
              <?php echo fmt_money($amt); ?>
            </button>
            <?php endforeach; ?>
          </div>
        </div>

        <div class="form-group">
          <label>Notes (Optional)</label>
          <textarea name="notes" class="form-control" rows="2" placeholder="e.g. Monthly meal allowance for June…"><?php echo h($_POST['notes'] ?? ''); ?></textarea>
        </div>

        <!-- Amount preview -->
        <div id="amountPreview" style="display:none;background:var(--success-bg);border:1px solid #BBF7D0;border-radius:12px;padding:14px 16px;margin-bottom:18px">
          <div style="font-size:.78rem;font-weight:700;text-transform:uppercase;letter-spacing:.08em;color:var(--success);margin-bottom:6px">Funding Summary</div>
          <div style="font-size:1.4rem;font-weight:800;color:var(--success)" id="summaryAmount"></div>
          <div style="font-size:.8rem;color:var(--text-muted);margin-top:4px">New balance will be: <strong id="summaryNewBalance" style="color:var(--success)"></strong></div>
        </div>

        <div style="display:flex;gap:10px">
          <a href="staff.php" class="btn btn-secondary btn-md">Cancel</a>
          <button type="submit" class="btn btn-org btn-lg" style="flex:1" onclick="return confirm('Confirm funding?')">
            <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 Funding
          </button>
        </div>
      </form>
    </div>
  </div>

  <?php endif; ?>

  <!-- Link to bulk fund -->
  <div style="margin-top:16px;text-align:center;font-size:.82rem;color:var(--text-muted)">
    Need to fund all staff at once?
    <a href="fund_bulk.php" style="color:var(--org-accent);font-weight:700">Use Bulk Fund →</a>
  </div>

</div>
</div>

<script>
function setAmount(v) {
  document.getElementById('amountInput').value = v;
  updatePreview();
}

function initials(name) {
  const p = name.split(' ');
  return (p[0][0] + (p[1] ? p[1][0] : '')).toUpperCase();
}

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

function updatePreview() {
  const sel    = document.getElementById('staffSelect');
  const amt    = parseFloat(document.getElementById('amountInput').value) || 0;
  const opt    = sel.options[sel.selectedIndex];
  const prev   = document.getElementById('staffPreview');
  const aPrev  = document.getElementById('amountPreview');

  if (opt && opt.value) {
    const balance = parseFloat(opt.dataset.balance) || 0;
    document.getElementById('previewInitials').textContent = initials(opt.dataset.name);
    document.getElementById('previewName').textContent     = opt.dataset.name;
    document.getElementById('previewDept').textContent     = opt.dataset.dept;
    document.getElementById('previewBalance').textContent  = fmt(balance);
    prev.style.display = 'block';

    if (amt >= 100) {
      document.getElementById('summaryAmount').textContent   = fmt(amt);
      document.getElementById('summaryNewBalance').textContent = fmt(balance + amt);
      aPrev.style.display = 'block';
    } else {
      aPrev.style.display = 'none';
    }
  } else {
    prev.style.display  = 'none';
    aPrev.style.display = 'none';
  }
}

// Run on page load if pre-selected
window.addEventListener('load', updatePreview);
</script>

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