<?php
session_start();
$page_title = 'Staff Profile';
$active_nav = 'staff_view';
require_once __DIR__ . '/includes/header.php';

$staff_id = (int)($_GET['id'] ?? 0);
if (!$staff_id) { header("Location: staff.php"); exit; }

// Load staff — must belong to this org
$s = $conn->prepare(
    "SELECT u.*, COALESCE(mt.balance, 0) AS mt_balance, COALESCE(pw.balance, 0) AS personal_balance
     FROM users u
     LEFT JOIN wallets mt ON mt.user_id=u.id AND mt.wallet_type='meal_ticket'
     LEFT JOIN wallets pw ON pw.user_id=u.id AND pw.wallet_type='customer'
     WHERE u.id=? AND u.organization_id=? AND u.role='org_staff'
     LIMIT 1"
);
$s->bind_param("ii", $staff_id, $org_id);
$s->execute();
$staff = $s->get_result()->fetch_assoc();

if (!$staff) { header("Location: staff.php"); exit; }

$page_title = h($staff['name']);

$success = '';
$error   = '';

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

    $form_action = $_POST['form_action'] ?? '';

    if ($form_action === 'toggle_status') {
        $new_status = (int)($_POST['new_status'] ?? 0);
        $upd = $conn->prepare("UPDATE users SET status=? WHERE id=? AND organization_id=?");
        $upd->bind_param("iii", $new_status, $staff_id, $org_id);
        $upd->execute();
        $staff['status'] = $new_status;
        $success = "Staff status updated.";
    }

    if ($form_action === 'reset_password') {
        $new_pw = trim($_POST['new_password'] ?? '');
        if (strlen($new_pw) < 8) {
            $error = "Password must be at least 8 characters.";
        } else {
            $hash = password_hash($new_pw, PASSWORD_BCRYPT);
            $upd  = $conn->prepare("UPDATE users SET password=? WHERE id=? AND organization_id=?");
            $upd->bind_param("sii", $hash, $staff_id, $org_id);
            $upd->execute();
            $success = "Password reset successfully.";
        }
    }

    if ($form_action === 'update_info') {
        $employee_id = trim($_POST['employee_id'] ?? '');
        $department  = trim($_POST['department']  ?? '');
        $phone       = trim($_POST['phone']       ?? '');
        $upd = $conn->prepare("UPDATE users SET employee_id=?, department=?, phone=? WHERE id=? AND organization_id=?");
        $upd->bind_param("sssii", $employee_id, $department, $phone, $staff_id, $org_id);
        $upd->execute();
        $staff['employee_id'] = $employee_id;
        $staff['department']  = $department;
        $staff['phone']       = $phone;
        $success = "Staff profile updated.";
    }
}

render:

// ─── Recent transactions ───────────────────────────────────────────────
$txns = $conn->prepare(
    "SELECT wt.amount, wt.type, wt.wallet_type, wt.description, wt.status, wt.created_at
     FROM wallet_transactions wt
     WHERE wt.user_id=? AND wt.wallet_type='meal_ticket'
     ORDER BY wt.created_at DESC LIMIT 10"
);
$txns->bind_param("i", $staff_id);
$txns->execute();
$transactions = $txns->get_result()->fetch_all(MYSQLI_ASSOC);

// Total funded to this staff
$tf = $conn->prepare(
    "SELECT COALESCE(SUM(amount),0), COUNT(*) FROM wallet_transactions
     WHERE user_id=? AND wallet_type='meal_ticket' AND type='credit'"
);
$tf->bind_param("i", $staff_id);
$tf->execute();
$tf_row = $tf->get_result()->fetch_row();
$total_funded_to_staff = (float)$tf_row[0];
$total_tx_count        = (int)$tf_row[1];
?>

<div class="anim-up">

<!-- Breadcrumb -->
<div style="font-size:.8rem;color:var(--text-muted);margin-bottom:20px">
  <a href="staff.php" style="color:var(--org-accent);font-weight:600">Staff</a>
  <span style="margin:0 8px">›</span>
  <span><?php echo h($staff['name']); ?></span>
