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

$success = '';
$error   = '';
$action  = $_GET['action'] ?? '';

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

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

    // ─── Add staff ──────────────────────────────────────────────────────
    if ($form_action === 'add') {
        $name        = trim($_POST['name']        ?? '');
        $email       = trim($_POST['email']       ?? '');
        $phone       = trim($_POST['phone']       ?? '');
        $employee_id = trim($_POST['employee_id'] ?? '');
        $department  = trim($_POST['department']  ?? '');
        $password    = trim($_POST['password']    ?? '');

        if (!$name || !$email || !$password) {
            $error = "Name, email, and password are required.";
        } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $error = "Invalid email address.";
        } elseif (!preg_match('/^(?=.*[A-Z])(?=.*[a-z])(?=.*\d)(?=.*[^A-Za-z0-9]).{8,}$/', $password)) {
            $error = "Password must be at least 8 characters and include an uppercase letter, a lowercase letter, a number, and a special character.";
        } else {
            // Check email uniqueness
            $chk = $conn->prepare("SELECT id FROM users WHERE email=? LIMIT 1");
            $chk->bind_param("s", $email);
            $chk->execute();
            if ($chk->get_result()->num_rows > 0) {
                $error = "An account with this email already exists.";
            } else {
                require_once __DIR__ . '/includes/org_heal.php';
                dabil_org_heal($conn); // ensure the org_staff role exists so the insert + wallet trigger work
                $hash = password_hash($password, PASSWORD_BCRYPT);
                $ins  = $conn->prepare(
                    "INSERT INTO users (name, email, phone, password, role, organization_id, employee_id, department, status, created_at)
                     VALUES (?, ?, ?, ?, 'org_staff', ?, ?, ?, 1, NOW())"
                );
                $ins->bind_param("ssssiss", $name, $email, $phone, $hash, $org_id, $employee_id, $department);
                if ($ins->execute()) {
                    $new_id = $conn->insert_id;
                    // Make sure the staff wallets exist even if the DB trigger isn't present.
                    @$conn->query("INSERT INTO wallets (user_id, wallet_type, balance, created_at)
                                   SELECT {$new_id},'customer',0.00,NOW() FROM DUAL
                                   WHERE NOT EXISTS (SELECT 1 FROM wallets WHERE user_id={$new_id} AND wallet_type='customer')");
                    @$conn->query("INSERT INTO wallets (user_id, wallet_type, organization_id, balance, created_at)
                                   SELECT {$new_id},'meal_ticket',{$org_id},0.00,NOW() FROM DUAL
                                   WHERE NOT EXISTS (SELECT 1 FROM wallets WHERE user_id={$new_id} AND wallet_type='meal_ticket')");
                    // Notify new staff
                    notify_user($conn, $new_id, null, $org_id, 'org_announcement', 'Welcome to Dabil!', "Your account has been created by {$__org_name}. Log in to access your meal ticket wallet.");
                    $success = "Staff member <strong>" . h($name) . "</strong> has been added successfully.";
                    $action  = '';
                } else {
                    $error = "Failed to create staff account. Please try again.";
                }
            }
        }
    }

    // ─── Suspend / Activate ─────────────────────────────────────────────
    if ($form_action === 'toggle_status') {
        $staff_id = (int)($_POST['staff_id'] ?? 0);
        $new_status = (int)($_POST['new_status'] ?? 0);

        // Verify belongs to this org
        $v = $conn->prepare("SELECT id FROM users WHERE id=? AND organization_id=? AND role='org_staff' LIMIT 1");
        $v->bind_param("ii", $staff_id, $org_id);
        $v->execute();
        if ($v->get_result()->num_rows === 0) {
            $error = "Staff member not found.";
        } else {
            $upd = $conn->prepare("UPDATE users SET status=? WHERE id=? AND organization_id=?");
            $upd->bind_param("iii", $new_status, $staff_id, $org_id);
            $upd->execute();
            $success = "Staff status updated successfully.";
        }
    }

    // ─── Reset password ─────────────────────────────────────────────────
    if ($form_action === 'reset_password') {
        $staff_id    = (int)($_POST['staff_id'] ?? 0);
        $new_password = trim($_POST['new_password'] ?? '');

        if (!preg_match('/^(?=.*[A-Z])(?=.*[a-z])(?=.*\d)(?=.*[^A-Za-z0-9]).{8,}$/', $new_password)) {
            $error = "Password must be at least 8 characters and include an uppercase letter, a lowercase letter, a number, and a special character.";
        } else {
            $v = $conn->prepare("SELECT id FROM users WHERE id=? AND organization_id=? AND role='org_staff' LIMIT 1");
            $v->bind_param("ii", $staff_id, $org_id);
            $v->execute();
            if ($v->get_result()->num_rows === 0) {
                $error = "Staff member not found.";
            } else {
                $hash = password_hash($new_password, 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.";
            }
        }
    }
}

render:

// ─── List staff ─────────────────────────────────────────────────────────
$search = trim($_GET['q'] ?? '');
$filter = $_GET['filter'] ?? 'all'; // all, active, suspended

$where_parts = ["u.organization_id = ?", "u.role = 'org_staff'"];
$bind_types  = "i";
$bind_vals   = [$org_id];

if ($search) {
    $where_parts[] = "(u.name LIKE ? OR u.email LIKE ? OR u.employee_id LIKE ?)";
    $bind_types   .= "sss";
    $like          = "%{$search}%";
    $bind_vals[]   = $like;
    $bind_vals[]   = $like;
    $bind_vals[]   = $like;
}

if ($filter === 'active')    { $where_parts[] = "u.status = 1"; }
if ($filter === 'suspended') { $where_parts[] = "u.status = 0"; }

$where = implode(' AND ', $where_parts);
$sql   = "SELECT u.id, u.name, u.email, u.phone, u.employee_id, u.department, u.status, u.created_at,
                 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 {$where}
          ORDER BY u.created_at DESC";

$stmt = $conn->prepare($sql);
$stmt->bind_param($bind_types, ...$bind_vals);
$stmt->execute();
$staff_list = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);

