<?php
session_start();
$page_title = 'Staff Management';
$active_nav = 'staff';
include("includes/header.php");
if (!$is_admin) { header("Location: dashboard.php"); exit; }

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

// Toggle status
if ($action==='toggle'&&isset($_GET['id'])) {
    $sid=(int)$_GET['id'];
    $s=$conn->prepare("UPDATE users SET status=1-status WHERE id=? AND restaurant_id=? AND role IN('staff','waiter')");
    $s->bind_param("ii",$sid,$__rid); $s->execute();
    header("Location: staff.php?msg=toggled"); exit;
}
// Delete
if ($action==='delete'&&isset($_POST['id'])) {
    $sid=(int)$_POST['id'];
    $s=$conn->prepare("DELETE FROM users WHERE id=? AND restaurant_id=? AND role IN('staff','waiter')");
    $s->bind_param("ii",$sid,$__rid); $s->execute();
    header("Location: staff.php?msg=deleted"); exit;
}
// Create / Edit staff
if ($_SERVER['REQUEST_METHOD']==='POST'&&in_array($action,['create','edit'])) {
    $name   =trim($_POST['name']??'');
    $email  =trim($_POST['email']??'');
    $phone  =trim($_POST['phone']??'');
    $role_s =in_array($_POST['role_s']??'',['staff','waiter'])?$_POST['role_s']:'staff';
    $pw     =$_POST['password']??'';
    $sid    =(int)($_POST['staff_id']??0);

    if (!$name||!$email) { $error="Name and email are required."; }
    else {
        if ($action==='create') {
            if (!$pw||strlen($pw)<6) { $error="Password must be at least 6 characters."; }
            else {
                $chk=$conn->prepare("SELECT id FROM users WHERE email=?");
                $chk->bind_param("s",$email); $chk->execute();
                if ($chk->get_result()->num_rows>0) { $error="Email already in use."; }
                else {
                    $hash=password_hash($pw,PASSWORD_DEFAULT);
                    $ins=$conn->prepare("INSERT INTO users(restaurant_id,name,email,phone,password,role,status) VALUES(?,?,?,?,?,?,1)");
                    $ins->bind_param("isssss",$__rid,$name,$email,$phone,$hash,$role_s);
                    $ins->execute();
                    $success="Staff member '{$name}' added successfully.";
                }
            }
        } else {
            $upd=$conn->prepare("UPDATE users SET name=?,email=?,phone=?,role=? WHERE id=? AND restaurant_id=?");
            $upd->bind_param("ssssii",$name,$email,$phone,$role_s,$sid,$__rid); $upd->execute();
            if ($pw&&strlen($pw)>=6) {
                $hash=password_hash($pw,PASSWORD_DEFAULT);
                $p=$conn->prepare("UPDATE users SET password=? WHERE id=? AND restaurant_id=?");
                $p->bind_param("sii",$hash,$sid,$__rid); $p->execute();
            }
            $success="Staff member updated.";
        }
    }
}

$msg=$_GET['msg']??'';
if($msg==='toggled') $success="Status updated.";
if($msg==='deleted') $success="Staff member removed.";

// For edit modal
$edit_staff=null;
if($action==='edit'&&isset($_GET['id'])){
    $s=$conn->prepare("SELECT * FROM users WHERE id=? AND restaurant_id=? AND role IN('staff','waiter')");
    $s->bind_param("ii",(int)$_GET['id'],$__rid); $s->execute();
    $edit_staff=$s->get_result()->fetch_assoc();
}

$search=trim($_GET['search']??'');
$role_f=$_GET['role_f']??'all';

$q="SELECT u.*,(SELECT COUNT(*) FROM orders WHERE assigned_to=u.id) as orders_handled FROM users u WHERE u.restaurant_id=? AND u.role IN('staff','waiter')";
$params=[$__rid]; $types="i";
if($search){$q.=" AND (u.name LIKE ? OR u.email LIKE ?)";$s="%$search%";$params[]=$s;$params[]=$s;$types.="ss";}
if($role_f!=='all'){$q.=" AND u.role=?";$params[]=$role_f;$types.="s";}
$q.=" ORDER BY u.created_at DESC";
$st=$conn->prepare($q); $st->bind_param($types,...$params); $st->execute();
$staff_list=$st->get_result();