</div>

<!-- Top section -->
<div style="display:grid;grid-template-columns:auto 1fr;gap:20px;align-items:start;margin-bottom:24px">
  <div style="width:72px;height:72px;border-radius:50%;background:var(--org-accent);display:flex;align-items:center;justify-content:center;font-size:1.5rem;font-weight:800;color:#fff">
    <?php echo h(initials($staff['name'])); ?>
  </div>
  <div>
    <div style="display:flex;align-items:center;gap:12px;flex-wrap:wrap">
      <h2 style="font-size:1.4rem;font-weight:800;letter-spacing:-.03em"><?php echo h($staff['name']); ?></h2>
      <?php echo status_badge($staff['status']); ?>
    </div>
    <p style="font-size:.85rem;color:var(--text-muted);margin-top:4px"><?php echo h($staff['email']); ?><?php if($staff['phone']): ?> · <?php echo h($staff['phone']); ?><?php endif; ?></p>
    <p style="font-size:.8rem;color:var(--text-muted);margin-top:2px">
      <?php if($staff['employee_id']): ?><span style="font-family:monospace;background:var(--bg);padding:2px 8px;border-radius:6px;margin-right:8px"><?php echo h($staff['employee_id']); ?></span><?php endif; ?>
      <?php if($staff['department']): ?><span><?php echo h($staff['department']); ?></span><?php endif; ?>
    </p>
  </div>
</div>

