<?php
/* ============================================================================
   WBMCZ — Admin · Task criteria

   One screen that decides WHO shows up on each tab of Activity & Task.

   Pick an audience (User / Seller / Employee …) and a tab (Lead / KYC /
   Subscription …), tick the conditions, and the count updates as you save.
   The tab then lists exactly those people, ready to be handed out in bulk.

   Nothing is hard-coded: a tab with no saved rule falls back to a sensible
   default (KYC = never filled, Subscription = never subscribed, and so on),
   and "Reset" puts that default back.
   ============================================================================ */

require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../db.php';
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/Language.php';
require_once __DIR__ . '/../includes/admin_list.php';
@require_once __DIR__ . '/../includes/acl.php';
require_once __DIR__ . '/../includes/tasks.php';
require_once __DIR__ . '/../includes/task_criteria.php';

if (!isLoggedIn() || !isAdmin()) { redirect('login.php'); }
/* Needs the Activity & Task module (Create a task), or the whole panel.
   tcrit_deny() explains what is missing instead of showing a blank page. */
if (!tcrit_can_manage($db)) { tcrit_deny($db, 'change task criteria'); }

$lang         = new Language($db);
$current_lang = $lang->getCurrentLanguage();
$user_id      = (int)$_SESSION['user_id'];

$can_users        = hasPermission('manage_users');
$can_sellers      = hasPermission('manage_sellers');
$can_staff        = hasPermission('manage_staff_roles');
$can_services     = hasPermission('manage_services');
$can_orders       = hasPermission('manage_orders');
$can_transactions = hasPermission('manage_transactions');
$can_tickets      = hasPermission('manage_tickets');
$can_settings     = hasPermission('manage_settings');

tasks_ensure_schema($db);
tcrit_ensure_schema($db);

$me = tasks_actor($db);

if (isset($_SESSION['flash_success'])) { $success_msg = $_SESSION['flash_success']; unset($_SESSION['flash_success']); }
if (isset($_SESSION['flash_error']))   { $error_msg   = $_SESSION['flash_error'];   unset($_SESSION['flash_error']); }

$ROLES   = tasks_roles();
$MODULES = tasks_modules();
$CONDS   = tcrit_conditions();

$SCOPE = $_GET['role'] ?? ($_POST['scope_role'] ?? 'user');
$MOD   = $_GET['mod']  ?? ($_POST['module_key'] ?? 'lead');
if (!isset($ROLES[$SCOPE]))   { $SCOPE = 'user'; }
if (!isset($MODULES[$MOD]))   { $MOD = 'lead'; }

$SELF = 'task_criteria.php?role=' . urlencode($SCOPE) . '&mod=' . urlencode($MOD);

/* ---------------------------------------------------------------------------
   Save / reset
   --------------------------------------------------------------------------- */
if (isset($_POST['save_criteria'])) {
    $rules = [];
    foreach ($CONDS as $k => $def) {
        $val = trim((string)($_POST['c_' . $k] ?? ''));
        if ($val === '') continue;
        if ($def[2] === 'days' && !ctype_digit($val)) continue;
        if ($def[2] === 'choice' && !array_key_exists($val, $def[3])) continue;
        $rules[$k] = sanitize($val);
    }
    $sort = (string)($_POST['sort_field'] ?? 'newest');
    if (!array_key_exists($sort, tcrit_sorts())) { $sort = 'newest'; }

    tcrit_save($db, $SCOPE, $MOD, sanitize($_POST['label'] ?? ''), $rules, $sort,
               ((int)($_POST['status'] ?? 1) === 1) ? 1 : 0, $me);

    $_SESSION['flash_success'] = 'Criteria saved for ' . $ROLES[$SCOPE][0] . ' → ' . $MODULES[$MOD][0] . '.';
    redirect($SELF);
}

if (isset($_POST['reset_criteria'])) {
    tcrit_reset($db, $SCOPE, $MOD);
    $_SESSION['flash_success'] = 'Put back to the built-in default.';
    redirect($SELF);
}

/* ---------------------------------------------------------------------------
   Current rule + a live preview of who it catches
   --------------------------------------------------------------------------- */
$CRIT    = tcrit_get($db, $SCOPE, $MOD);
$matched = tcrit_count($db, $CRIT['rules'], $MOD);
$sample  = tcrit_rows($db, $CRIT['rules'], $MOD, $CRIT['sort'], 8, 0);