$total_staff=$conn->prepare("SELECT COUNT(*) FROM users WHERE restaurant_id=? AND role IN('staff','waiter')"); $total_staff->bind_param("i",$__rid); $total_staff->execute(); $total_staff=$total_staff->get_result()->fetch_row()[0];
$waiters=$conn->prepare("SELECT COUNT(*) FROM users WHERE restaurant_id=? AND role='waiter'"); $waiters->bind_param("i",$__rid); $waiters->execute(); $waiters=$waiters->get_result()->fetch_row()[0];
$staff_only=$conn->prepare("SELECT COUNT(*) FROM users WHERE restaurant_id=? AND role='staff'"); $staff_only->bind_param("i",$__rid); $staff_only->execute(); $staff_only=$staff_only->get_result()->fetch_row()[0];
?>

<div style="display:flex;align-items:flex-start;justify-content:space-between;margin-bottom:24px;flex-wrap:wrap;gap:12px">
  <div>
    <h1 style="font-size:1.4rem;font-weight:800;letter-spacing:-.03em;margin-bottom:3px">Staff Management</h1>
    <p style="color:var(--text-muted);font-size:.85rem">Manage your restaurant team — <?php echo htmlspecialchars($__rest_name); ?></p>
  </div>
  <button class="btn btn-primary btn-md" onclick="openModal('addStaffModal')">
    <svg viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round"><path d="M16 21v-2a4 4 0 00-4-4H6a4 4 0 00-4 4v2"/><circle cx="9" cy="7" r="4"/><line x1="19" y1="8" x2="19" y2="14"/><line x1="22" y1="11" x2="16" y2="11"/></svg>
    Add Staff Member
  </button>
</div>

<!-- Quick Stats -->
<div class="grid-3" style="margin-bottom:24px">
  <div class="card" style="padding:18px 20px;display:flex;align-items:center;gap:14px">
    <div style="width:42px;height:42px;background:var(--primary-bg);border-radius:12px;display:flex;align-items:center;justify-content:center">
      <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="var(--primary)" stroke-width="2" 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"/><path d="M23 21v-2a4 4 0 00-3-3.87M16 3.13a4 4 0 010 7.75"/></svg>
    </div>
    <div><div style="font-size:.68rem;font-weight:700;text-transform:uppercase;letter-spacing:.08em;color:var(--text-muted);margin-bottom:3px">Total Team</div><div style="font-size:1.4rem;font-weight:800;color:var(--primary)"><?php echo $total_staff; ?></div></div>
  </div>
  <div class="card" style="padding:18px 20px;display:flex;align-items:center;gap:14px">
    <div style="width:42px;height:42px;background:var(--success-bg);border-radius:12px;display:flex;align-items:center;justify-content:center">
      <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="var(--success)" stroke-width="2" stroke-linecap="round"><path d="M20 21v-2a4 4 0 00-4-4H8a4 4 0 00-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>
    </div>
    <div><div style="font-size:.68rem;font-weight:700;text-transform:uppercase;letter-spacing:.08em;color:var(--text-muted);margin-bottom:3px">Waiters</div><div style="font-size:1.4rem;font-weight:800;color:var(--success)"><?php echo $waiters; ?></div></div>
  </div>
  <div class="card" style="padding:18px 20px;display:flex;align-items:center;gap:14px">
    <div style="width:42px;height:42px;background:var(--warning-bg);border-radius:12px;display:flex;align-items:center;justify-content:center">
      <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="var(--warning)" stroke-width="2" stroke-linecap="round"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>
    </div>
    <div><div style="font-size:.68rem;font-weight:700;text-transform:uppercase;letter-spacing:.08em;color:var(--text-muted);margin-bottom:3px">Other Staff</div><div style="font-size:1.4rem;font-weight:800;color:var(--warning)"><?php echo $staff_only; ?></div></div>
  </div>
</div>

<?php if($success): ?><div class="alert alert-success"><svg viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round"><path d="M22 11.08V12a10 10 0 11-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg><?php echo $success; ?></div><?php endif; ?>
<?php if($error): ?><div class="alert alert-error"><svg viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/></svg><?php echo htmlspecialchars($error); ?></div><?php endif; ?>

