<?php
session_start();
$page_title = 'All Users';
$active_nav = 'users';
include("includes/header.php");

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

// TOGGLE STATUS
if ($action === 'toggle' && isset($_GET['id'])) {
    $user_id = (int)$_GET['id'];
    if ($user_id !== $uid) { // can't deactivate yourself
        $stmt = $conn->prepare("UPDATE users SET status = 1 - status WHERE id=? AND role != 'super_admin'");
        $stmt->bind_param("i",$user_id); $stmt->execute();
    }
    header("Location: users.php?msg=toggled"); exit;
}

// DELETE USER
if ($action === 'delete' && isset($_POST['id'])) {
    $user_id = (int)$_POST['id'];
    if ($user_id !== $uid) {
        $stmt = $conn->prepare("DELETE FROM users WHERE id=? AND role != 'super_admin'");
        $stmt->bind_param("i",$user_id); $stmt->execute();
    }
    header("Location: users.php?msg=deleted"); exit;
}

// CREATE SUPER ADMIN
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $action === 'create_admin') {
    $name  = trim($_POST['name'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $phone = trim($_POST['phone'] ?? '');
    $pw    = $_POST['password'] ?? '';

    if (!$name || !$email || !$pw) {
        $error = "Name, email and password are required.";
    } 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 exists.";
        } else {
            $hash = password_hash($pw, PASSWORD_DEFAULT);
            $stmt = $conn->prepare("INSERT INTO users (name,email,phone,password,role,status) VALUES (?,?,?,?,'super_admin',1)");
            $stmt->bind_param("ssss",$name,$email,$phone,$hash);
            $stmt->execute();
            $success = "Super admin account created.";
        }
    }
}

$msg = $_GET['msg'] ?? '';
if ($msg === 'toggled') $success = "User status updated.";
if ($msg === 'deleted') $success = "User deleted.";

// Filters
$role_filter   = $_GET['role'] ?? 'all';
$search        = trim($_GET['search'] ?? '');

$query = "SELECT u.*, r.name as restaurant_name,
           (SELECT COALESCE(SUM(balance),0) FROM wallets w WHERE w.user_id=u.id) as wallet_balance,
           (SELECT COUNT(*) FROM orders o WHERE o.user_id=u.id) as order_count
          FROM users u
          LEFT JOIN restaurants r ON u.restaurant_id=r.id
          WHERE 1=1";
$params = []; $types = "";

if ($role_filter !== 'all') {
    $query  .= " AND u.role=?";
    $params[] = $role_filter; $types .= "s";
}
if ($search) {
    $query  .= " AND (u.name LIKE ? OR u.email LIKE ? OR u.phone LIKE ?)";
    $s = "%$search%"; $params = array_merge($params,[$s,$s,$s]); $types .= "sss";
}
$query .= " ORDER BY u.created_at DESC";

$stmt = $conn->prepare($query);
if ($params) $stmt->bind_param($types,...$params);
$stmt->execute();
$users = $stmt->get_result();

