<?php
/**
 * admin/settingss.php — Chat Foreigners admin settings
 */
require_once '../config/database.php';
require_once '../includes/functions.php';
$pageTitle = 'Chat Foreigners Settings';
include 'side.php';
require_once 'admin_protect.php';
requirePermission('system_settings');

$conn = getConnection();

// ── POST handler ───────────────────────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    if ($action === 'save_settings') {
        $fee        = max(0, floatval($_POST['upgrade_fee'] ?? 200));
        $enabled    = isset($_POST['feature_enabled']) ? '1' : '0';
        $apiKey     = trim($_POST['anthropic_api_key'] ?? '');

        updateSetting('chat_foreigners_upgrade_fee', $fee);
        updateSetting('chat_foreigners_enabled',     $enabled);
        if (!empty($apiKey)) updateSetting('anthropic_api_key', $apiKey);

        setFlash('success', 'Chat settings updated!');
        redirect('settingss.php');
    }

    if ($action === 'grant_user') {
        $uid = intval($_POST['user_id']);
        $conn->prepare("UPDATE users SET chat_foreigners_access=1, chat_upgrade_date=NOW() WHERE id=?")->bind_param("i",$uid);
        $s = $conn->prepare("UPDATE users SET chat_foreigners_access=1, chat_upgrade_date=NOW() WHERE id=?");
        $s->bind_param("i",$uid); $s->execute();
        setFlash('success','Access granted!');
        redirect('settingss.php');
    }

    if ($action === 'revoke_user') {
        $uid = intval($_POST['user_id']);
        $s = $conn->prepare("UPDATE users SET chat_foreigners_access=0, chat_upgrade_date=NULL WHERE id=?");
        $s->bind_param("i",$uid); $s->execute();
        setFlash('success','Access revoked!');
        redirect('settingss.php');
    }

    if ($action === 'bulk_grant') {
        $conn->query("UPDATE users SET chat_foreigners_access=1, chat_upgrade_date=NOW() WHERE status='active' AND chat_foreigners_access=0");
        $count = $conn->affected_rows;
        setFlash('success', "Access granted to $count active users!");
        redirect('settingss.php');
    }
}

// ── Settings ──────────────────────────────────────────────────────────────────
$upgradeFee    = floatval(getSetting('chat_foreigners_upgrade_fee', '200'));
$featureOn     = getSetting('chat_foreigners_enabled', '1') === '1';
$apiKeySet     = !empty(getSetting('anthropic_api_key', ''));

// ── Stats ─────────────────────────────────────────────────────────────────────
$totalUsers      = $conn->query("SELECT COUNT(*) FROM users WHERE status='active'")->fetch_row()[0];
$usersWithAccess = $conn->query("SELECT COUNT(*) FROM users WHERE chat_foreigners_access=1")->fetch_row()[0];
$noAccess        = $totalUsers - $usersWithAccess;
$upgradesToday   = $conn->query("SELECT COUNT(*) FROM users WHERE chat_foreigners_access=1 AND DATE(chat_upgrade_date)=CURDATE()")->fetch_row()[0];
$totalRevenue    = $conn->query("SELECT COALESCE(SUM(amount),0) FROM chat_upgrade_payments WHERE status='completed'")->fetch_row()[0];

// ── User search ───────────────────────────────────────────────────────────────
$search   = trim($_GET['search'] ?? '');
$filter   = $_GET['filter'] ?? 'all';
$page     = max(1, intval($_GET['page'] ?? 1));
$perPage  = 25;
$offset   = ($page - 1) * $perPage;

$where = "WHERE 1=1";
$params = [];
$types  = '';

if ($search) {
    $like = "%$search%";
    $where .= " AND (u.username LIKE ? OR u.phone LIKE ?)";
    $params[] = $like; $params[] = $like; $types .= 'ss';
}
if ($filter === 'access') {
    $where .= " AND u.chat_foreigners_access=1";
} elseif ($filter === 'no_access') {
    $where .= " AND u.chat_foreigners_access=0";
}

$totalQ = $conn->prepare("SELECT COUNT(*) FROM users u $where");
if ($params) { $totalQ->bind_param($types, ...$params); }
$totalQ->execute();
$totalRows = $totalQ->get_result()->fetch_row()[0];
$totalPages = ceil($totalRows / $perPage);