<!-- Filters -->
<div style="display:flex;gap:8px;margin-bottom:16px;flex-wrap:wrap;align-items:center">
  <?php foreach(['all'=>'All','waiter'=>'Waiters / Waitresses','staff'=>'Other Staff'] as $k=>$l): ?>
  <a href="?role_f=<?php echo $k; ?>" class="btn btn-sm <?php echo $role_f===$k?'btn-primary':'btn-secondary'; ?>"><?php echo $l; ?></a>
  <?php endforeach; ?>
  <form method="GET" style="margin-left:auto">
    <input type="hidden" name="role_f" value="<?php echo htmlspecialchars($role_f); ?>">
    <div style="position:relative">
      <svg style="position:absolute;left:11px;top:50%;transform:translateY(-50%);width:14px;height:14px;stroke:var(--text-light);fill:none" viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round"><circle cx="11" cy="11" r="8"/><path d="m21 21-4.35-4.35"/></svg>
      <input type="text" name="search" placeholder="Search staff…" value="<?php echo htmlspecialchars($search); ?>"
             style="height:38px;border:1.5px solid var(--border);border-radius:10px;background:var(--white);padding:0 12px 0 32px;font-size:.83rem;font-family:var(--font);outline:none;width:200px"
             onfocus="this.style.borderColor='var(--primary)'" onblur="this.style.borderColor='var(--border)'">
    </div>
  </form>
</div>

<div class="card">
  <?php if($staff_list->num_rows===0): ?>
    <div style="padding:56px;text-align:center;color:var(--text-muted)">
      <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="var(--border)" stroke-width="1.5" stroke-linecap="round" style="margin:0 auto 14px;display:block"><path d="M17 21v-2a4 4 0 00-4-4H5a4 4 0 00-4 4v2"/><circle cx="9" cy="7" r="4"/></svg>
      <p style="font-weight:700;margin-bottom:6px">No staff members yet</p>
      <button class="btn btn-primary btn-sm" onclick="openModal('addStaffModal')" style="margin-top:10px">Add First Staff Member</button>
    </div>
  <?php else: ?>
  <div class="table-scroll">
<table class="data-table">
    <thead><tr><th>Staff Member</th><th>Role</th><th>Phone</th><th>Orders Handled</th><th>Status</th><th>Joined</th><th>Actions</th></tr></thead>
    <tbody>
    <?php while($s=$staff_list->fetch_assoc()):
      $initials=strtoupper(substr($s['name'],0,1)).(strpos($s['name'],' ')!==false?strtoupper(substr(strrchr($s['name'],' '),1,1)):'');
      $role_color=$s['role']==='waiter'?'badge-success':'badge-primary';
    ?>
      <tr>
        <td>
          <div style="display:flex;align-items:center;gap:10px">
            <div style="width:34px;height:34px;border-radius:50%;background:var(--primary);display:flex;align-items:center;justify-content:center;font-size:.72rem;font-weight:800;color:#fff;flex-shrink:0"><?php echo $initials; ?></div>
            <div>
              <div style="font-weight:700;font-size:.85rem"><?php echo htmlspecialchars($s['name']); ?></div>
              <div style="font-size:.72rem;color:var(--text-muted)"><?php echo htmlspecialchars($s['email']); ?></div>
            </div>
          </div>
        </td>
        <td><span class="badge <?php echo $role_color; ?>"><?php echo ucfirst($s['role']); ?></span></td>
        <td style="font-size:.82rem"><?php echo htmlspecialchars($s['phone']??'—'); ?></td>
        <td style="font-weight:600"><?php echo $s['orders_handled']; ?></td>
        <td><span class="badge <?php echo $s['status']?'badge-success':'badge-error'; ?>"><?php echo $s['status']?'Active':'Inactive'; ?></span></td>
        <td style="font-size:.78rem;color:var(--text-muted)"><?php echo date('M j, Y',strtotime($s['created_at'])); ?></td>
        <td>
          <div style="display:flex;gap:6px;flex-wrap:wrap">
            <a href="?action=edit&id=<?php echo $s['id']; ?>" class="btn btn-secondary btn-sm">Edit</a>
            <a href="?action=toggle&id=<?php echo $s['id']; ?>" class="btn btn-sm <?php echo $s['status']?'btn-warning':'btn-success'; ?>"
               onclick="return confirm('<?php echo $s['status']?'Deactivate':'Activate'; ?> <?php echo addslashes($s['name']); ?>?')">
              <?php echo $s['status']?'Deactivate':'Activate'; ?>
            </a>
            <form method="POST" style="display:inline" onsubmit="return confirm('Remove <?php echo addslashes($s['name']); ?> from team?')">
              <input type="hidden" name="action" value="delete">
              <input type="hidden" name="id" value="<?php echo $s['id']; ?>">
              <button class="btn btn-danger btn-sm">Remove</button>
            </form>
          </div>
        </td>
      </tr>
    <?php endwhile; ?>
    </tbody>
  </table>