// Role counts
$role_counts = [];
foreach(['all','super_admin','restaurant_admin','staff','customer'] as $r) {
    if ($r === 'all') $role_counts[$r] = $conn->query("SELECT COUNT(*) FROM users")->fetch_row()[0];
    else $role_counts[$r] = $conn->query("SELECT COUNT(*) FROM users WHERE role='$r'")->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.5rem;font-weight:800;letter-spacing:-.03em;margin-bottom:4px">All Users</h1>
    <p style="color:var(--text-muted);font-size:.875rem">Manage platform users across all roles</p>
  </div>
  <button class="btn btn-primary btn-md" onclick="openModal('createAdminModal')">
    <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 Super Admin
  </button>
</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; ?>

<!-- Role Filter Tabs -->
<div style="display:flex;gap:8px;margin-bottom:20px;flex-wrap:wrap;align-items:center">
  <?php
  $role_labels = ['all'=>'All','super_admin'=>'Super Admins','restaurant_admin'=>'Restaurant Admins','staff'=>'Staff','customer'=>'Customers'];
  foreach($role_labels as $k=>$l):
  ?>
  <a href="?role=<?php echo $k; ?><?php echo $search?"&search=".urlencode($search):''; ?>"
     class="btn btn-sm <?php echo $role_filter===$k?'btn-primary':'btn-secondary'; ?>">
    <?php echo $l; ?> <span style="opacity:.7">(<?php echo $role_counts[$k]; ?>)</span>
  </a>
  <?php endforeach; ?>
  <form method="GET" style="margin-left:auto">
    <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="hidden" name="role" value="<?php echo htmlspecialchars($role_filter); ?>">
      <input type="text" name="search" placeholder="Search users…" 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:220px"
             onfocus="this.style.borderColor='var(--primary)'" onblur="this.style.borderColor='var(--border)'">
    </div>
  </form>
</div>

<div class="card">
  <?php if ($users->num_rows === 0): ?>
    <div style="padding:60px;text-align:center;color:var(--text-muted)">
      <p style="font-weight:700;margin-bottom:6px">No users found</p>
      <p style="font-size:.85rem">Try a different filter or search term.</p>
    </div>
  <?php else: ?>
  <div style="overflow-x:auto">
  <table class="data-table">
    <thead><tr><th>User</th><th>Role</th><th>Restaurant</th><th>Wallet</th><th>Orders</th><th>Status</th><th>Joined</th><th>Actions</th></tr></thead>
    <tbody>
    <?php while($u_row = $users->fetch_assoc()):
      $role_colors = ['super_admin'=>'badge-error','restaurant_admin'=>'badge-primary','staff'=>'badge-info','customer'=>'badge-success'];
      $role_labels_map = ['super_admin'=>'Super Admin','restaurant_admin'=>'Rest. Admin','staff'=>'Staff','customer'=>'Customer'];
      $rc = $role_colors[$u_row['role']] ?? 'badge-muted';
      $rl = $role_labels_map[$u_row['role']] ?? ucfirst($u_row['role']);
      $is_me = $u_row['id'] == $uid;
    ?>
      <tr>
        <td>
          <div style="display:flex;align-items:center;gap:10px">
            <div style="width:32px;height:32px;border-radius:50%;background:var(--primary);display:flex;align-items:center;justify-content:center;font-size:.7rem;font-weight:800;color:#fff;flex-shrink:0">
              <?php echo strtoupper(substr($u_row['name'],0,1)); ?>
            </div>
            <div>
              <div style="font-weight:700;font-size:.85rem">
                <?php echo htmlspecialchars($u_row['name']); ?>
                <?php if($is_me): ?><span style="font-size:.68rem;color:var(--primary);font-weight:600"> (you)</span><?php endif; ?>
              </div>
              <div style="font-size:.72rem;color:var(--text-muted)"><?php echo htmlspecialchars($u_row['email']); ?></div>
            </div>
          </div>
        </td>
        <td><span class="badge <?php echo $rc; ?>"><?php echo $rl; ?></span></td>
        <td style="font-size:.82rem"><?php echo htmlspecialchars($u_row['restaurant_name'] ?? '—'); ?></td>
        <td style="font-weight:600;color:var(--primary)">₦<?php echo number_format($u_row['wallet_balance'],0); ?></td>
        <td style="font-weight:600"><?php echo $u_row['order_count']; ?></td>
        <td><span class="badge <?php echo $u_row['status']?'badge-success':'badge-error'; ?>"><?php echo $u_row['status']?'Active':'Inactive'; ?></span></td>
        <td style="font-size:.78rem;color:var(--text-muted)"><?php echo date('M j, Y', strtotime($u_row['created_at'])); ?></td>
        <td>
          <?php if (!$is_me && $u_row['role'] !== 'super_admin'): ?>
          <div style="display:flex;gap:6px">
            <a href="?action=toggle&id=<?php echo $u_row['id']; ?>"
               class="btn btn-sm <?php echo $u_row['status']?'btn-danger':'btn-success'; ?>"
               onclick="return confirm('<?php echo $u_row['status']?'Deactivate':'Activate'; ?> this user?')">
              <?php echo $u_row['status']?'Deactivate':'Activate'; ?>
            </a>
            <form method="POST" style="display:inline" onsubmit="return confirm('Delete <?php echo addslashes($u_row['name']); ?>?')">
              <input type="hidden" name="action" value="delete">
              <input type="hidden" name="id" value="<?php echo $u_row['id']; ?>">
              <button type="submit" class="btn btn-danger btn-sm">Delete</button>
            </form>
          </div>
          <?php else: ?>
          <span style="font-size:.75rem;color:var(--text-light)">—</span>
          <?php endif; ?>
        </td>
      </tr>
    <?php endwhile; ?>
    </tbody>
  </table>
  </div>
  <?php endif; ?>
</div>

<!-- Create Super Admin Modal -->
<div class="modal-backdrop" id="createAdminModal">
  <div class="modal">
    <div class="modal-header">
      <h3>Create Super Admin</h3>
      <button class="modal-close" onclick="closeModal('createAdminModal')"><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_admin">
      <div class="modal-body">
        <div class="form-group">
          <label>Full Name *</label>
          <input type="text" name="name" class="form-control" placeholder="Admin Full Name" required>
        </div>
        <div class="form-group">
          <label>Email *</label>
          <input type="email" name="email" class="form-control" placeholder="admin@dabil.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" style="margin-bottom:0">
          <label>Password *</label>
          <input type="password" name="password" class="form-control" placeholder="Min. 6 characters" required>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary btn-md" onclick="closeModal('createAdminModal')">Cancel</button>
        <button type="submit" class="btn btn-primary btn-md">Create Admin</button>
      </div>
    </form>
  </div>
</div>

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