/* how many each tab currently catches, for the chips */
$tab_counts = [];
foreach ($MODULES as $mk => $mv) {
    $c = tcrit_get($db, $SCOPE, $mk);
    $tab_counts[$mk] = empty($c['rules']) ? null : tcrit_count($db, $c['rules'], $mk);
}

/* group the conditions for the form */
$by_group = [];
foreach ($CONDS as $k => $def) { $by_group[$def[1]][$k] = $def; }

$company_logo = getSetting('company_logo', '../assets/images/logo.png');
?>
<!DOCTYPE html>
<html lang="<?php echo $current_lang; ?>">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Task Criteria - Admin Panel</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800;900&display=swap" rel="stylesheet">
    <style>
        body { font-family:'Inter',sans-serif; }
        .lbl { display:block; font-size:10px; font-weight:800; color:#64748b; margin-bottom:.25rem; text-transform:uppercase; letter-spacing:.05em; }
        .fld { width:100%; padding:.55rem .7rem; background:#fff; border:1.5px solid #cbd5e1; border-radius:.7rem; font-size:.8rem; outline:none; color:#0f172a; }
        .fld:focus { border-color:#6366f1; box-shadow:0 0 0 3px rgba(99,102,241,.14); }
        .tc-pill { display:inline-flex; align-items:center; gap:.4rem; padding:.55rem .9rem; border-radius:.8rem;
                   font-size:12px; font-weight:800; text-decoration:none; color:#64748b; background:#fff; border:1px solid #e2e8f0; }
        .tc-pill.on { background:#0f172a; color:#fff; border-color:#0f172a; }
        .tc-pill b { font-size:10px; padding:.05rem .4rem; border-radius:999px; background:rgba(100,116,139,.16); }
        .tc-pill.on b { background:rgba(255,255,255,.22); }
        .tc-card { background:#fff; border:1px solid #e2e8f0; border-radius:1rem; }
        .tc-set { font-size:10px; font-weight:900; text-transform:uppercase; letter-spacing:.06em; color:#4f46e5; }
    </style>
</head>
<body class="bg-gray-50" x-data="{ sidebarOpen: window.innerWidth >= 768 }">
<div class="flex h-screen overflow-hidden">

    <?php include __DIR__ . '/includes/sidebar.php'; ?>

    <div class="flex-1 flex flex-col min-w-0 bg-gray-100 overflow-hidden">
        <header class="h-20 bg-white text-slate-800 flex items-center justify-between px-4 lg:px-8 shadow-sm border-b border-gray-200 z-40 relative">
            <div class="flex items-center">
                <button @click="sidebarOpen = !sidebarOpen" class="p-2 mr-3 text-slate-500 hover:text-emerald-600 rounded-lg"><i class="fas fa-bars text-xl"></i></button>
                <div>
                    <h2 class="text-xl font-bold text-slate-800">Task Criteria</h2>
                    <p class="text-[11px] text-slate-400">Decide who lands on each tab of Activity &amp; Task</p>
                </div>
            </div>
            <a href="activity_task.php?role=<?php echo urlencode($SCOPE); ?>&mod=<?php echo urlencode($MOD); ?>"
               class="inline-flex items-center gap-2 px-4 py-2.5 rounded-xl bg-slate-900 text-white text-sm font-bold">
                <i class="fas fa-list-check"></i> Open Activity &amp; Task
            </a>
        </header>

        <main class="flex-1 overflow-y-auto p-4 md:p-6">
            <?php echo alist_styles(); ?>

            <?php if (isset($success_msg)): ?>
            <div class="mb-4 bg-emerald-50 border border-emerald-200 text-emerald-700 px-4 py-3 rounded-xl flex items-center shadow-sm">
                <i class="fas fa-check-circle mr-2"></i><span class="font-medium"><?php echo htmlspecialchars($success_msg); ?></span>
            </div>
            <?php endif; ?>
            <?php if (isset($error_msg)): ?>
            <div class="mb-4 bg-rose-50 border border-rose-200 text-rose-700 px-4 py-3 rounded-xl flex items-center shadow-sm">
                <i class="fas fa-triangle-exclamation mr-2"></i><span class="font-medium"><?php echo htmlspecialchars($error_msg); ?></span>
            </div>
            <?php endif; ?>

            <!-- audience -->
            <p class="tc-set mb-2">1 · Whose tab</p>
            <div class="flex flex-wrap gap-2 mb-4">
                <?php foreach ($ROLES as $rk => $rv): ?>
                    <a href="task_criteria.php?role=<?php echo $rk; ?>&mod=<?php echo urlencode($MOD); ?>"
                       class="tc-pill <?php echo $SCOPE === $rk ? 'on' : ''; ?>">
                        <i class="fas <?php echo $rv[1]; ?>"></i><?php echo esc($rv[0]); ?>
                    </a>
                <?php endforeach; ?>
            </div>

            <!-- tab -->
            <p class="tc-set mb-2">2 · Which tab</p>
            <div class="flex flex-wrap gap-2 mb-5">
                <?php foreach ($MODULES as $mk => $mv): ?>
                    <a href="task_criteria.php?role=<?php echo urlencode($SCOPE); ?>&mod=<?php echo $mk; ?>"
                       class="tc-pill <?php echo $MOD === $mk ? 'on' : ''; ?>">
                        <i class="fas <?php echo $mv[1]; ?>"></i><?php echo esc($mv[0]); ?>
                        <?php if ($tab_counts[$mk] !== null): ?><b><?php echo number_format($tab_counts[$mk]); ?></b><?php endif; ?>
                    </a>
                <?php endforeach; ?>
            </div>

            <form method="POST" class="grid grid-cols-1 xl:grid-cols-3 gap-5">
                <input type="hidden" name="scope_role" value="<?php echo htmlspecialchars($SCOPE); ?>">
                <input type="hidden" name="module_key" value="<?php echo htmlspecialchars($MOD); ?>">

                <!-- ============ the rule ============ -->
                <div class="xl:col-span-2 space-y-4">
                    <div class="tc-card p-5">
                        <div class="flex flex-wrap items-center justify-between gap-3 mb-4">
                            <div>
                                <h3 class="text-base font-extrabold text-slate-800">
                                    <?php echo esc($ROLES[$SCOPE][0]); ?> &rarr; <?php echo esc($MODULES[$MOD][0]); ?>
                                </h3>
                                <p class="text-[11.5px] text-slate-500 mt-0.5">
                                    <?php if ($CRIT['saved']): ?>
                                        Your own rule is in use.
                                    <?php else: ?>
                                        Using the built-in default — save once to make it your own.
                                    <?php endif; ?>
                                </p>
                            </div>
                            <span class="px-3 py-1.5 rounded-xl bg-indigo-50 text-indigo-700 text-xs font-black">
                                <?php echo number_format($matched); ?> match now
                            </span>
                        </div>

                        <div class="grid grid-cols-1 md:grid-cols-3 gap-3 mb-5">
                            <div class="md:col-span-2">
                                <label class="lbl">What to call this list</label>
                                <input name="label" value="<?php echo esc($CRIT['label']); ?>" class="fld"
                                       placeholder="e.g. Never subscribed">
                            </div>
                            <div>
                                <label class="lbl">Order</label>
                                <select name="sort_field" class="fld">
                                    <?php foreach (tcrit_sorts() as $sk => $sv): ?>
                                        <option value="<?php echo $sk; ?>" <?php echo $CRIT['sort'] === $sk ? 'selected' : ''; ?>><?php echo $sv; ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>

                        <?php foreach (tcrit_groups() as $g): if (empty($by_group[$g])) continue; ?>
                        <div class="mb-4">
                            <p class="text-[11px] font-bold uppercase tracking-wide text-slate-500 mb-2 border-b pb-1"><?php echo esc($g); ?></p>
                            <div class="grid grid-cols-1 md:grid-cols-2 gap-3">
                                <?php foreach ($by_group[$g] as $k => $def):
                                    $cur = isset($CRIT['rules'][$k]) ? (string)$CRIT['rules'][$k] : '';
                                ?>
                                <div>
                                    <label class="lbl"><?php echo esc($def[0]); ?></label>
                                    <?php if ($def[2] === 'choice'): ?>
                                        <select name="c_<?php echo $k; ?>" class="fld">
                                            <?php foreach ($def[3] as $ov => $ol): ?>
                                                <option value="<?php echo esc($ov); ?>" <?php echo $cur === (string)$ov ? 'selected' : ''; ?>><?php echo esc($ol); ?></option>
                                            <?php endforeach; ?>
                                        </select>
                                    <?php elseif ($def[2] === 'days'): ?>
                                        <input type="number" min="0" name="c_<?php echo $k; ?>" value="<?php echo esc($cur); ?>" class="fld" placeholder="days">
                                    <?php else: ?>
                                        <input name="c_<?php echo $k; ?>" value="<?php echo esc($cur); ?>" class="fld" placeholder="any">
                                    <?php endif; ?>
                                    <?php if (!empty($def[4])): ?>
                                        <p class="text-[10px] text-slate-400 mt-1"><?php echo esc($def[4]); ?></p>
                                    <?php endif; ?>
                                </div>
                                <?php endforeach; ?>
                            </div>
                        </div>
                        <?php endforeach; ?>

                        <div class="flex flex-wrap items-center gap-2 pt-3 border-t border-slate-100">
                            <label class="flex items-center gap-2 text-[12px] font-bold text-slate-600 mr-auto">
                                <input type="checkbox" name="status" value="1" <?php echo (int)$CRIT['status'] === 1 ? 'checked' : ''; ?> class="rounded">
                                Show this list on the tab
                            </label>
                            <button type="submit" name="reset_criteria" value="1"
                                    onclick="return confirm('Put the built-in default back for this tab?')"
                                    class="px-4 py-2.5 rounded-xl bg-slate-100 text-slate-600 text-sm font-bold">Reset to default</button>
                            <button type="submit" name="save_criteria" value="1"
                                    class="px-5 py-2.5 rounded-xl bg-indigo-600 hover:bg-indigo-700 text-white text-sm font-bold shadow">
                                <i class="fas fa-save mr-1"></i>Save criteria
                            </button>
                        </div>
                    </div>
                </div>

                <!-- ============ live preview ============ -->
                <div class="space-y-4">
                    <div class="tc-card p-5">
                        <h3 class="text-sm font-extrabold text-slate-800 mb-1"><i class="fas fa-eye text-indigo-500 mr-1.5"></i>Who this catches</h3>
                        <p class="text-[11.5px] text-slate-500 mb-3"><?php echo esc(tcrit_summary($CRIT['rules'])); ?></p>

                        <p class="text-3xl font-extrabold text-slate-800 leading-none"><?php echo number_format($matched); ?></p>
                        <p class="text-[11px] text-slate-400 font-semibold mb-4">people right now</p>

                        <?php if (empty($sample)): ?>
                            <p class="text-[12px] text-slate-400 text-center py-6 bg-slate-50 rounded-xl">
                                Nobody matches yet. Loosen a condition above.
                            </p>
                        <?php else: ?>
                            <div class="space-y-1.5 max-h-72 overflow-y-auto">
                                <?php foreach ($sample as $sm): ?>
                                    <div class="flex items-center gap-2 px-3 py-2 rounded-lg bg-slate-50 border border-slate-100">
                                        <span class="w-7 h-7 rounded-lg bg-indigo-100 text-indigo-700 flex items-center justify-center text-[11px] font-black flex-shrink-0">
                                            <?php echo strtoupper(mb_substr((string)$sm['name'], 0, 1)); ?>
                                        </span>
                                        <div class="min-w-0 flex-1">
                                            <p class="text-[12px] font-bold text-slate-700 truncate"><?php echo esc($sm['name']); ?></p>
                                            <p class="text-[10px] text-slate-400"><?php echo esc($sm['mobile']); ?></p>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                            <?php if ($matched > count($sample)): ?>
                                <p class="text-[10.5px] text-slate-400 mt-2 text-center">
                                    …and <?php echo number_format($matched - count($sample)); ?> more
                                </p>
                            <?php endif; ?>
                        <?php endif; ?>

                        <a href="activity_task.php?role=<?php echo urlencode($SCOPE); ?>&mod=<?php echo urlencode($MOD); ?>&view=people"
                           class="mt-4 flex items-center justify-center gap-2 w-full py-2.5 rounded-xl bg-slate-900 text-white text-xs font-bold">
                            <i class="fas fa-users"></i> Open the full list and assign
                        </a>
                    </div>

                    <div class="tc-card p-4 text-[11.5px] text-slate-500 leading-relaxed">
                        <p class="font-bold text-slate-700 mb-1"><i class="fas fa-circle-info text-indigo-500 mr-1"></i>How the tabs read this</p>
                        Every condition you set is combined with <b>AND</b> — somebody has to match all of them.
                        Leaving a condition on <b>Any</b> means it is ignored.
                        <br><br>
                        <b>Existing task on this tab</b> is the useful one: set it to
                        <b>No open task yet</b> and a person drops off the list the moment they are handed to somebody,
                        so the same member is never assigned twice.
                    </div>
                </div>
            </form>
        </main>
    </div>
</div>
</body>
</html>