</div>
  <?php endif; ?>
</div>

<!-- Add Staff Modal -->
<div class="modal-backdrop" id="addStaffModal">
  <div class="modal">
    <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" stroke-linecap="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg></button>
    </div>
    <form method="POST">
      <input type="hidden" name="action" value="create">
      <div class="modal-body">
        <div class="grid-2">
          <div class="form-group"><label>Full Name *</label><input type="text" name="name" class="form-control" placeholder="Jane Doe" required></div>
          <div class="form-group">
            <label>Role *</label>
            <select name="role_s" class="form-control">
              <option value="waiter">Waiter / Waitress</option>
              <option value="staff">Other Staff (Kitchen, Cashier…)</option>
            </select>
          </div>
          <div class="form-group"><label>Email *</label><input type="email" name="email" class="form-control" placeholder="staff@email.com" required></div>
          <div class="form-group"><label>Phone</label><input type="tel" name="phone" class="form-control" placeholder="08012345678"></div>
          <div class="form-group"><label>Password * <span style="font-weight:400;text-transform:none;letter-spacing:0;color:var(--text-light)">(min. 6 chars)</span></label><input type="password" name="password" class="form-control" placeholder="••••••••" required></div>
          <div class="form-group"><label>Confirm Password</label><input type="password" id="cpw" class="form-control" placeholder="Repeat password"></div>
        </div>
        <div class="alert alert-info" style="margin-top:4px">
          <svg viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round"><circle cx="12" cy="12" r="10"/><path d="M12 8v4M12 16h.01"/></svg>
          Staff will log in at this portal with their email and password. They can see orders and notifications for <?php echo htmlspecialchars($__rest_name); ?>.
        </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-primary btn-md">Add Staff Member</button>
      </div>
    </form>
  </div>
</div>

<!-- Edit Staff Modal -->
<?php if($edit_staff): ?>
<div class="modal-backdrop" id="editStaffModal" style="display:flex">
  <div class="modal">
    <div class="modal-header">
      <h3>Edit — <?php echo htmlspecialchars($edit_staff['name']); ?></h3>
      <a href="staff.php" class="modal-close"><svg viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg></a>
    </div>
    <form method="POST">
      <input type="hidden" name="action" value="edit">
      <input type="hidden" name="staff_id" value="<?php echo $edit_staff['id']; ?>">
      <div class="modal-body">
        <div class="grid-2">
          <div class="form-group"><label>Full Name</label><input type="text" name="name" class="form-control" value="<?php echo htmlspecialchars($edit_staff['name']); ?>" required></div>
          <div class="form-group">
            <label>Role</label>
            <select name="role_s" class="form-control">
              <option value="waiter" <?php echo $edit_staff['role']==='waiter'?'selected':''; ?>>Waiter / Waitress</option>
              <option value="staff"  <?php echo $edit_staff['role']==='staff'?'selected':''; ?>>Other Staff</option>
            </select>
          </div>
          <div class="form-group"><label>Email</label><input type="email" name="email" class="form-control" value="<?php echo htmlspecialchars($edit_staff['email']); ?>" required></div>
          <div class="form-group"><label>Phone</label><input type="tel" name="phone" class="form-control" value="<?php echo htmlspecialchars($edit_staff['phone']??''); ?>"></div>
          <div class="form-group" style="grid-column:1/-1"><label>New Password <span style="font-weight:400;text-transform:none;letter-spacing:0;color:var(--text-light)">(leave blank to keep)</span></label><input type="password" name="password" class="form-control" placeholder="New password…"></div>
        </div>
      </div>
      <div class="modal-footer">
        <a href="staff.php" class="btn btn-secondary btn-md">Cancel</a>
        <button type="submit" class="btn btn-primary btn-md">Save Changes</button>
      </div>
    </form>
  </div>
</div>
<?php endif; ?>

<?php include("includes/footer.php"); ?>