<?php if ($success): ?>
<div class="alert alert-success"><svg viewBox="0 0 24 24" stroke-width="2"><polyline points="20 6 9 17 4 12"/></svg><?php echo $success; ?></div>
<?php endif; ?>
<?php if ($error): ?>
<div class="alert alert-error"><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; ?>

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

  <div style="display:flex;flex-direction:column;gap:16px">

    <!-- Wallet stats -->
    <div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:14px">
      <div class="stat-card" style="border-top:3px solid var(--org-accent)">
        <div class="stat-label">Meal Ticket Balance</div>
        <div class="stat-value" style="font-size:1.3rem;color:var(--org-accent)"><?php echo fmt_money($staff['mt_balance']); ?></div>
        <div class="stat-sub">Available to spend</div>
      </div>
      <div class="stat-card" style="border-top:3px solid var(--primary)">
        <div class="stat-label">Total Received</div>
        <div class="stat-value" style="font-size:1.3rem;color:var(--primary)"><?php echo fmt_money($total_funded_to_staff); ?></div>
        <div class="stat-sub"><?php echo $total_tx_count; ?> credit<?php echo $total_tx_count!==1?'s':''; ?></div>
      </div>
      <div class="stat-card" style="border-top:3px solid var(--text-muted)">
        <div class="stat-label">Personal Wallet</div>
        <div class="stat-value" style="font-size:1.3rem"><?php echo fmt_money($staff['personal_balance']); ?></div>
        <div class="stat-sub">Self-funded</div>
      </div>
    </div>

    <!-- Transaction history -->
    <div class="card">
      <div class="card-header"><h3>Meal Ticket Transaction History</h3></div>
      <?php if (empty($transactions)): ?>
      <div class="card-body" style="text-align:center;color:var(--text-muted);font-size:.84rem">No transactions yet.</div>
      <?php else: ?>
      <div style="overflow-x:auto">
        <table class="data-table">
          <thead>
            <tr><th>Date</th><th>Description</th><th>Type</th><th>Amount</th><th>Status</th></tr>
          </thead>
          <tbody>
            <?php foreach ($transactions as $t): ?>
            <tr>
              <td style="font-size:.78rem;color:var(--text-muted)"><?php echo fmt_datetime($t['created_at']); ?></td>
              <td style="font-size:.82rem;max-width:220px"><?php echo h($t['description']); ?></td>
              <td><span class="badge <?php echo $t['type']==='credit'?'badge-success':'badge-error'; ?>"><?php echo ucfirst($t['type']); ?></span></td>
              <td style="font-weight:700;color:<?php echo $t['type']==='credit'?'var(--success)':'var(--error)'; ?>">
                <?php echo ($t['type']==='credit'?'+':'−') . fmt_money($t['amount']); ?>
              </td>
              <td><span class="badge badge-muted"><?php echo ucfirst($t['status']); ?></span></td>
            </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>
      <?php endif; ?>
    </div>

  </div>

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

    <!-- Quick fund -->
    <div class="card card-body" style="padding:18px 20px">
      <h3 style="font-size:.88rem;font-weight:700;margin-bottom:12px">Fund Meal Ticket</h3>
      <a href="fund_staff.php?staff_id=<?php echo $staff_id; ?>" class="btn btn-org btn-md btn-block">
        <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>
        Fund <?php echo h(explode(' ', $staff['name'])[0]); ?>
      </a>
    </div>

    <!-- Edit info -->
    <div class="card card-body" style="padding:18px 20px">
      <h3 style="font-size:.88rem;font-weight:700;margin-bottom:12px">Edit Profile Info</h3>
      <form method="POST">
        <?php echo csrf_field(); ?>
        <input type="hidden" name="form_action" value="update_info">
        <div class="form-group">
          <label>Employee ID</label>
          <input type="text" name="employee_id" class="form-control" value="<?php echo h($staff['employee_id'] ?? ''); ?>" placeholder="EMP-001">
        </div>
        <div class="form-group">
          <label>Department</label>
          <input type="text" name="department" class="form-control" value="<?php echo h($staff['department'] ?? ''); ?>" placeholder="Finance, HR…">
        </div>
        <div class="form-group">
          <label>Phone</label>
          <input type="tel" name="phone" class="form-control" value="<?php echo h($staff['phone'] ?? ''); ?>">
        </div>
        <button type="submit" class="btn btn-secondary btn-md btn-block">Save Changes</button>
      </form>
    </div>

    <!-- Password reset -->
    <div class="card card-body" style="padding:18px 20px">
      <h3 style="font-size:.88rem;font-weight:700;margin-bottom:12px">Reset Password</h3>
      <form method="POST">
        <?php echo csrf_field(); ?>
        <input type="hidden" name="form_action" value="reset_password">
        <div class="form-group">
          <label>New Password</label>
          <input type="password" name="new_password" class="form-control" placeholder="Min. 8 characters" minlength="8" required>
        </div>
        <button type="submit" class="btn btn-secondary btn-md btn-block" onclick="return confirm('Reset this staff member\'s password?')">Reset Password</button>
      </form>
    </div>

    <!-- Status toggle -->
    <div class="card card-body" style="padding:18px 20px;border:1px solid <?php echo $staff['status'] ? 'var(--error-bg)' : 'var(--success-bg)'; ?>">
      <h3 style="font-size:.88rem;font-weight:700;margin-bottom:8px;color:<?php echo $staff['status'] ? 'var(--error)' : 'var(--success)'; ?>"><?php echo $staff['status'] ? 'Suspend Account' : 'Activate Account'; ?></h3>
      <p style="font-size:.78rem;color:var(--text-muted);margin-bottom:12px">
        <?php echo $staff['status'] ? 'Suspended staff cannot log in or use their wallet.' : 'Activate to restore login and wallet access.'; ?>
      </p>
      <form method="POST" onsubmit="return confirm('<?php echo $staff['status'] ? 'Suspend this account?' : 'Activate this account?'; ?>')">
        <?php echo csrf_field(); ?>
        <input type="hidden" name="form_action" value="toggle_status">
        <input type="hidden" name="new_status" value="<?php echo $staff['status'] ? '0' : '1'; ?>">
        <button type="submit" class="btn <?php echo $staff['status'] ? 'btn-danger' : 'btn-success'; ?> btn-md btn-block">
          <?php echo $staff['status'] ? '🚫 Suspend Account' : '✅ Activate Account'; ?>
        </button>
      </form>
    </div>

  </div>
</div>

</div>

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