$total_staff     = count($staff_list);
$active_count    = count(array_filter($staff_list, fn($s) => $s['status'] == 1));
$suspended_count = $total_staff - $active_count;
?>

<div class="anim-up">

<!-- Page header -->
<div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:24px;flex-wrap:wrap;gap:12px">
  <div>
    <h2 style="font-size:1.4rem;font-weight:800;letter-spacing:-.03em">Staff Management</h2>
    <p style="font-size:.84rem;color:var(--text-muted);margin-top:3px"><?php echo number_format($active_count); ?> active · <?php echo number_format($suspended_count); ?> suspended</p>
  </div>
  <button onclick="openModal('addStaffModal')" class="btn btn-org btn-md">
    <svg viewBox="0 0 24 24" stroke-width="2" fill="none" stroke="currentColor" stroke-linecap="round"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
    Add Staff Member
  </button>
</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; ?>

<!-- Filter bar -->
<div class="card card-body" style="padding:14px 18px;margin-bottom:16px">
  <form method="GET" style="display:flex;align-items:center;gap:12px;flex-wrap:wrap">
    <div style="flex:1;min-width:220px;position:relative">
      <svg style="position:absolute;left:12px;top:50%;transform:translateY(-50%);width:15px;height:15px;stroke:var(--text-light);fill:none" viewBox="0 0 24 24" stroke-width="2"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>
      <input type="text" name="q" value="<?php echo h($search); ?>" placeholder="Search name, email, employee ID…"
             class="form-control" style="padding-left:38px">
    </div>
    <select name="filter" class="form-control" style="width:auto;min-width:140px">
      <option value="all"       <?php echo $filter==='all'?'selected':''; ?>>All Staff</option>
      <option value="active"    <?php echo $filter==='active'?'selected':''; ?>>Active Only</option>
      <option value="suspended" <?php echo $filter==='suspended'?'selected':''; ?>>Suspended</option>
    </select>
    <button type="submit" class="btn btn-secondary btn-md">Filter</button>
    <?php if ($search || $filter !== 'all'): ?>
    <a href="staff.php" class="btn btn-secondary btn-md">Clear</a>
    <?php endif; ?>
    <span style="font-size:.82rem;color:var(--text-muted);margin-left:auto"><?php echo number_format($total_staff); ?> result<?php echo $total_staff!==1?'s':''; ?></span>
  </form>