$usersQ = $conn->prepare("
    SELECT u.id, u.username, u.phone, u.country, u.status, u.chat_foreigners_access, u.chat_upgrade_date
    FROM users u $where ORDER BY u.id DESC LIMIT $perPage OFFSET $offset
");
if ($params) { $usersQ->bind_param($types, ...$params); }
$usersQ->execute();
$users = $usersQ->get_result()->fetch_all(MYSQLI_ASSOC);

$flash = getFlash();
?>
<style>
.cs-stats{display:grid;grid-template-columns:repeat(auto-fit,minmax(130px,1fr));gap:12px;margin-bottom:22px}
.cs-stat{background:var(--card-bg);border:1px solid var(--border-color);border-radius:14px;padding:14px;text-align:center}
.cs-stat-v{font-size:22px;font-weight:900;color:var(--text-primary);margin-bottom:3px}
.cs-stat-l{font-size:11px;color:var(--text-secondary);font-weight:600}
.cs-card{background:var(--card-bg);border:1px solid var(--border-color);border-radius:14px;padding:20px;margin-bottom:18px}
.cs-title{font-size:15px;font-weight:800;color:var(--text-primary);margin-bottom:14px;display:flex;align-items:center;gap:8px}
.cs-form-row{margin-bottom:14px}
.cs-lbl{font-size:12px;font-weight:700;color:var(--text-primary);margin-bottom:5px;display:block}
.cs-inp{width:100%;padding:10px 13px;background:var(--dark-bg);border:1.5px solid var(--border-color);border-radius:9px;color:var(--text-primary);font-size:13px;box-sizing:border-box}
.cs-inp:focus{outline:none;border-color:var(--theme-color)}
.cs-hint{font-size:11px;color:var(--text-secondary);margin-top:4px;line-height:1.5}
.cs-sw{display:flex;align-items:center;gap:10px;margin-bottom:14px}
.switch{position:relative;width:44px;height:24px;flex-shrink:0}
.switch input{opacity:0;width:0;height:0}
.slider{position:absolute;cursor:pointer;inset:0;background:var(--border-color);transition:.3s;border-radius:24px}
.slider:before{position:absolute;content:'';height:18px;width:18px;left:3px;bottom:3px;background:#fff;transition:.3s;border-radius:50%}
input:checked+.slider{background:var(--theme-color)}
input:checked+.slider:before{transform:translateX(20px)}
.cs-btn{padding:10px 20px;border-radius:9px;border:none;cursor:pointer;font-size:13px;font-weight:700;display:inline-flex;align-items:center;gap:6px;transition:all .18s}
.cs-btn-pri{background:linear-gradient(135deg,var(--theme-color),#ec4899);color:#fff}
.cs-btn-pri:hover{transform:translateY(-2px);box-shadow:0 6px 18px rgba(var(--theme-rgb),.35)}
.cs-btn-grn{background:linear-gradient(135deg,#10b981,#059669);color:#fff}
.cs-btn-red{background:linear-gradient(135deg,#ef4444,#dc2626);color:#fff}
.cs-btn-sm{padding:5px 11px;font-size:11.5px;height:28px}
/* Users table */
.cs-filter-row{display:flex;gap:8px;flex-wrap:wrap;margin-bottom:12px;align-items:center}
.cs-filter-btn{padding:5px 13px;border-radius:7px;border:1px solid var(--border-color);background:none;color:var(--text-secondary);font-size:12px;font-weight:600;cursor:pointer;transition:.15s}
.cs-filter-btn.on{background:var(--theme-color);border-color:var(--theme-color);color:#fff}
.cs-table-wrap{overflow-x:auto}
table.cs-tbl{width:100%;border-collapse:collapse;font-size:12.5px}
.cs-tbl th{padding:8px 10px;font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:.5px;color:var(--text-secondary);background:var(--darker-bg);text-align:left;white-space:nowrap}
.cs-tbl td{padding:9px 10px;border-bottom:1px solid var(--border-color);color:var(--text-primary);vertical-align:middle}
.cs-tbl tr:last-child td{border-bottom:none}
.cs-tbl tr:hover td{background:rgba(99,102,241,.04)}
.cs-badge{display:inline-flex;align-items:center;gap:4px;padding:2px 8px;border-radius:6px;font-size:10.5px;font-weight:700}
.cs-badge-grn{background:rgba(16,185,129,.12);color:#10b981;border:1px solid rgba(16,185,129,.25)}
.cs-badge-red{background:rgba(239,68,68,.1);color:#ef4444;border:1px solid rgba(239,68,68,.2)}
.cs-badge-yel{background:rgba(245,158,11,.1);color:#f59e0b;border:1px solid rgba(245,158,11,.2)}
.cs-flash{padding:10px 14px;border-radius:10px;margin-bottom:14px;font-size:13px;font-weight:600}
.cs-flash.success{background:rgba(16,185,129,.1);border:1px solid rgba(16,185,129,.3);color:#4ade80}
.cs-flash.error{background:rgba(239,68,68,.1);border:1px solid rgba(239,68,68,.3);color:#f87171}
.cs-pagi{display:flex;gap:6px;flex-wrap:wrap;margin-top:14px;align-items:center}
.cs-pagi-btn{height:30px;padding:0 11px;border-radius:8px;border:1px solid var(--border-color);background:none;color:var(--text-secondary);font-size:12px;font-weight:600;cursor:pointer;text-decoration:none;display:inline-flex;align-items:center}
.cs-pagi-btn.on{background:var(--theme-color);border-color:var(--theme-color);color:#fff}
.cs-pagi-btn:hover:not(.on){border-color:var(--theme-color);color:var(--theme-color)}
</style>

<div class="page-header">
    <h1 class="page-title">🌍 Chat Foreigners Settings</h1>
    <p class="page-subtitle">Manage upgrade fees, feature toggle, and user access</p>
</div>

<?php if($flash): ?><div class="cs-flash <?= $flash['type'] ?>"><?= htmlspecialchars($flash['message']) ?></div><?php endif; ?>

<!-- Stats -->
<div class="cs-stats">
    <div class="cs-stat">
        <div class="cs-stat-v"><?= number_format($totalRevenue) ?></div>
        <div class="cs-stat-l">Ksh Revenue</div>
    </div>
    <div class="cs-stat">
        <div class="cs-stat-v" style="color:#10b981"><?= $usersWithAccess ?></div>
        <div class="cs-stat-l">Have Access</div>
    </div>
    <div class="cs-stat">
        <div class="cs-stat-v" style="color:#f59e0b"><?= $noAccess ?></div>
        <div class="cs-stat-l">No Access</div>
    </div>
    <div class="cs-stat">
        <div class="cs-stat-v" style="color:#6366f1"><?= $upgradesToday ?></div>
        <div class="cs-stat-l">Upgrades Today</div>
    </div>
    <div class="cs-stat">
        <div class="cs-stat-v" style="color:<?= $featureOn?'#10b981':'#ef4444' ?>"><?= $featureOn?'ON':'OFF' ?></div>
        <div class="cs-stat-l">Feature Status</div>
    </div>
</div>

<!-- Settings form -->
<div class="cs-card">
    <div class="cs-title"><i class="fas fa-cog" style="color:var(--theme-color)"></i> Chat Feature Settings</div>
    <form method="POST">
        <input type="hidden" name="action" value="save_settings">

        <div class="cs-sw">
            <label class="switch">
                <input type="checkbox" name="feature_enabled" <?= $featureOn?'checked':'' ?>>
                <span class="slider"></span>
            </label>
            <div>
                <strong>Enable Chat Foreigners</strong>
                <div class="cs-hint">Disable to temporarily hide the feature from all users</div>
            </div>
        </div>

        <div class="cs-form-row">
            <label class="cs-lbl">Upgrade Fee (Ksh)</label>
            <input type="number" name="upgrade_fee" class="cs-inp" min="0" step="0.01"
                value="<?= htmlspecialchars($upgradeFee) ?>" style="max-width:200px">
            <div class="cs-hint">One-time fee users pay from their wallet to unlock global chat. Set 0 for free access.</div>
        </div>

        <div class="cs-form-row">
            <label class="cs-lbl">Anthropic API Key (Claude AI)</label>
            <input type="password" name="anthropic_api_key" class="cs-inp" placeholder="Leave blank to keep current">
            <div class="cs-hint">
                <?= $apiKeySet ? '<span style="color:#10b981;font-weight:700">✅ API key is set</span>' : '<span style="color:#ef4444;font-weight:700">❌ No API key — AI chat will use fallback replies</span>' ?>
                — Get yours at <a href="https://console.anthropic.com" target="_blank" style="color:var(--theme-color)">console.anthropic.com</a>
            </div>
        </div>

        <button type="submit" class="cs-btn cs-btn-pri"><i class="fas fa-save"></i> Save Settings</button>
    </form>
</div>

<!-- Bulk actions -->
<div class="cs-card">
    <div class="cs-title"><i class="fas fa-bolt" style="color:#fbbf24"></i> Bulk Actions</div>
    <form method="POST" onsubmit="return confirm('Grant free access to ALL active users who don\'t have it yet?')">
        <input type="hidden" name="action" value="bulk_grant">
        <p style="font-size:13px;color:var(--text-secondary);margin-bottom:12px">
            Grant free Chat Foreigners access to all <strong style="color:var(--text-primary)"><?= $noAccess ?></strong> active users who don't have it yet.
        </p>
        <button type="submit" class="cs-btn cs-btn-grn"><i class="fas fa-users"></i> Grant Free Access to All</button>
    </form>
</div>

<!-- User management -->
<div class="cs-card">
    <div class="cs-title"><i class="fas fa-users" style="color:#06b6d4"></i> User Access Management</div>

    <form method="GET" action="settingss.php" style="display:flex;gap:8px;margin-bottom:12px;flex-wrap:wrap">
        <input type="text" name="search" class="cs-inp" placeholder="Search username or phone…" value="<?= htmlspecialchars($search) ?>" style="flex:1;min-width:180px;max-width:300px;height:38px;padding:0 12px">
        <input type="hidden" name="filter" value="<?= htmlspecialchars($filter) ?>">
        <button type="submit" class="cs-btn cs-btn-pri" style="padding:0 16px;height:38px"><i class="fas fa-search"></i> Search</button>
        <?php if($search): ?><a href="settingss.php?filter=<?= $filter ?>" class="cs-btn" style="background:rgba(239,68,68,.1);border:1px solid rgba(239,68,68,.2);color:#ef4444;padding:0 12px;height:38px;text-decoration:none"><i class="fas fa-xmark"></i> Clear</a><?php endif; ?>
    </form>

    <div class="cs-filter-row">
        <?php $filters=[['all','All Users'],['access','Has Access'],['no_access','No Access']]; ?>
        <?php foreach($filters as [$k,$l]): ?>
        <a href="?filter=<?= $k ?><?= $search?'&search='.urlencode($search):'' ?>" class="cs-filter-btn <?= $filter===$k?'on':'' ?>"><?= $l ?></a>
        <?php endforeach; ?>
        <span style="font-size:12px;color:var(--text-secondary);margin-left:auto"><?= number_format($totalRows) ?> users</span>
    </div>

    <div class="cs-table-wrap">
        <table class="cs-tbl">
            <thead>
                <tr>
                    <th>User</th>
                    <th>Country</th>
                    <th>Access</th>
                    <th>Upgraded</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
            <?php foreach ($users as $u): ?>
            <tr>
                <td>
                    <div style="font-weight:700"><?= htmlspecialchars($u['username']) ?></div>
                    <div style="font-size:10.5px;color:var(--text-secondary)"><?= htmlspecialchars($u['phone']??'') ?></div>
                </td>
                <td><?= htmlspecialchars($u['country']??'—') ?></td>
                <td>
                    <?php if($u['chat_foreigners_access']): ?>
                    <span class="cs-badge cs-badge-grn"><i class="fas fa-check"></i> Active</span>
                    <?php else: ?>
                    <span class="cs-badge cs-badge-red"><i class="fas fa-lock"></i> Locked</span>
                    <?php endif; ?>
                </td>
                <td style="font-size:11px;color:var(--text-secondary)">
                    <?= $u['chat_upgrade_date'] ? date('d M Y', strtotime($u['chat_upgrade_date'])) : '—' ?>
                </td>
                <td>
                    <?php if($u['chat_foreigners_access']): ?>
                    <form method="POST" style="display:inline" onsubmit="return confirm('Revoke access from <?= htmlspecialchars($u['username']) ?>?')">
                        <input type="hidden" name="action" value="revoke_user">
                        <input type="hidden" name="user_id" value="<?= $u['id'] ?>">
                        <button type="submit" class="cs-btn cs-btn-red cs-btn-sm"><i class="fas fa-ban"></i> Revoke</button>
                    </form>
                    <?php else: ?>
                    <form method="POST" style="display:inline">
                        <input type="hidden" name="action" value="grant_user">
                        <input type="hidden" name="user_id" value="<?= $u['id'] ?>">
                        <button type="submit" class="cs-btn cs-btn-grn cs-btn-sm"><i class="fas fa-unlock"></i> Grant</button>
                    </form>
                    <?php endif; ?>
                </td>
            </tr>
            <?php endforeach; ?>
            <?php if(empty($users)): ?>
            <tr><td colspan="5" style="text-align:center;padding:30px;color:var(--text-secondary)">No users found.</td></tr>
            <?php endif; ?>
            </tbody>
        </table>
    </div>

    <!-- Pagination -->
    <?php if($totalPages > 1): ?>
    <div class="cs-pagi">
        <?php if($page>1): ?><a href="?page=<?= $page-1 ?>&filter=<?= $filter ?>&search=<?= urlencode($search) ?>" class="cs-pagi-btn">‹ Prev</a><?php endif; ?>
        <?php for($p=max(1,$page-2);$p<=min($totalPages,$page+2);$p++): ?>
        <a href="?page=<?= $p ?>&filter=<?= $filter ?>&search=<?= urlencode($search) ?>" class="cs-pagi-btn <?= $p===$page?'on':'' ?>"><?= $p ?></a>
        <?php endfor; ?>
        <?php if($page<$totalPages): ?><a href="?page=<?= $page+1 ?>&filter=<?= $filter ?>&search=<?= urlencode($search) ?>" class="cs-pagi-btn">Next ›</a><?php endif; ?>
    </div>
    <?php endif; ?>
</div>

<?php include 'footer.php'; ?>