<?php
/* ============================================================================
   WBMCZ — Admin list toolkit

   Shared by the User list, Product Management and the Service list:
     - STICKY filters  : once applied, a filter survives paging, sorting and
                         navigating away. It only clears when Reset is pressed.
     - Search box
     - CSV export of exactly what is on screen
     - Stat cards row

   Filters are remembered per list key in $_SESSION['adm_filters'][$key].
   ============================================================================ */

if (!function_exists('alist_filters')) {

/**
 * Resolve the active filters for a list.
 *
 * $key    unique list name, e.g. 'users'
 * $fields ['search' => '', 'status' => '', ...]  name => default
 *
 * Behaviour:
 *   ?reset=1        clears everything for this list
 *   any field in $_GET   overwrites and is remembered
 *   nothing in $_GET     the remembered values are used
 */
function alist_filters($key, $fields) {
    if (!isset($_SESSION['adm_filters']) || !is_array($_SESSION['adm_filters'])) {
        $_SESSION['adm_filters'] = [];
    }

    if (isset($_GET['reset'])) {
        unset($_SESSION['adm_filters'][$key]);
        /* Reset clears what the PERSON chose. It must not clear what the PAGE
           is: a list that fixes one of these fields for itself — the audience
           of User / Seller / Employees / Admin, the recycle bin, a plan-only
           list — writes that field into $_GET on every single load, before it
           gets here. Those come back; everything else returns to its default.

           Handing back the bare defaults, as this used to, quietly widened the
           list: Reset on the User page showed sellers and staff as well. */
        $out = [];
        foreach ($fields as $name => $default) {
            $out[$name] = isset($_GET[$name]) ? trim((string)$_GET[$name]) : $default;
        }
        $_SESSION['adm_filters'][$key] = $out;
        return $out;
    }

    $saved = isset($_SESSION['adm_filters'][$key]) && is_array($_SESSION['adm_filters'][$key])
        ? $_SESSION['adm_filters'][$key] : [];

    // Did this request actually submit the filter form?
    $submitted = isset($_GET['f']) && $_GET['f'] === $key;

    $out = [];
    foreach ($fields as $name => $default) {
        if ($submitted) {
            $out[$name] = isset($_GET[$name]) ? trim((string)$_GET[$name]) : $default;
        } elseif (isset($_GET[$name])) {
            $out[$name] = trim((string)$_GET[$name]);           // deep link
        } elseif (array_key_exists($name, $saved)) {
            $out[$name] = $saved[$name];                        // remembered
        } else {
            $out[$name] = $default;
        }
    }

    $_SESSION['adm_filters'][$key] = $out;
    return $out;
}

/* Is anything actually filtering right now? */
function alist_active($filters, $defaults) {
    foreach ($defaults as $k => $v) {
        if (($filters[$k] ?? $v) !== $v) return true;
    }
    return false;
}

/* How many filters are on — used for the badge */
function alist_active_count($filters, $defaults) {
    $n = 0;
    foreach ($defaults as $k => $v) { if (($filters[$k] ?? $v) !== $v) $n++; }
    return $n;
}

/* Rebuild the current URL with the filters in it (for export / paging links) */
function alist_url($self, $key, $filters, $extra = []) {
    $p = array_filter($filters, function ($v) { return $v !== '' && $v !== null; });
    $p['f'] = $key;
    return $self . '?' . http_build_query(array_merge($p, $extra));
}

/* ---------------------------------------------------------------------------
   CSV export — call BEFORE any HTML output
   $columns = ['Header' => 'row_key' | callable($row)]
   --------------------------------------------------------------------------- */
function alist_export_csv($filename, $columns, $rows) {
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename="' . $filename . '_' . date('Ymd_His') . '.csv"');
    $out = fopen('php://output', 'w');
    fprintf($out, chr(0xEF) . chr(0xBB) . chr(0xBF));   // BOM so Excel reads UTF-8
    fputcsv($out, array_keys($columns));
    foreach ($rows as $r) {
        $line = [];
        foreach ($columns as $spec) {
            if (is_callable($spec)) { $line[] = $spec($r); }
            else { $line[] = html_entity_decode((string)($r[$spec] ?? ''), ENT_QUOTES); }
        }
        fputcsv($out, $line);
    }
    fclose($out);
    exit;
}

/* ---------------------------------------------------------------------------
   UI pieces
   --------------------------------------------------------------------------- */

/* Row of stat cards. $cards = [['label','value','sub','colour','icon'], ...] */
function alist_stats($cards) {
    ob_start(); ?>
    <div class="grid grid-cols-2 md:grid-cols-3 xl:grid-cols-6 gap-2.5 mb-5">
        <?php foreach ($cards as $c):
            $col = $c['colour'] ?? 'slate';
        ?>
        <div class="al-stat">
            <div class="al-stat-ico bg-<?php echo $col; ?>-50 text-<?php echo $col; ?>-600 border-<?php echo $col; ?>-100">
                <i class="fas <?php echo $c['icon'] ?? 'fa-circle'; ?>"></i>
            </div>
            <div class="min-w-0">
                <p class="al-stat-k"><?php echo htmlspecialchars($c['label']); ?></p>
                <p class="al-stat-v text-<?php echo $col; ?>-600"><?php echo $c['value']; ?></p>
                <?php if (!empty($c['sub'])): ?><p class="al-stat-s"><?php echo htmlspecialchars($c['sub']); ?></p><?php endif; ?>
            </div>
        </div>
        <?php endforeach; ?>
    </div>
    <?php
    return ob_get_clean();
}

/* Sticky-filter banner shown while filters are on */
function alist_banner($self, $key, $filters, $defaults, $labels = []) {
    $n = alist_active_count($filters, $defaults);
    if ($n === 0) return '';
    $chips = [];
    foreach ($defaults as $k => $v) {
        $cur = $filters[$k] ?? $v;
        if ($cur === $v) continue;
        $lbl = $labels[$k] ?? ucfirst(str_replace('_', ' ', $k));
        $chips[] = $lbl . ': ' . $cur;
    }
    ob_start(); ?>
    <div class="al-banner">
        <i class="fas fa-filter"></i>
        <div class="min-w-0 flex-1">
            <b><?php echo $n; ?> filter<?php echo $n > 1 ? 's' : ''; ?> active</b>
            <span class="opacity-80"> — <?php echo htmlspecialchars(implode(' · ', $chips)); ?></span>
            <span class="block text-[10px] opacity-70 mt-0.5">This stays applied until you press Reset.</span>
        </div>
        <a href="<?php echo $self; ?>?reset=1" class="al-btn al-btn-reset flex-shrink-0"><i class="fas fa-xmark"></i> Reset</a>
    </div>
    <?php
    return ob_get_clean();
}

/* Shared styles — printed once */
function alist_styles() {
    static $done = false;
    if ($done) return '';
    $done = true;
    ob_start(); ?>
<style>
    .al-stat { display:flex; align-items:center; gap:.7rem; background:#fff; border:1px solid #e2e8f0;
               border-radius:.9rem; padding:.75rem .85rem; }
    .al-stat-ico { width:36px; height:36px; border-radius:.7rem; display:flex; align-items:center;
                   justify-content:center; font-size:.85rem; border:1px solid; flex-shrink:0; }
    .al-stat-k { font-size:9px; font-weight:800; text-transform:uppercase; letter-spacing:.06em; color:#94a3b8; line-height:1.2; }
    .al-stat-v { font-size:1.05rem; font-weight:900; line-height:1.2; }
    .al-stat-s { font-size:9px; color:#cbd5e1; font-weight:600; }

    .al-banner { display:flex; align-items:flex-start; gap:.7rem; padding:.7rem .9rem; margin-bottom:1rem;
                 background:#eef2ff; border:1px solid #c7d2fe; border-radius:.85rem; font-size:11.5px; color:#3730a3; }
    .al-banner > i { margin-top:.15rem; }

    .al-panel { background:#fff; border:1px solid #e2e8f0; border-radius:1rem; }
    .al-l { display:block; font-size:10px; font-weight:800; color:#64748b; margin-bottom:.25rem;
            text-transform:uppercase; letter-spacing:.05em; }
    .al-f { width:100%; padding:.6rem .75rem; background:#fff; border:1.5px solid #cbd5e1;
            border-radius:.75rem; font-size:.78rem; outline:none; color:#0f172a; }
    .al-f:focus { border-color:#6366f1; box-shadow:0 0 0 3px rgba(99,102,241,.14); }

    .al-btn { display:inline-flex; align-items:center; justify-content:center; gap:.4rem; padding:.6rem 1rem;
              border-radius:.75rem; font-weight:800; font-size:.74rem; border:0; cursor:pointer;
              white-space:nowrap; transition:.15s; text-decoration:none; }
    .al-btn-apply { background:#0f172a; color:#fff; }
    .al-btn-apply:hover { background:#1e293b; }
    .al-btn-reset { background:#fff; color:#4338ca; border:1px solid #c7d2fe; }
    .al-btn-csv   { background:#059669; color:#fff; }
    .al-btn-csv:hover { background:#047857; }
    .al-btn-ghost { background:#f1f5f9; color:#475569; }

    .al-count { display:inline-flex; align-items:center; justify-content:center; min-width:17px; height:17px;
                padding:0 4px; border-radius:999px; background:#4f46e5; color:#fff; font-size:9.5px; font-weight:900; }
</style>
<?php
    return ob_get_clean();
}

} // end function_exists guard