</div>

<!-- Staff table -->
<div class="card">
  <?php if (empty($staff_list)): ?>
  <div style="text-align:center;padding:56px 24px">
    <div style="width:52px;height:52px;background:var(--org-accent-bg);border-radius:50%;display:flex;align-items:center;justify-content:center;margin:0 auto 14px">
      <svg width="24" height="24" viewBox="0 0 24 24" stroke-width="2" fill="none" stroke="var(--org-accent)" stroke-linecap="round"><path d="M17 21v-2a4 4 0 00-4-4H5a4 4 0 00-4 4v2"/><circle cx="9" cy="7" r="4"/></svg>
    </div>
    <p style="font-weight:700;margin-bottom:6px"><?php echo $search ? 'No staff found' : 'No staff members yet'; ?></p>
    <p style="font-size:.82rem;color:var(--text-muted)"><?php echo $search ? 'Try a different search term' : 'Add your first staff member to get started'; ?></p>
    <?php if (!$search): ?>
    <button onclick="openModal('addStaffModal')" class="btn btn-org btn-md" style="margin-top:16px">Add First Staff Member</button>
    <?php endif; ?>
  </div>
  <?php else: ?>
  <div style="overflow-x:auto">
    <table class="data-table">
      <thead>
        <tr>
          <th>Staff Member</th>
          <th>Employee ID</th>
          <th>Department</th>
          <th>Meal Ticket</th>
          <th>Status</th>
          <th>Joined</th>
          <th>Actions</th>
        </tr>
      </thead>
      <tbody>
        <?php foreach ($staff_list as $s): ?>
        <tr>
          <td>
            <div style="display:flex;align-items:center;gap:10px">
              <div style="width:36px;height:36px;border-radius:50%;background:var(--org-accent-bg);display:flex;align-items:center;justify-content:center;font-size:.75rem;font-weight:800;color:var(--org-accent);flex-shrink:0"><?php echo h(initials($s['name'])); ?></div>
              <div>
                <div style="font-weight:700;font-size:.88rem"><?php echo h($s['name']); ?></div>
                <div style="font-size:.75rem;color:var(--text-muted)"><?php echo h($s['email']); ?></div>
              </div>
            </div>
          </td>
          <td style="font-family:monospace;font-size:.8rem;color:var(--text-muted)"><?php echo h($s['employee_id'] ?: '—'); ?></td>
          <td style="font-size:.82rem"><?php echo h($s['department'] ?: '—'); ?></td>
          <td style="font-weight:700;color:var(--success)"><?php echo fmt_money($s['mt_balance']); ?></td>
          <td><?php echo status_badge($s['status']); ?></td>
          <td style="font-size:.8rem;color:var(--text-muted)"><?php echo fmt_date($s['created_at']); ?></td>
          <td>
            <div style="display:flex;gap:6px;align-items:center">
              <a href="staff_view.php?id=<?php echo $s['id']; ?>" class="btn btn-secondary btn-sm">View</a>
              <button onclick="openResetModal(<?php echo $s['id']; ?>, '<?php echo h(addslashes($s['name'])); ?>')" class="btn btn-secondary btn-sm" title="Reset password">
                <svg viewBox="0 0 24 24" stroke-width="2" fill="none" stroke="currentColor" stroke-linecap="round" width="13" height="13"><rect x="3" y="11" width="18" height="11" rx="2"/><path d="M7 11V7a5 5 0 0110 0v4"/></svg>
              </button>
              <form method="POST" style="display:inline" onsubmit="return confirm('<?php echo $s['status'] ? 'Suspend this staff member?' : 'Activate this staff member?'; ?>')">
                <?php echo csrf_field(); ?>
                <input type="hidden" name="form_action" value="toggle_status">
                <input type="hidden" name="staff_id" value="<?php echo $s['id']; ?>">
                <input type="hidden" name="new_status" value="<?php echo $s['status'] ? '0' : '1'; ?>">
                <button type="submit" class="btn btn-sm <?php echo $s['status'] ? 'btn-danger' : 'btn-success'; ?>" title="<?php echo $s['status'] ? 'Suspend' : 'Activate'; ?>">
                  <?php echo $s['status'] ? 'Suspend' : 'Activate'; ?>
                </button>
              </form>
            </div>
          </td>
        </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  </div>
  <?php endif; ?>
