<?php
/* ============================================================================
   WBMCZ ADMIN — ROLE (audience) FILTER HELPER
   ----------------------------------------------------------------------------
   The premium sidebar links every "management" section with a ?role= deep link:

        ...php?role=all | free | pro | seller | employee | admin

   This file turns that single query parameter into a reusable SQL condition,
   a label and a banner, so every admin page filters the same way.

   Typical use:

        require_once __DIR__ . '/includes/role_filter.php';
        $role = wb_role();
        $cond = wb_role_sql($role, 'u');           // e.g. "u.user_type='seller'"
        $rows = $db->select("SELECT ... WHERE $cond ...");
        echo wb_role_banner($role);                // optional context pill
   ========================================================================== */

if (!function_exists('wb_role')) {

/** Normalised role coming from the sidebar link ('' when not a role view). */
function wb_role() {
    $r = isset($_GET['role']) ? strtolower(trim((string)$_GET['role'])) : '';
    $ok = ['all', 'free', 'pro', 'seller', 'employee', 'admin'];
    return in_array($r, $ok, true) ? $r : '';
}

/** Human label for the current role view. */
function wb_role_label($r) {
    $m = [
        'all'      => 'All Users',
        'free'     => 'Free Users',
        'pro'      => 'Pro Users',
        'seller'   => 'Sellers',
        'employee' => 'Employees',
        'admin'    => 'Admins',
    ];
    return $m[$r] ?? 'All Users';
}

/** Icon for the current role view. */
function wb_role_icon($r) {
    $m = [
        'all'      => 'fa-layer-group',
        'free'     => 'fa-user',
        'pro'      => 'fa-gem',
        'seller'   => 'fa-store',
        'employee' => 'fa-user-tie',
        'admin'    => 'fa-shield-halved',
    ];
    return $m[$r] ?? 'fa-layer-group';
}

/** Tailwind tone classes for the current role view. */
function wb_role_tone($r) {
    $m = [
        'all'      => 'bg-slate-100 text-slate-700 ring-slate-200',
        'free'     => 'bg-sky-50 text-sky-700 ring-sky-200',
        'pro'      => 'bg-fuchsia-50 text-fuchsia-700 ring-fuchsia-200',
        'seller'   => 'bg-amber-50 text-amber-700 ring-amber-200',
        'employee' => 'bg-teal-50 text-teal-700 ring-teal-200',
        'admin'    => 'bg-rose-50 text-rose-700 ring-rose-200',
    ];
    return $m[$r] ?? $m['all'];
}

/**
 * SQL condition against the `users` table.
 *
 * Employees  = staff accounts that carry a custom role (role_id set)
 * Admin      = staff accounts without a custom role (super admins)
 * Pro / Free = customers split by `is_subscribed`
 *
 * @param string $r      role key
 * @param string $alias  users-table alias used in the caller's query
 * @return string        always a valid boolean expression ("1" when unfiltered)
 */
function wb_role_sql($r, $alias = 'u') {
    $a = preg_replace('/[^A-Za-z0-9_]/', '', $alias);
    $a = $a === '' ? 'u' : $a . '.';
    if (substr($a, -1) !== '.') $a .= '.';

    switch ($r) {
        case 'free':     return "({$a}user_type = 'customer' AND COALESCE({$a}is_subscribed,0) = 0)";
        case 'pro':      return "({$a}user_type = 'customer' AND COALESCE({$a}is_subscribed,0) = 1)";
        case 'seller':   return "({$a}user_type = 'seller')";
        case 'employee': return "({$a}user_type = 'admin' AND {$a}role_id IS NOT NULL)";
        case 'admin':    return "({$a}user_type = 'admin' AND {$a}role_id IS NULL)";
        case 'all':
        default:         return "1";
    }
}

/** Small contextual pill shown above a filtered table. */
function wb_role_banner($r, $suffix = '') {
    if ($r === '') return '';
    $label = wb_role_label($r);
    $icon  = wb_role_icon($r);
    $tone  = wb_role_tone($r);
    $extra = $suffix !== '' ? ' <span class="opacity-60 font-medium">' . htmlspecialchars($suffix) . '</span>' : '';
    return '<div class="mb-5 flex flex-wrap items-center gap-3">'
         . '<span class="inline-flex items-center gap-2 px-3.5 py-1.5 rounded-full text-xs font-bold ring-1 ' . $tone . '">'
         . '<i class="fas ' . $icon . '"></i> Viewing: ' . htmlspecialchars($label) . $extra . '</span>'
         . '<a href="?role=all" class="text-xs font-semibold text-slate-400 hover:text-emerald-600 transition-colors">'
         . '<i class="fas fa-rotate-left mr-1"></i>Show all</a></div>';
}

/** Convenience: the six audience tabs, rendered as premium pills. */
function wb_role_tabs($current, $base = '', $roles = ['all','free','pro','seller','employee','admin']) {
    $out = '<div class="flex flex-wrap gap-2 mb-6">';
    foreach ($roles as $r) {
        $on   = ($current === $r) || ($current === '' && $r === 'all');
        $cls  = $on
            ? 'bg-slate-900 text-white shadow-lg shadow-slate-900/20 ring-slate-900'
            : 'bg-white text-slate-600 ring-slate-200 hover:bg-slate-50 hover:text-slate-900';
        $out .= '<a href="' . htmlspecialchars($base) . '?role=' . $r . '" '
              . 'class="inline-flex items-center gap-2 px-4 py-2 rounded-xl text-xs font-bold ring-1 transition-all ' . $cls . '">'
              . '<i class="fas ' . wb_role_icon($r) . ' text-[.7rem]"></i>' . htmlspecialchars(wb_role_label($r))
              . '</a>';
    }
    return $out . '</div>';
}

} // end function_exists guard