</div>

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

<!-- Add Staff Modal -->
<div class="modal-backdrop" id="addStaffModal" <?php echo $action==='add'?'style="display:flex"':''; ?>>
  <div class="modal modal-lg">
    <div class="modal-header">
      <h3>Add Staff Member</h3>
      <button class="modal-close" onclick="closeModal('addStaffModal')">
        <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>
    <form method="POST">
      <?php echo csrf_field(); ?>
      <input type="hidden" name="form_action" value="add">
      <div class="modal-body">
        <?php if ($error && !$success): ?>
        <div class="alert alert-error" style="margin-bottom:16px">
          <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 1fr;gap:16px">
          <div class="form-group" style="grid-column:1/-1">
            <label>Full Name <span style="color:var(--error)">*</span></label>
            <input type="text" name="name" class="form-control" placeholder="John Adeyemi" required value="<?php echo h($_POST['name'] ?? ''); ?>">
          </div>
          <div class="form-group">
            <label>Email Address <span style="color:var(--error)">*</span></label>
            <input type="email" name="email" class="form-control" placeholder="john@example.com" required value="<?php echo h($_POST['email'] ?? ''); ?>">
          </div>
          <div class="form-group">
            <label>Phone Number</label>
            <input type="tel" name="phone" class="form-control" placeholder="+234 800 000 0000" value="<?php echo h($_POST['phone'] ?? ''); ?>">
          </div>
          <div class="form-group">
            <label>Employee ID</label>
            <input type="text" name="employee_id" class="form-control" placeholder="EMP-001" value="<?php echo h($_POST['employee_id'] ?? ''); ?>">
          </div>
          <div class="form-group">
            <label>Department</label>
            <input type="text" name="department" class="form-control" placeholder="Finance, HR, etc." value="<?php echo h($_POST['department'] ?? ''); ?>">
          </div>
          <div class="form-group" style="grid-column:1/-1">
            <label>Initial Password <span style="color:var(--error)">*</span></label>
            <input type="password" name="password" class="form-control" placeholder="Minimum 8 characters" required minlength="8" data-pwmeter>
            <p style="font-size:.74rem;color:var(--text-muted);margin-top:5px">Share this password with the staff member securely. They can change it after logging in.</p>
          </div>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary btn-md" onclick="closeModal('addStaffModal')">Cancel</button>
        <button type="submit" class="btn btn-org btn-md">
          <svg viewBox="0 0 24 24" stroke-width="2" fill="none" stroke="currentColor" stroke-linecap="round" width="15" height="15"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
          Add Staff Member
        </button>
      </div>
    </form>
  </div>
</div>

<!-- Reset Password Modal -->
<div class="modal-backdrop" id="resetPwModal">
  <div class="modal">
    <div class="modal-header">
      <h3>Reset Password</h3>
      <button class="modal-close" onclick="closeModal('resetPwModal')">
        <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>
    <form method="POST">
      <?php echo csrf_field(); ?>
      <input type="hidden" name="form_action" value="reset_password">
      <input type="hidden" name="staff_id" id="resetStaffId">
      <div class="modal-body">
        <p style="margin-bottom:16px;font-size:.88rem">Reset password for <strong id="resetStaffName"></strong></p>
        <div class="form-group">
          <label>New Password <span style="color:var(--error)">*</span></label>
          <input type="password" name="new_password" class="form-control" placeholder="Minimum 8 characters" required minlength="8" data-pwmeter>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary btn-md" onclick="closeModal('resetPwModal')">Cancel</button>
        <button type="submit" class="btn btn-primary btn-md">Reset Password</button>
      </div>
    </form>
  </div>
</div>

<script>
function openResetModal(id, name) {
  document.getElementById('resetStaffId').value = id;
  document.getElementById('resetStaffName').textContent = name;
  openModal('resetPwModal');
}
<?php if ($action === 'add'): ?>
window.addEventListener('load', function(){ openModal('addStaffModal'); });
<?php endif; ?>
</script>

<script src="assets/js/pwmeter.js?v=1"></script>
<?php require_once __DIR__ . '/includes/footer.php'; ?>
