<?php
require_once '../config/database.php';
require_once '../includes/functions.php';
require_once '../includes/lipalink.php'; // LipaLink/PesaFlux API helper

if (session_status() === PHP_SESSION_NONE) session_start();
if (!isset($_SESSION['user_id'])) redirect('../login.php');

$userId = $_SESSION['user_id'];
$conn   = getConnection();

$stmt = $conn->prepare("SELECT u.*, c.currency_symbol, c.currency_code, c.exchange_rate FROM users u LEFT JOIN countries c ON u.country=c.name WHERE u.id=?");
$stmt->bind_param("i",$userId); $stmt->execute();
$userData = $stmt->get_result()->fetch_assoc();
$cs = $userData['currency_symbol'] ?? 'Ksh';

// ── Check access (admin-granted or paid) — re-checked on EVERY page load ────
$hasAccess   = false;
$accessSource = null; // 'admin' or 'paid'
$accessExpiry = null; // for paid: timestamp when access expires

// ── 1. Admin-granted access ───────────────────────────────────────────────
// Checks status='active' — if admin revoked (status='revoked'), this returns nothing
$accessChk = $conn->query("SHOW TABLES LIKE 'chat_foreigners_access'");
if ($accessChk && $accessChk->num_rows > 0) {
    $aStmt = $conn->prepare(
        "SELECT status FROM chat_foreigners_access
         WHERE user_id=? AND status='active' LIMIT 1"
    );
    $aStmt->bind_param("i", $userId);
    $aStmt->execute();
    $aRow = $aStmt->get_result()->fetch_assoc();
    if ($aRow && $aRow['status'] === 'active') {
        $hasAccess    = true;
        $accessSource = 'admin';
    }
}

// ── 2. Paid access (only if no admin access) ─────────────────────────────
// Checks most recent COMPLETED payment within the 30-day window.
// Also verifies admin hasn't revoked this user in the access table.
if (!$hasAccess) {
    // First check if admin explicitly revoked this user
    $revokedChk = false;
    if ($accessChk && $accessChk->num_rows > 0) {
        $rStmt = $conn->prepare(
            "SELECT status FROM chat_foreigners_access
             WHERE user_id=? AND status='revoked' LIMIT 1"
        );
        $rStmt->bind_param("i", $userId);
        $rStmt->execute();
        $rRow = $rStmt->get_result()->fetch_assoc();
        if ($rRow) $revokedChk = true; // admin explicitly revoked — block paid access too
    }

    if (!$revokedChk) {
        $paidChk = $conn->query("SHOW TABLES LIKE 'chat_foreigners_payments'");
        if ($paidChk && $paidChk->num_rows > 0) {
            $pStmt = $conn->prepare(
                "SELECT * FROM chat_foreigners_payments
                 WHERE user_id=? AND status='completed'
                 ORDER BY created_at DESC LIMIT 1"
            );
            $pStmt->bind_param("i", $userId);
            $pStmt->execute();
            $pRow = $pStmt->get_result()->fetch_assoc();
            if ($pRow) {
                $expiresAt    = strtotime($pRow['created_at']) + (30 * 86400);
                $accessExpiry = $expiresAt;
                if (time() < $expiresAt) {
                    $hasAccess    = true;
                    $accessSource = 'paid';
                }
            }
        }
    }
}

$unlockFee    = getSetting('chat_foreigners_unlock_fee', '100');
$redirectLink = getSetting('chat_foreigners_redirect_link', '');

// Chat Foreigners uses its OWN dedicated gateway credentials
$cfApiKey    = getSetting('chat_foreigners_api_key', '');
$cfBizId     = intval(getSetting('chat_foreigners_business_id', 0));

// ── Handle unlock payment initiation ─────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'initiate_unlock') {
    $phone = lipalink_format_phone($_POST['phone'] ?? '');
    if (!lipalink_valid_phone($phone)) {
        setFlash('error','Invalid phone number. Use format 07XXXXXXXX');
        redirect('chat_foreigners.php');
    }

    // Initiate STK push via HashPay/active gateway
    $amount   = floatval($unlockFee);
    $ref      = 'CF_UNLOCK_'.$userId.'_'.time();
    $callback = rtrim(getSetting('pesaflux_callback_url',''),'/');
    $callback = str_replace('mpesa/callback.php','chat_foreigners_callback.php',$callback);

    if (empty($cfApiKey) || $cfBizId < 1) {
        setFlash('error','Chat Foreigners payment gateway not configured. Contact admin.');
        redirect('chat_foreigners.php');
    }

    // ── Fire STK push via LipaLink API ──────────────────────────────
    $decoded = lipalink_stk_push($phone, intval($amount), $ref, $cfApiKey, $cfBizId);

    // Save pending payment record
    $conn->query("CREATE TABLE IF NOT EXISTS chat_foreigners_payments (
        id INT AUTO_INCREMENT PRIMARY KEY,
        user_id INT NOT NULL,
        phone VARCHAR(20) NOT NULL,
        amount DECIMAL(10,2) NOT NULL,
        reference VARCHAR(100) UNIQUE,
        checkout_request_id VARCHAR(200),
        status ENUM('pending','completed','failed') DEFAULT 'pending',
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        completed_at DATETIME NULL,
        INDEX idx_user (user_id), INDEX idx_ref (reference), INDEX idx_status (status)
    )");

    $insStmt = $conn->prepare("INSERT INTO chat_foreigners_payments (user_id,phone,amount,reference,checkout_request_id,status) VALUES (?,?,?,?,?,'pending')");
    $insStmt->bind_param("isdss",$userId,$phone,$amount,$ref,$ref); // will be updated to real tx_id on STK success
    $insStmt->execute();

    // lipalink_stk_push() returns: { success, transaction_id, message } or { success:false, error }
    if (!empty($decoded['success']) && !empty($decoded['transaction_id'])) {
        $transactionId = $decoded['transaction_id']; // PFX... — store as checkout_request_id
        $updRef = $conn->prepare("UPDATE chat_foreigners_payments
            SET checkout_request_id=? WHERE reference=? AND user_id=?");
        $updRef->bind_param("ssi", $transactionId, $ref, $userId);
        $updRef->execute();
        $_SESSION['cf_pending_ref'] = $ref;
        setFlash('success', ($decoded['message'] ?? 'STK Push sent!') . ' Enter your M-PESA PIN.');
    } else {
        $errMsg = $decoded['error'] ?? 'Payment initiation failed. Please try again.';
        setFlash('error', $errMsg);
    }
    redirect('chat_foreigners.php');
}

// ── Check pending payment status ──────────────────────────────────────────
$pendingRef = $_SESSION['cf_pending_ref'] ?? null;
$pendingPayment = null;
if ($pendingRef) {
    $pChk = $conn->prepare("SELECT * FROM chat_foreigners_payments WHERE reference=? AND user_id=? LIMIT 1");
    $pChk->bind_param("si",$pendingRef,$userId); $pChk->execute();
    $pendingPayment = $pChk->get_result()->fetch_assoc();
    if ($pendingPayment && $pendingPayment['status'] === 'completed') {
        $hasAccess = true; $accessSource = 'paid';
        unset($_SESSION['cf_pending_ref']);
    }
}

// ── Fetch chat tasks ───────────────────────────────────────────────────────
$chatTasks = [];
if ($hasAccess) {
    $tq = $conn->prepare("
        SELECT t.*,
            (SELECT COUNT(*) FROM task_completions WHERE task_id=t.id AND user_id=? AND DATE(created_at)=CURDATE()) as today_done,
            (SELECT COUNT(*) FROM task_completions WHERE task_id=t.id AND status='completed') as total_done
        FROM tasks t WHERE t.task_type='chat' AND t.status='active'
        ORDER BY t.featured DESC, t.created_at ASC
    ");
    $tq->bind_param("i",$userId); $tq->execute();
    $res = $tq->get_result();
    while ($r = $res->fetch_assoc()) $chatTasks[] = $r;
}

// Stats
$statsQ = $conn->prepare("SELECT COUNT(*) as total, SUM(CASE WHEN tc.status='completed' THEN 1 ELSE 0 END) as done, SUM(CASE WHEN tc.status='completed' THEN tc.reward_earned ELSE 0 END) as earned FROM task_completions tc JOIN tasks t ON t.id=tc.task_id WHERE tc.user_id=? AND t.task_type='chat'");
$statsQ->bind_param("i",$userId); $statsQ->execute();
$stats = $statsQ->get_result()->fetch_assoc();

$flash = getFlash();

$pageTitle = 'Chat Foreigners';
include 'side.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0">
<title>Chat Foreigners</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.6.0/css/all.min.css">
<style>
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap');

:root{
    --ink:#0a0814;--paper:#ffffff;
    --p:#6d28d9;--p2:#8b5cf6;--p3:#a78bfa;
    --gold:#f59e0b;--gold2:#fcd34d;
    --ok:#10b981;--err:#ef4444;
    --glass:rgba(255,255,255,0.07);
    --glass2:rgba(255,255,255,0.12);
    --bdr:rgba(255,255,255,0.1);
}
[data-theme=light]{--ink:#ffffff;--paper:#0a0814}

*{box-sizing:border-box;margin:0;padding:0}
body{font-family:'Inter',sans-serif;background:#0a0814;color:#e2d9f3;min-height:100vh;overflow-x:hidden}
.page{padding:12px;max-width:600px;margin:0 auto;width:100%}
@media(max-width:360px){.page{padding:8px}}

/* ── FLASH ── */
.flash{padding:11px 14px;border-radius:12px;font-size:12.5px;font-weight:600;margin-bottom:14px;display:flex;align-items:center;gap:8px}
.flash.success{background:rgba(16,185,129,.12);border:1px solid rgba(16,185,129,.3);color:#4ade80}
.flash.error{background:rgba(239,68,68,.12);border:1px solid rgba(239,68,68,.3);color:#f87171}

/* ══════════════════════════════
   PAGE HEADER + STATS STRIP
══════════════════════════════ */
.cf-page-hdr{
    display:flex;align-items:center;gap:8px;margin-bottom:14px;
}
.cf-page-title{
    font-size:17px;font-weight:800;color:#fff;
    display:flex;align-items:center;gap:7px;flex:1;min-width:0;
}
.cf-page-title span{font-size:19px;line-height:1;flex-shrink:0}

/* Compact stats strip */
.cf-stats-strip{
    display:grid;grid-template-columns:repeat(3,1fr);
    gap:8px;margin-bottom:16px;
}
.cf-stat{
    background:rgba(255,255,255,.05);border:1px solid rgba(255,255,255,.08);
    border-radius:14px;padding:12px 8px;text-align:center;
}
.cf-stat-val{font-size:17px;font-weight:800;color:#fff;line-height:1;word-break:break-all}
.cf-stat-lbl{font-size:9px;text-transform:uppercase;letter-spacing:.5px;color:rgba(255,255,255,.35);margin-top:4px;font-weight:600}
@media(max-width:360px){
    .cf-stat-val{font-size:13px}
    .cf-stat{padding:10px 5px}
}

/* ══════════════════════════════
   UNLOCK BLOCK SHARED STYLES
   (now lives inside .unlock-modal)
══════════════════════════════ */
@keyframes fadeUp{from{opacity:0;transform:translateY(20px)}to{opacity:1;transform:none}}
.unlock-lock{
    width:72px;height:72px;border-radius:50%;margin:0 auto 18px;
    background:conic-gradient(from 0deg,#6d28d9,#f59e0b,#6d28d9);
    padding:3px;display:flex;align-items:center;justify-content:center;
    box-shadow:0 0 40px rgba(109,40,217,.4);
    animation:lockPulse 2s ease-in-out infinite;
}
@keyframes lockPulse{0%,100%{box-shadow:0 0 40px rgba(109,40,217,.4)}50%{box-shadow:0 0 60px rgba(109,40,217,.7),0 0 80px rgba(245,158,11,.2)}}
.unlock-lock-inner{
    width:100%;height:100%;border-radius:50%;
    background:radial-gradient(circle at 35% 35%,#2e1065,#1a0533);
    display:flex;align-items:center;justify-content:center;font-size:28px;
}
.unlock-title{
    font-family:'Inter',sans-serif;font-size:19px;font-weight:800;color:#fff;margin-bottom:8px;
}
@media(min-width:380px){.unlock-title{font-size:22px}}
.unlock-sub{font-size:12.5px;color:rgba(255,255,255,.45);line-height:1.6;margin-bottom:22px}

/* Feature list */
.unlock-features{
    display:grid;grid-template-columns:1fr;gap:8px;margin-bottom:20px;text-align:left;
}
@media(min-width:360px){.unlock-features{grid-template-columns:1fr 1fr}}
.unlock-feat{
    display:flex;align-items:flex-start;gap:8px;
    padding:10px 11px;background:rgba(255,255,255,.05);border:1px solid rgba(255,255,255,.08);
    border-radius:12px;
}
.unlock-feat i{color:#a78bfa;font-size:11px;margin-top:2px;flex-shrink:0}
.unlock-feat span{font-size:11.5px;color:rgba(255,255,255,.65);line-height:1.45}

/* Price badge */
.unlock-price{
    display:inline-flex;align-items:center;gap:8px;
    padding:8px 18px;border-radius:20px;margin-bottom:20px;
    background:rgba(245,158,11,.1);border:1px solid rgba(245,158,11,.25);
}
.unlock-price-val{font-family:'Inter',sans-serif;font-size:22px;font-weight:800;color:#fcd34d}
.unlock-price-lbl{font-size:11px;color:rgba(255,255,255,.5);font-weight:600}

/* Phone form */
.unlock-form{display:flex;flex-direction:column;gap:10px}
.phone-row{display:flex;gap:8px;flex-wrap:wrap}
.phone-row .phone-inp{min-width:0;width:100%}
.phone-prefix{
    flex-shrink:0;height:48px;padding:0 11px;
    background:rgba(109,40,217,.15);border:2px solid rgba(109,40,217,.3);
    border-radius:12px;color:#a78bfa;font-size:12px;font-weight:700;
    display:flex;align-items:center;gap:5px;white-space:nowrap;
}
.phone-prefix img{height:18px;border-radius:2px}
.phone-inp{
    flex:1;height:48px;padding:0 14px;
    background:rgba(255,255,255,.06);border:2px solid rgba(255,255,255,.12);
    border-radius:12px;color:#fff;font-size:14px;font-family:'Inter',sans-serif;
    outline:none;transition:border-color .2s;
}
.phone-inp:focus{border-color:#8b5cf6;background:rgba(255,255,255,.09)}
.phone-inp::placeholder{color:rgba(255,255,255,.25)}
.unlock-btn{
    height:52px;border-radius:14px;border:none;cursor:pointer;
    background:linear-gradient(135deg,#6d28d9,#a855f7);
    color:#fff;font-size:15px;font-weight:800;font-family:'Inter',sans-serif;
    display:flex;align-items:center;justify-content:center;gap:9px;
    box-shadow:0 8px 28px rgba(109,40,217,.5);
    transition:all .2s;width:100%;
}
.unlock-btn:hover{transform:translateY(-3px);box-shadow:0 14px 38px rgba(109,40,217,.65)}
.unlock-btn:disabled{opacity:.5;cursor:not-allowed;transform:none}

/* Pending payment notice */
.pending-notice{
    display:flex;align-items:flex-start;gap:10px;
    padding:14px;background:rgba(245,158,11,.08);border:1px solid rgba(245,158,11,.2);
    border-radius:14px;margin-bottom:14px;
}
.pending-notice i{color:#fbbf24;font-size:16px;flex-shrink:0;margin-top:1px}
.pending-notice-txt{font-size:12.5px;color:rgba(255,255,255,.65);line-height:1.55}
.pending-notice-txt strong{color:#fcd34d;display:block;margin-bottom:3px}

/* Check status btn */
.check-status-btn{
    height:40px;padding:0 18px;border-radius:10px;border:1px solid rgba(109,40,217,.35);
    background:rgba(109,40,217,.12);color:#a78bfa;font-size:12px;font-weight:700;
    cursor:pointer;margin-top:8px;transition:.2s;font-family:'Inter',sans-serif;
    display:inline-flex;align-items:center;gap:6px;
}
.check-status-btn:hover{background:rgba(109,40,217,.22);border-color:rgba(109,40,217,.5)}
.cf-poll-notice{font-size:12px;font-weight:600;padding:8px 12px;border-radius:9px;margin-top:8px;display:none}
.cf-poll-notice.ok {display:block;background:rgba(16,185,129,.1);color:#4ade80;border:1px solid rgba(16,185,129,.2)}
.cf-poll-notice.err{display:block;background:rgba(239,68,68,.1);color:#f87171;border:1px solid rgba(239,68,68,.2)}
@keyframes cfPollSpin{to{transform:rotate(360deg)}}

/* ══════════════════════════════════════════════════════
   ★ LIVE FOREIGNERS LIST (10s timed view)
══════════════════════════════════════════════════════ */
.live-card{
    background:linear-gradient(155deg,rgba(109,40,217,.08),rgba(16,185,129,.04));
    border:1px solid rgba(255,255,255,.08);
    border-radius:18px;padding:14px 12px 14px;margin-bottom:18px;
    position:relative;overflow:hidden;
    animation:fadeUp .5s ease both;
}
@media(min-width:400px){.live-card{padding:16px 14px 16px}}
.live-card::before{
    content:'';position:absolute;top:0;left:0;right:0;height:2px;
    background:linear-gradient(90deg,transparent,#10b981,#6d28d9,#fcd34d,transparent);
    z-index:2;
}

.live-hdr{
    display:flex;align-items:center;gap:10px;margin-bottom:12px;
}
.live-hdr-left{flex:1;min-width:0}
.live-title{font-size:14px;font-weight:800;color:#fff;display:flex;align-items:center;gap:7px;margin-bottom:2px}
.live-dot{
    width:8px;height:8px;border-radius:50%;background:#4ade80;flex-shrink:0;
    box-shadow:0 0 0 0 rgba(74,222,128,.7);
    animation:livePulse 1.4s ease-in-out infinite;
}
@keyframes livePulse{0%,100%{box-shadow:0 0 0 0 rgba(74,222,128,.7)}50%{box-shadow:0 0 0 6px rgba(74,222,128,0)}}
.live-sub{font-size:11px;color:rgba(255,255,255,.5);line-height:1.4}

/* People grid (2 columns on mobile, 3 on bigger) */
.people-grid{
    display:grid;grid-template-columns:repeat(2,1fr);
    gap:8px;position:relative;
}
@media(min-width:420px){.people-grid{grid-template-columns:repeat(3,1fr);gap:9px}}
@media(min-width:560px){.people-grid{grid-template-columns:repeat(4,1fr)}}

.person{
    background:rgba(255,255,255,.05);border:1px solid rgba(255,255,255,.08);
    border-radius:13px;padding:10px 8px 11px;text-align:center;
    cursor:pointer;transition:all .2s;position:relative;overflow:hidden;
    animation:personIn .35s ease both;
}
@keyframes personIn{from{opacity:0;transform:translateY(8px) scale(.96)}to{opacity:1;transform:none}}
.person:hover{background:rgba(109,40,217,.13);border-color:rgba(109,40,217,.35);transform:translateY(-2px)}

.person-av-wrap{
    width:54px;height:54px;border-radius:50%;margin:0 auto 7px;
    position:relative;
    background:conic-gradient(from 0deg,#6d28d9,#10b981,#a855f7,#6d28d9);
    padding:2px;
}
.person-av{
    width:100%;height:100%;border-radius:50%;overflow:hidden;
    background:#0a0814;
}
.person-av img{width:100%;height:100%;object-fit:cover;display:block}
.person-online{
    position:absolute;bottom:1px;right:1px;
    width:13px;height:13px;border-radius:50%;
    background:#4ade80;border:2px solid #0a0814;
}
.person-name{
    font-size:11.5px;font-weight:700;color:#fff;
    white-space:nowrap;overflow:hidden;text-overflow:ellipsis;
    margin-bottom:3px;
}
.person-country{
    font-size:9.5px;color:rgba(255,255,255,.5);
    display:flex;align-items:center;justify-content:center;gap:4px;
    white-space:nowrap;overflow:hidden;
}
.person-country img{height:8px;border-radius:1px;flex-shrink:0}
.person-country span{overflow:hidden;text-overflow:ellipsis;min-width:0}
.person-reward{
    display:inline-flex;align-items:center;gap:4px;
    margin-top:8px;padding:4px 10px;border-radius:8px;
    font-size:10px;font-weight:800;color:#fcd34d;
    background:rgba(245,158,11,.12);
    border:1px solid rgba(245,158,11,.28);
    letter-spacing:.2px;font-variant-numeric:tabular-nums;
    box-shadow:inset 0 0 0 1px rgba(252,211,77,.05);
}
.person-reward i{font-size:8px;color:#fbbf24}
.person:hover .person-reward{
    background:rgba(245,158,11,.18);
    border-color:rgba(245,158,11,.4);
}

/* ══════════════════════════════
   TASK CARDS (when has access)
══════════════════════════════ */
.cf-section-hdr{
    display:flex;align-items:center;gap:10px;margin-bottom:12px;
}
.cf-section-lbl{font-size:9.5px;font-weight:800;letter-spacing:2px;text-transform:uppercase;color:rgba(167,139,250,.6)}
.cf-section-line{flex:1;height:1px;background:rgba(255,255,255,.07)}

.cf-access-badge{
    display:inline-flex;align-items:center;gap:6px;
    padding:5px 12px;border-radius:20px;font-size:11px;font-weight:700;
    margin-bottom:14px;
}
.cf-access-badge.admin{background:rgba(16,185,129,.12);border:1px solid rgba(16,185,129,.3);color:#4ade80}
.cf-access-badge.paid{background:rgba(109,40,217,.12);border:1px solid rgba(109,40,217,.3);color:#a78bfa}

.cf-grid{display:flex;flex-direction:column;gap:10px;margin-bottom:18px}

.cf-task{
    display:flex;align-items:center;gap:12px;
    padding:14px 15px;border-radius:16px;
    background:rgba(255,255,255,.05);
    border:1px solid rgba(255,255,255,.08);
    cursor:pointer;transition:all .2s;position:relative;overflow:hidden;
}
.cf-task::before{
    content:'';position:absolute;left:0;top:0;bottom:0;width:3px;
    background:linear-gradient(180deg,#6d28d9,#a78bfa);
    opacity:0;transition:opacity .2s;
}
.cf-task:hover{background:rgba(109,40,217,.1);border-color:rgba(109,40,217,.28);transform:translateX(3px)}
.cf-task:hover::before{opacity:1}
.cf-task.done{opacity:.4;cursor:not-allowed}
.cf-task.done:hover{transform:none;background:rgba(255,255,255,.05);border-color:rgba(255,255,255,.08)}
.cf-task.done::before{opacity:0}

.cf-task-num{
    width:42px;height:42px;border-radius:12px;flex-shrink:0;
    background:linear-gradient(135deg,#3730a3,#6d28d9);
    display:flex;align-items:center;justify-content:center;
    font-family:'Inter',sans-serif;font-size:16px;font-weight:900;color:#fff;
    box-shadow:0 4px 16px rgba(109,40,217,.4);position:relative;
}
.cf-task.done .cf-task-num{background:linear-gradient(135deg,#065f46,#10b981)}
.done-overlay{position:absolute;inset:0;border-radius:12px;background:rgba(16,185,129,.9);display:flex;align-items:center;justify-content:center;font-size:16px}

.cf-task-info{flex:1;min-width:0}
.cf-task-title{font-size:13.5px;font-weight:700;color:#fff;margin-bottom:4px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.cf-task-meta{display:flex;align-items:center;gap:6px;flex-wrap:wrap}
.cf-task-tag{display:inline-flex;align-items:center;gap:3px;padding:2px 7px;border-radius:5px;font-size:9px;font-weight:800;text-transform:uppercase;background:rgba(109,40,217,.18);color:#a78bfa}
.cf-task-dur{font-size:10px;color:rgba(255,255,255,.32);display:flex;align-items:center;gap:3px}

.cf-task-right{text-align:right;flex-shrink:0;min-width:0}
.cf-task-reward{font-family:'Inter',sans-serif;font-size:16px;font-weight:900;color:#fcd34d;line-height:1}
.cf-task-rlbl{font-size:9px;color:rgba(255,255,255,.3);text-transform:uppercase;letter-spacing:.5px;margin-top:2px}
.cf-task-cta{
    display:inline-flex;align-items:center;gap:4px;margin-top:6px;
    padding:4px 10px;border-radius:7px;font-size:10px;font-weight:800;color:#fff;
    background:linear-gradient(135deg,#4f46e5,#7c3aed);
}
.cf-task.done .cf-task-cta{background:rgba(16,185,129,.18);color:#4ade80}

.cf-pulse{width:8px;height:8px;border-radius:50%;background:#4ade80;flex-shrink:0;box-shadow:0 0 0 0 rgba(74,222,128,.6);animation:cfPulse 2s infinite}
@keyframes cfPulse{0%,100%{box-shadow:0 0 0 0 rgba(74,222,128,.6)}50%{box-shadow:0 0 0 6px rgba(74,222,128,0)}}
.cf-task.done .cf-pulse{background:#6b7280;animation:none;box-shadow:none}

.cf-empty{text-align:center;padding:44px 20px;background:rgba(255,255,255,.03);border:1px solid rgba(255,255,255,.07);border-radius:18px}
.cf-empty-ico{font-size:40px;margin-bottom:12px;display:block;opacity:.35}
.cf-empty-t{font-size:15px;font-weight:700;color:rgba(255,255,255,.5);margin-bottom:5px;font-family:'Inter',sans-serif}
.cf-empty-s{font-size:12px;color:rgba(255,255,255,.3);line-height:1.6}

/* ══════════════════════════════
   LAUNCH CARD (access granted)
══════════════════════════════ */
.cf-launch-card{
    border-radius:20px;
    background:linear-gradient(145deg,#0f0025,#141228,#001a10);
    border:1px solid rgba(109,40,217,.3);
    padding:28px 20px;text-align:center;
    position:relative;overflow:hidden;
    animation:fadeUp .4s ease both;
}
.cf-launch-card::before{
    content:'';position:absolute;top:0;left:0;right:0;height:2px;
    background:linear-gradient(90deg,transparent,#6d28d9,#10b981,#6d28d9,transparent);
}
.cf-launch-badge{
    display:inline-flex;align-items:center;gap:6px;
    padding:4px 12px;border-radius:20px;font-size:11px;font-weight:700;
    margin-bottom:20px;
}
.cf-launch-badge.admin{background:rgba(16,185,129,.12);border:1px solid rgba(16,185,129,.3);color:#4ade80}
.cf-launch-badge.paid {background:rgba(109,40,217,.12);border:1px solid rgba(109,40,217,.3);color:#a78bfa}
.cf-launch-ico{
    width:80px;height:80px;border-radius:50%;margin:0 auto 16px;
    background:conic-gradient(from 0deg,#6d28d9,#10b981,#6d28d9);
    padding:3px;display:flex;align-items:center;justify-content:center;
    box-shadow:0 0 40px rgba(109,40,217,.35);
    animation:lockPulse 2.5s ease-in-out infinite;
}
.cf-launch-ico-inner{
    width:100%;height:100%;border-radius:50%;
    background:radial-gradient(circle at 35% 35%,#1a0f40,#0a0814);
    display:flex;align-items:center;justify-content:center;font-size:32px;
}
.cf-launch-title{font-size:20px;font-weight:800;color:#fff;margin-bottom:8px}
.cf-launch-sub{font-size:12.5px;color:rgba(255,255,255,.4);line-height:1.65;margin-bottom:24px}
.cf-launch-btn{
    display:flex;align-items:center;justify-content:center;gap:10px;
    width:100%;height:54px;border-radius:14px;border:none;cursor:pointer;
    background:linear-gradient(135deg,#6d28d9,#a855f7);
    color:#fff;font-size:15px;font-weight:800;font-family:'Inter',sans-serif;
    box-shadow:0 8px 28px rgba(109,40,217,.5);
    transition:all .2s;text-decoration:none;
    margin-bottom:12px;
}
.cf-launch-btn:hover{transform:translateY(-2px);box-shadow:0 14px 38px rgba(109,40,217,.65)}
.cf-launch-note{font-size:11px;color:rgba(255,255,255,.25);margin-top:4px}

/* ══════════════════════════════
   UNLOCK MODAL (triggered after 5 chat msgs)
══════════════════════════════ */
.unlock-overlay{
    display:none;position:fixed;inset:0;z-index:3100;
    background:rgba(0,0,0,.82);backdrop-filter:blur(14px);-webkit-backdrop-filter:blur(14px);
    align-items:flex-end;justify-content:center;padding:0;
}
@media(min-width:520px){.unlock-overlay{align-items:center;padding:20px}}
.unlock-overlay.on{display:flex;animation:unlockFadeIn .25s ease both}
@keyframes unlockFadeIn{from{opacity:0}to{opacity:1}}

.unlock-modal{
    background:linear-gradient(160deg,#0f0025 0%,#141228 50%,#001a10 100%);
    border:1px solid rgba(109,40,217,.35);
    border-radius:24px 24px 0 0;width:100%;max-width:500px;
    padding:18px 16px 22px;text-align:center;
    box-shadow:0 -20px 60px rgba(109,40,217,.25),0 -40px 80px rgba(0,0,0,.55);
    position:relative;overflow:hidden;
    max-height:92vh;overflow-y:auto;
    animation:unlockSlideUp .4s cubic-bezier(.22,1,.36,1) both;
}
@media(min-width:520px){
    .unlock-modal{border-radius:24px;animation-name:unlockScaleIn;padding:26px 22px 28px}
}
@supports(padding:max(0px)){
    .unlock-modal{padding-bottom:max(22px,env(safe-area-inset-bottom))}
}
@keyframes unlockSlideUp{from{transform:translateY(100%)}to{transform:none}}
@keyframes unlockScaleIn{from{opacity:0;transform:scale(.92) translateY(20px)}to{opacity:1;transform:none}}
.unlock-modal::before{
    content:'';position:absolute;top:0;left:0;right:0;height:2px;
    background:linear-gradient(90deg,transparent,#6d28d9,#f59e0b,#6d28d9,transparent);
}
.unlock-modal-close{
    position:absolute;top:14px;right:14px;width:30px;height:30px;border-radius:8px;
    background:rgba(255,255,255,.07);border:1px solid rgba(255,255,255,.1);
    color:rgba(255,255,255,.5);font-size:14px;cursor:pointer;
    display:flex;align-items:center;justify-content:center;transition:.15s;z-index:2;
}
.unlock-modal-close:hover{background:rgba(239,68,68,.15);color:#f87171}

/* ══════════════════════════════
   CHAT MODAL
══════════════════════════════ */
.cf-overlay{
    display:none;position:fixed;inset:0;z-index:3000;
    background:rgba(0,0,0,.8);backdrop-filter:blur(12px);
    align-items:flex-end;justify-content:center;padding:0;
}
@media(min-width:520px){.cf-overlay{align-items:center;padding:20px}}
.cf-overlay.on{display:flex}

.cf-modal{
    background:linear-gradient(160deg,#0f0025 0%,#141228 50%,#001a10 100%);
    border:1px solid rgba(109,40,217,.3);
    border-radius:24px 24px 0 0;width:100%;max-width:500px;
    padding:16px 14px 20px;
    box-shadow:0 -20px 60px rgba(109,40,217,.2),0 -40px 80px rgba(0,0,0,.5);
    position:relative;overflow:hidden;
    max-height:90vh;overflow-y:auto;
    animation:modalSlideUp .35s cubic-bezier(.22,1,.36,1) both;
}
@media(min-width:520px){
    .cf-modal{border-radius:24px;animation-name:modalScaleIn;padding:22px 20px 26px}
}
@supports(padding:max(0px)){
    .cf-modal{padding-bottom:max(20px,env(safe-area-inset-bottom))}
}
@keyframes modalSlideUp{from{transform:translateY(100%)}to{transform:none}}
@keyframes modalScaleIn{from{opacity:0;transform:scale(.92) translateY(20px)}to{opacity:1;transform:none}}
.cf-modal::before{content:'';position:absolute;top:0;left:0;right:0;height:2px;background:linear-gradient(90deg,transparent,#6d28d9,#fcd34d,#6d28d9,transparent)}

/* Drag handle for mobile */
.modal-handle{width:40px;height:4px;border-radius:2px;background:rgba(255,255,255,.15);margin:0 auto 16px}

.cf-modal-close{position:absolute;top:16px;right:16px;width:30px;height:30px;border-radius:8px;background:rgba(255,255,255,.07);border:1px solid rgba(255,255,255,.1);color:rgba(255,255,255,.5);font-size:14px;cursor:pointer;display:flex;align-items:center;justify-content:center;transition:.15s}
.cf-modal-close:hover{background:rgba(239,68,68,.15);color:#f87171}

/* Loading */
.cf-loading{text-align:center;padding:20px 0}
.cf-spin{width:52px;height:52px;border-radius:50%;border:3px solid rgba(109,40,217,.2);border-top-color:#8b5cf6;animation:spin .8s linear infinite;margin:0 auto 14px}
@keyframes spin{to{transform:rotate(360deg)}}
.cf-loading-txt{font-size:13px;color:rgba(255,255,255,.5)}

/* Unavailable */
.cf-unavail{text-align:center;padding:10px 0}
.cf-unavail-ico{font-size:48px;margin-bottom:14px;display:block}
.cf-unavail-title{font-family:'Inter',sans-serif;font-size:18px;font-weight:800;color:#fff;margin-bottom:8px}
.cf-unavail-txt{font-size:12.5px;color:rgba(255,255,255,.45);line-height:1.65;margin-bottom:16px}
.cf-tip{display:flex;align-items:flex-start;gap:8px;padding:10px 12px;border-radius:10px;background:rgba(245,158,11,.08);border:1px solid rgba(245,158,11,.18);font-size:11px;color:rgba(255,255,255,.5);line-height:1.55;margin-bottom:16px;text-align:left}
.cf-tip i{color:#fbbf24;flex-shrink:0;margin-top:1px}

/* Chat */
.cf-chat-hdr{display:flex;align-items:center;gap:10px;padding-bottom:14px;border-bottom:1px solid rgba(255,255,255,.08);margin-bottom:12px}
.cf-chat-av{width:46px;height:46px;border-radius:50%;flex-shrink:0;overflow:hidden;border:2px solid rgba(109,40,217,.4);box-shadow:0 0 14px rgba(109,40,217,.35)}
.cf-chat-av img{width:100%;height:100%;object-fit:cover}
.cf-chat-name{font-weight:700;color:#fff;font-size:14px}
.cf-chat-online{font-size:10px;color:#4ade80;display:flex;align-items:center;gap:4px;margin-top:2px}
.cf-chat-online::before{content:'';width:5px;height:5px;border-radius:50%;background:#4ade80;display:inline-block}

.cf-timer-bar{height:4px;border-radius:2px;background:rgba(255,255,255,.07);overflow:hidden;margin-bottom:6px}
.cf-timer-fill{height:100%;background:linear-gradient(90deg,#4f46e5,#a78bfa);border-radius:2px;width:100%;transition:width 1s linear}
.cf-timer-txt{font-size:10px;color:rgba(255,255,255,.35);text-align:right;margin-bottom:10px}

.cf-msgs{height:200px;overflow-y:auto;display:flex;flex-direction:column;gap:7px;padding:4px 0;margin-bottom:12px;scrollbar-width:thin;scrollbar-color:rgba(255,255,255,.1) transparent}
@media(max-height:700px){.cf-msgs{height:160px}}

.cf-msg-row{display:flex;align-items:flex-end;gap:6px}
.cf-msg-row.them{flex-direction:row}
.cf-msg-row.me{flex-direction:row-reverse}
.cf-bav{width:26px;height:26px;border-radius:50%;flex-shrink:0;overflow:hidden;border:1.5px solid rgba(109,40,217,.3)}
.cf-bav img{width:100%;height:100%;object-fit:cover}
.cf-bav.me{background:linear-gradient(135deg,#059669,#10b981);display:flex;align-items:center;justify-content:center;font-size:11px;font-weight:800;color:#fff}
.cf-msg{max-width:78%;padding:9px 12px;border-radius:14px;font-size:12.5px;line-height:1.5}
.cf-msg.them{background:rgba(255,255,255,.08);color:rgba(255,255,255,.9);border-radius:4px 14px 14px 14px}
.cf-msg.me{background:linear-gradient(135deg,#4f46e5,#7c3aed);color:#fff;border-radius:14px 4px 14px 14px}

.cf-typing-row{display:flex;align-items:flex-end;gap:6px}
.cf-typing{display:flex;gap:4px;padding:9px 12px;background:rgba(255,255,255,.08);border-radius:4px 14px 14px 14px;width:fit-content}
.cf-typing span{width:6px;height:6px;border-radius:50%;background:rgba(255,255,255,.45);animation:typDot 1.2s ease-in-out infinite}
.cf-typing span:nth-child(2){animation-delay:.2s}
.cf-typing span:nth-child(3){animation-delay:.4s}
@keyframes typDot{0%,60%,100%{transform:none}30%{transform:translateY(-5px)}}

.cf-input-row{display:flex;gap:7px}
.cf-input{flex:1;height:42px;padding:0 13px;background:rgba(255,255,255,.07);border:1.5px solid rgba(255,255,255,.12);border-radius:11px;color:#fff;font-size:13px;outline:none;transition:.15s;font-family:'Inter',sans-serif}
.cf-input:focus{border-color:#8b5cf6;background:rgba(255,255,255,.1)}
.cf-input::placeholder{color:rgba(255,255,255,.25)}
.cf-send{width:42px;height:42px;border-radius:11px;border:none;cursor:pointer;flex-shrink:0;background:linear-gradient(135deg,#4f46e5,#7c3aed);color:#fff;font-size:15px;display:flex;align-items:center;justify-content:center;transition:.15s}
.cf-send:hover{filter:brightness(1.15)}

.cf-modal-btn{
    width:100%;height:46px;border-radius:12px;border:none;cursor:pointer;
    font-size:14px;font-weight:800;color:#fff;font-family:'Inter',sans-serif;
    display:flex;align-items:center;justify-content:center;gap:7px;transition:all .2s;
}
.cf-modal-btn.primary{background:linear-gradient(135deg,#4f46e5,#7c3aed);box-shadow:0 6px 20px rgba(109,40,217,.4);margin-top:12px}
.cf-modal-btn.primary:hover{transform:translateY(-2px)}
.cf-modal-btn.primary:disabled{opacity:.4;cursor:not-allowed;transform:none;box-shadow:none}
.cf-modal-btn.earn{background:linear-gradient(135deg,#059669,#10b981);box-shadow:0 6px 20px rgba(16,185,129,.4);margin-top:12px}
.cf-modal-btn.earn:hover{transform:translateY(-2px)}
.cf-modal-btn.secondary{background:rgba(255,255,255,.06);border:1px solid rgba(255,255,255,.1);color:rgba(255,255,255,.6);margin-top:8px}
.cf-modal-btn.secondary:hover{background:rgba(255,255,255,.1);color:#fff}
</style>
</head>
<body>

<div class="page">

<?php if ($flash): ?>
<div class="flash <?= $flash['type'] ?>">
    <i class="fa-solid fa-<?= $flash['type']==='success'?'check-circle':'exclamation-circle' ?>"></i>
    <?= htmlspecialchars($flash['message']) ?>
</div>
<?php endif; ?>

<!-- ── PAGE HEADER + STATS ── -->
<div class="cf-page-hdr">
    <div class="cf-page-title"><span>💬</span> Chat Foreigners</div>
</div>
<div class="cf-stats-strip">
    <div class="cf-stat">
        <div class="cf-stat-val"><?= count($chatTasks) ?: '–' ?></div>
        <div class="cf-stat-lbl">Tasks</div>
    </div>
    <div class="cf-stat">
        <div class="cf-stat-val"><?= intval($stats['done'] ?? 0) ?></div>
        <div class="cf-stat-lbl">Done</div>
    </div>
    <div class="cf-stat">
        <div class="cf-stat-val" style="font-size:13px"><?= $cs ?>&nbsp;<?= number_format($stats['earned'] ?? 0) ?></div>
        <div class="cf-stat-lbl">Earned</div>
    </div>
</div>

<?php if (!$hasAccess): ?>

<!-- ═══ ★ LIVE FOREIGNERS LIST ═══ -->
<div class="live-card" id="liveCard">
    <div class="live-hdr">
        <div class="live-hdr-left">
            <div class="live-title"><span class="live-dot"></span> Foreigners online now</div>
            <div class="live-sub">Tap anyone to start chatting & earning</div>
        </div>
    </div>

    <div class="people-grid" id="peopleGrid">
        <!-- People populated by JS so we can render real photos + flags consistently -->
    </div>
</div>

<?php else: ?>
<!-- ═══ HAS ACCESS ═══ -->

<?php if (!empty($redirectLink)): ?>
<!-- ── ACCESS GRANTED: launch card with direct link ── -->
<div class="cf-launch-card">
    <span class="cf-launch-badge <?= $accessSource === 'admin' ? 'admin' : 'paid' ?>">
        <i class="fa-solid fa-<?= $accessSource === 'admin' ? 'shield-halved' : 'check-circle' ?>"></i>
        <?= $accessSource === 'admin' ? 'Admin-Granted Access' : 'Premium Access Active' ?>
    </span>
    <div class="cf-launch-ico">
        <div class="cf-launch-ico-inner">💬</div>
    </div>
    <div class="cf-launch-title">You're In! Start Chatting</div>
    <div class="cf-launch-sub">
        Your access is active. Tap the button below to open the chat platform.<br>
        It will open in a new tab so you can earn while staying on Earnovix.
    </div>
    <a href="<?= htmlspecialchars($redirectLink) ?>" target="_blank" rel="noopener" class="cf-launch-btn" id="cfLaunchBtn" onclick="cfLaunchClick(this)">
        <i class="fa-solid fa-arrow-up-right-from-square"></i>
        Open Chat Platform
    </a>
    <div class="cf-launch-note">
        <i class="fa-solid fa-lock" style="font-size:9px;margin-right:3px"></i>
        Opens securely in a new tab · Your session is protected
    </div>
    <?php if ($accessSource === 'paid' && $accessExpiry): ?>
    <div style="margin-top:12px;font-size:11px;color:rgba(255,255,255,.3)">
        <?php
            $daysLeft = ceil(($accessExpiry - time()) / 86400);
            $expDate  = date('M j, Y', $accessExpiry);
        ?>
        <i class="fa-solid fa-clock" style="font-size:9px;margin-right:3px;color:rgba(109,40,217,.6)"></i>
        Access expires in <strong style="color:rgba(167,139,250,.7)"><?= $daysLeft ?> day<?= $daysLeft != 1 ? 's' : '' ?></strong> &nbsp;·&nbsp; <?= $expDate ?>
    </div>
    <?php endif; ?>
</div>

<?php else: ?>
<!-- ── No link set — show task list fallback ── -->
<?php if ($accessSource === 'admin'): ?>
<div class="cf-access-badge admin">
    <i class="fa-solid fa-shield-halved"></i> Admin-granted access
</div>
<?php else: ?>
<div class="cf-access-badge paid">
    <i class="fa-solid fa-check-circle"></i> Premium access active
</div>
<?php endif; ?>

<div class="cf-section-hdr">
    <span class="cf-section-lbl"><i class="fa-solid fa-satellite-dish" style="font-size:8px"></i> Live Sessions</span>
    <div class="cf-section-line"></div>
</div>

<?php if (empty($chatTasks)): ?>
<div class="cf-empty">
    <span class="cf-empty-ico">💬</span>
    <div class="cf-empty-t">No Chat Tasks Yet</div>
    <div class="cf-empty-s">Admin hasn't set up chat tasks yet.<br>Check back soon!</div>
</div>
<?php else: ?>
<div class="cf-grid">
    <?php foreach ($chatTasks as $i => $task):
        $done = $task['today_done'] >= $task['daily_limit_per_user'] || ($task['total_limit'] && $task['total_done'] >= $task['total_limit']);
    ?>
    <div class="cf-task <?= $done?'done':'' ?>"
         onclick="<?= $done?'':'openChat(this)' ?>"
         data-task-id="<?= $task['id'] ?>"
         data-title="<?= htmlspecialchars($task['title']) ?>"
         data-reward="<?= $task['reward'] ?>"
         data-duration="<?= intval($task['min_duration_seconds']??120) ?>">
        <div class="cf-pulse"></div>
        <div class="cf-task-num">
            <?= str_pad($i+1,2,'0',STR_PAD_LEFT) ?>
            <?php if ($done): ?><div class="done-overlay"><i class="fa-solid fa-check"></i></div><?php endif; ?>
        </div>
        <div class="cf-task-info">
            <div class="cf-task-title"><?= htmlspecialchars($task['title']) ?></div>
            <div class="cf-task-meta">
                <span class="cf-task-tag"><i class="fa-solid fa-message" style="font-size:7px"></i> CHAT</span>
                <?php if ($task['min_duration_seconds']): ?>
                <span class="cf-task-dur"><i class="fa-solid fa-clock" style="font-size:9px"></i> <?= gmdate('i:s',$task['min_duration_seconds']) ?></span>
                <?php endif; ?>
            </div>
        </div>
        <div class="cf-task-right">
            <div class="cf-task-reward"><?= $cs ?> <?= number_format($task['reward'],2) ?></div>
            <div class="cf-task-rlbl">Per session</div>
            <div class="cf-task-cta"><?= $done?'<i class="fa-solid fa-check"></i> Done':'<i class="fa-solid fa-play"></i> Start' ?></div>
        </div>
    </div>
    <?php endforeach; ?>
</div>
<?php endif; ?>
<?php endif; // end no-link fallback ?>
<?php endif; // end has access ?>

</div><!-- /.page -->

<?php if (!$hasAccess): ?>
<!-- ════════ UNLOCK MODAL (triggered after 5 chat messages) ════════ -->
<div class="unlock-overlay" id="unlockOverlay">
<div class="unlock-modal" id="unlockModal">
    <div class="modal-handle"></div>
    <button class="unlock-modal-close" onclick="closeUnlockModal()" aria-label="Close"><i class="fa-solid fa-xmark"></i></button>

    <div class="unlock-lock"><div class="unlock-lock-inner">🔒</div></div>
    <div class="unlock-title">Unlock to Keep Earning</div>
    <div class="unlock-sub">Pay once and chat with foreigners to start earning. 30 days of full access.</div>

    <div class="unlock-features">
        <div class="unlock-feat"><i class="fa-solid fa-globe-africa"></i><span>Chat with verified foreigners worldwide</span></div>
        <div class="unlock-feat"><i class="fa-solid fa-coins"></i><span>Earn per completed chat session</span></div>
        <div class="unlock-feat"><i class="fa-solid fa-shield-halved"></i><span>Secure & safe platform</span></div>
        <div class="unlock-feat"><i class="fa-solid fa-clock-rotate-left"></i><span>30-day access after payment</span></div>
    </div>

    <div class="unlock-price">
        <div class="unlock-price-val"><?= $cs ?> <?= number_format(floatval($unlockFee)) ?></div>
        <div class="unlock-price-lbl">One-time unlock</div>
    </div>

    <?php if ($pendingPayment && $pendingPayment['status'] === 'pending'): ?>
    <div class="pending-notice">
        <i class="fa-solid fa-hourglass-half"></i>
        <div class="pending-notice-txt">
            <strong>Payment Pending</strong>
            Check your phone and complete the M-PESA payment. Tap below to refresh status.
        </div>
    </div>
    <div class="pending-notice" style="margin-bottom:0">
        <i class="fa-solid fa-circle-notch" id="cfPollIcon" style="color:#fbbf24;font-size:14px;flex-shrink:0;animation:cfPollSpin .8s linear infinite"></i>
        <div class="pending-notice-txt">
            <strong>Waiting for M-PESA…</strong>
            Complete the payment on your phone. This page detects it automatically.
        </div>
    </div>
    <div id="cfPollNotice" class="cf-poll-notice"></div>
    <button class="check-status-btn" onclick="checkPaymentStatus()" style="margin-top:6px">
        <i class="fa-solid fa-rotate-right"></i> Check Now
    </button>
    <?php else: ?>
    <form class="unlock-form" method="POST">
        <input type="hidden" name="action" value="initiate_unlock">
        <div class="phone-row">
            <div class="phone-prefix">
                <img src="https://flagcdn.com/w40/ke.png" alt="KE"> 🇰🇪 +254
            </div>
            <input type="tel" name="phone" class="phone-inp" placeholder="07XXXXXXXX" required pattern="[0-9]{10}" maxlength="10">
        </div>
        <button type="submit" class="unlock-btn">
            <i class="fa-brands fa-mpesa" style="font-size:16px"></i>
            Pay <?= $cs ?> <?= number_format(floatval($unlockFee)) ?> via M-PESA
        </button>
    </form>
    <?php endif; ?>
</div>
</div>
<?php endif; ?>

<!-- ════════ CHAT MODAL ════════ -->
<div class="cf-overlay" id="cfOverlay">
<div class="cf-modal" id="cfModal">
    <div class="modal-handle"></div>
    <button class="cf-modal-close" onclick="closeChat()"><i class="fa-solid fa-xmark"></i></button>

    <div id="cfLoading">
        <div class="cf-loading">
            <div class="cf-spin"></div>
            <div class="cf-loading-txt">Finding someone to chat with…</div>
        </div>
    </div>

    <div id="cfUnavail" style="display:none">
        <div class="cf-unavail">
            <span class="cf-unavail-ico">😔</span>
            <div class="cf-unavail-title">Everyone's Busy!</div>
            <div class="cf-unavail-txt">All foreigners are currently chatting. Please try again in a few minutes.</div>
            <div class="cf-tip"><i class="fa-solid fa-lightbulb"></i><span>Do other tasks and come back — new slots open frequently.</span></div>
            <button class="cf-modal-btn primary" onclick="retryFind()"><i class="fa-solid fa-rotate-right"></i> Try Again</button>
            <button class="cf-modal-btn secondary" onclick="closeChat()"><i class="fa-solid fa-arrow-left"></i> Back</button>
        </div>
    </div>

    <div id="cfChat" style="display:none">
        <div class="cf-chat-hdr">
            <div class="cf-chat-av"><img id="partnerImg" src="" alt=""></div>
            <div style="flex:1;min-width:0">
                <div class="cf-chat-name" id="partnerName">–</div>
                <div class="cf-chat-online" id="partnerOnline">● Online now</div>
            </div>
            <div style="text-align:right;font-size:10px;color:rgba(255,255,255,.4);flex-shrink:0" id="partnerCountry"></div>
        </div>
        <div class="cf-timer-bar"><div class="cf-timer-fill" id="timerFill"></div></div>
        <div class="cf-timer-txt" id="timerTxt">–:--</div>
        <div class="cf-msgs" id="cfMsgs"></div>
        <div class="cf-input-row">
            <input type="text" class="cf-input" id="cfInput" placeholder="Type your message…" onkeydown="if(event.key==='Enter')sendMsg()">
            <button class="cf-send" onclick="sendMsg()"><i class="fa-solid fa-paper-plane"></i></button>
        </div>
        <button class="cf-modal-btn earn" id="earnBtn" disabled onclick="submitTask()">
            <i class="fa-solid fa-lock"></i> Complete chat to earn
        </button>
    </div>
</div>
</div>

<form id="taskForm" method="POST" action="tasks.php" style="display:none">
    <input type="hidden" name="submit_task" value="1">
    <input type="hidden" name="task_id" id="formTaskId">
    <input type="hidden" name="proof_text" id="formProof">
</form>

<script>
var TASK=null,timer=null,timeLeft=0,chatOn=false,partner=null,chatHist=[];
var UI='<?= strtoupper(substr($userData['username']??'U',0,1)) ?>';
var CS='<?= $cs ?>';
var CF_REDIRECT='<?= addslashes(getSetting('chat_foreigners_redirect_link','')) ?>';
var CF_PENDING=<?= ($pendingPayment && $pendingPayment['status']==='pending') ? 'true' : 'false' ?>;
var HAS_ACCESS=<?= $hasAccess ? 'true' : 'false' ?>;

// Preview-mode state (only used when user has no access)
var PREVIEW_MODE        = false;    // true = unauthenticated chat
var PREVIEW_SECONDS     = 10;       // seconds of chat before unlock modal
var PREVIEW_REWARD      = 1000;     // amount the user would earn per person (local currency)
var previewTimer        = null;
var previewTimeLeft     = 0;
var previewLocked       = false;

var PARTNERS=[
    {n:'James Miller',c:'United States',code:'us',img:'https://randomuser.me/api/portraits/men/32.jpg'},
    {n:'Sophie Laurent',c:'France',code:'fr',img:'https://randomuser.me/api/portraits/women/44.jpg'},
    {n:'Carlos Rivera',c:'Mexico',code:'mx',img:'https://randomuser.me/api/portraits/men/55.jpg'},
    {n:'Aiko Tanaka',c:'Japan',code:'jp',img:'https://randomuser.me/api/portraits/women/22.jpg'},
    {n:'Emma Wilson',c:'United Kingdom',code:'gb',img:'https://randomuser.me/api/portraits/women/63.jpg'},
    {n:'Luca Rossi',c:'Italy',code:'it',img:'https://randomuser.me/api/portraits/men/18.jpg'},
    {n:'Anna Schmidt',c:'Germany',code:'de',img:'https://randomuser.me/api/portraits/women/37.jpg'},
    {n:'Marcus Johnson',c:'Canada',code:'ca',img:'https://randomuser.me/api/portraits/men/71.jpg'},
    {n:'Priya Sharma',c:'India',code:'in',img:'https://randomuser.me/api/portraits/women/28.jpg'},
    {n:'Omar Khalil',c:'Egypt',code:'eg',img:'https://randomuser.me/api/portraits/men/43.jpg'},
    {n:'Maria Santos',c:'Brazil',code:'br',img:'https://randomuser.me/api/portraits/women/51.jpg'},
    {n:'Jake Thompson',c:'Australia',code:'au',img:'https://randomuser.me/api/portraits/men/64.jpg'},
];

function openChat(el){
    TASK={id:el.dataset.taskId,title:el.dataset.title,reward:el.dataset.reward,duration:parseInt(el.dataset.duration)||120};
    chatHist=[];
    document.getElementById('cfOverlay').classList.add('on');
    document.body.style.overflow='hidden';
    show('loading');
    setTimeout(function(){
        Math.random()<.78?startChat():show('unavail');
    },1200+Math.random()*800);
}

/* Unauthenticated entry point — uses the chosen person, 10s timer triggers unlock modal */
function openChatPreview(person){
    PREVIEW_MODE = true;
    previewLocked = false;
    previewTimeLeft = PREVIEW_SECONDS;
    partner = person;
    chatHist = [];
    document.getElementById('cfOverlay').classList.add('on');
    document.body.style.overflow = 'hidden';

    // Repurpose the bottom earn button as a "you would earn" reward pitch
    var earnBtn = document.getElementById('earnBtn');
    if(earnBtn){
        earnBtn.disabled = true; // not clickable in preview
        earnBtn.style.opacity = '1';
        earnBtn.style.cursor = 'default';
        earnBtn.innerHTML = '<i class="fa-solid fa-coins"></i> Chat to earn ' + CS + ' ' + PREVIEW_REWARD.toLocaleString();
    }

    show('loading');
    // Always succeed for preview (no "Everyone's busy" — user tapped a specific person)
    setTimeout(function(){ startChatPreview(); }, 900 + Math.random()*500);
}

function startChatPreview(){
    document.getElementById('partnerImg').src = partner.img;
    document.getElementById('partnerName').textContent = partner.n;
    document.getElementById('partnerCountry').innerHTML =
        '<img src="https://flagcdn.com/w40/'+partner.code+'.png" style="height:14px;border-radius:2px;vertical-align:middle;margin-right:3px">'+partner.c;
    document.getElementById('cfMsgs').innerHTML = '';
    show('chat');

    // Start the 10s countdown right away using the existing timer bar
    startPreviewTimer();

    // Partner greets first
    setTimeout(function(){
        typing(true);
        callAI([{role:'user',content:'Say hi briefly and ask one friendly question. Max 2 sentences.'}], function(r){
            typing(false);
            addMsg(r, 'them');
            chatHist.push({role:'assistant', content: r});
            chatOn = true; // enable user replies
        });
    }, 800);
}

function startPreviewTimer(){
    var fill = document.getElementById('timerFill');
    var txt  = document.getElementById('timerTxt');
    if(fill){ fill.style.width = '100%'; fill.style.background = 'linear-gradient(90deg,#4f46e5,#a78bfa)'; }
    if(txt){ txt.textContent = previewTimeLeft + 's left'; txt.style.color = ''; }

    if(previewTimer) clearInterval(previewTimer);
    previewTimer = setInterval(function(){
        previewTimeLeft--;
        var pct = Math.max(0, previewTimeLeft / PREVIEW_SECONDS * 100);
        if(fill) fill.style.width = pct + '%';
        if(txt){
            txt.textContent = Math.max(0, previewTimeLeft) + 's left';
            if(previewTimeLeft <= 3) txt.style.color = '#f87171';
        }
        if(previewTimeLeft <= 0){
            clearInterval(previewTimer);
            previewTimer = null;
            lockPreview();
        }
    }, 1000);
}

function lockPreview(){
    if(previewLocked) return;
    previewLocked = true;
    chatOn = false;
    typing(false);
    // Disable input + send button
    var inp = document.getElementById('cfInput');
    if(inp){ inp.disabled = true; inp.placeholder = 'Unlock to keep chatting…'; }
    var send = inp && inp.nextElementSibling;
    if(send && send.classList && send.classList.contains('cf-send')){ send.disabled = true; send.style.opacity = '.4'; }
    // Timer text → red, fill → red
    var fill = document.getElementById('timerFill');
    var txt  = document.getElementById('timerTxt');
    if(fill){ fill.style.width = '100%'; fill.style.background = 'linear-gradient(90deg,#dc2626,#f87171)'; }
    if(txt){ txt.textContent = 'Time up — unlock to continue'; txt.style.color = '#f87171'; }
    // Show unlock modal after a short beat
    setTimeout(showUnlockModal, 500);
}

function startChat(){
    partner=PARTNERS[Math.floor(Math.random()*PARTNERS.length)];
    document.getElementById('partnerImg').src=partner.img;
    document.getElementById('partnerName').textContent=partner.n;
    document.getElementById('partnerCountry').innerHTML=
        '<img src="https://flagcdn.com/w40/'+partner.code+'.png" style="height:14px;border-radius:2px;vertical-align:middle;margin-right:3px">'+partner.c;
    document.getElementById('cfMsgs').innerHTML='';
    show('chat');
    setTimeout(function(){typing(true);aiMsg();},1000);
}

function retryFind(){
    show('loading');
    setTimeout(function(){Math.random()<.78?startChat():show('unavail');},1200+Math.random()*600);
}

function show(s){
    document.getElementById('cfLoading').style.display=s==='loading'?'block':'none';
    document.getElementById('cfUnavail').style.display=s==='unavail'?'block':'none';
    document.getElementById('cfChat').style.display=s==='chat'?'block':'none';
}

var typRow=null;
function typing(on){
    var box=document.getElementById('cfMsgs');
    if(on&&!typRow){
        typRow=document.createElement('div');typRow.className='cf-typing-row';
        var av=document.createElement('div');av.className='cf-bav';
        var im=document.createElement('img');im.src=partner.img;av.appendChild(im);
        var dots=document.createElement('div');dots.className='cf-typing';
        dots.innerHTML='<span></span><span></span><span></span>';
        typRow.appendChild(av);typRow.appendChild(dots);
        box.appendChild(typRow);box.scrollTop=box.scrollHeight;
    } else if(!on&&typRow){typRow.remove();typRow=null;}
}

function addMsg(txt,who){
    typing(false);
    var box=document.getElementById('cfMsgs');
    var row=document.createElement('div');row.className='cf-msg-row '+who;
    var av=document.createElement('div');av.className='cf-bav '+(who==='them'?'':'me');
    if(who==='them'){var im=document.createElement('img');im.src=partner.img;av.appendChild(im);}
    else av.textContent=UI;
    var bub=document.createElement('div');bub.className='cf-msg '+who;bub.textContent=txt;
    if(who==='them'){row.appendChild(av);row.appendChild(bub);}
    else{row.appendChild(bub);row.appendChild(av);}
    box.appendChild(row);box.scrollTop=box.scrollHeight;
}

function sysPropmt(){
    return "You are "+partner.n+" from "+partner.c+". You're a real person, lonely and looking for friendly chat online. Reply like a human — casual, warm, curious. Keep it SHORT (1-3 sentences). Never mention being AI. Ask follow-up questions. Share things about your life and culture.";
}

// Rotating fallbacks — used only when fetch fails completely (network down).
// The server-side proxy has its own local engine, so empty replies are rare.
var CHAT_FALLBACKS = [
    "Hmm, my signal's a bit weird 😅 say that again?",
    "Wait sorry, what was that?",
    "Oh haha, didn't catch that — tell me again?",
    "My internet just glitched 🙃 what'd you say?",
    "Sorry, can you repeat? My phone's being weird",
    "Lol my connection is bad rn, try again?",
];
function _fallbackReply(){
    return CHAT_FALLBACKS[Math.floor(Math.random()*CHAT_FALLBACKS.length)];
}

function callAI(msgs,cb){
    fetch('ai_chat_proxy.php',{
        method:'POST',
        headers:{'Content-Type':'application/json'},
        body:JSON.stringify({system:sysPropmt(),messages:msgs})
    })
    .then(function(r){ return r.json(); })
    .then(function(d){ cb(d.reply || _fallbackReply()); })
    .catch(function(){ cb(_fallbackReply()); });
}

function aiMsg(){
    callAI([{role:'user',content:'Say hi briefly and ask one question. Max 2 sentences.'}],function(r){
        typing(false);addMsg(r,'them');chatHist.push({role:'assistant',content:r});startTimer();
    });
}

function sendMsg(){
    var inp=document.getElementById('cfInput');var txt=inp.value.trim();if(!txt)return;
    addMsg(txt,'me');inp.value='';inp.focus();
    chatHist.push({role:'user',content:txt});

    // Preview mode: just exchange messages — the 10s timer drives the lock, not message count
    if(PREVIEW_MODE){
        if(previewLocked) return; // safety: timer hit zero
        setTimeout(function(){
            if(previewLocked) return; // user hit timer before bot replied
            typing(true);
            callAI(chatHist.slice(-8), function(r){
                if(previewLocked){ typing(false); return; }
                typing(false);
                setTimeout(function(){
                    if(previewLocked) return;
                    addMsg(r, 'them');
                    chatHist.push({role:'assistant', content: r});
                }, Math.max(300, Math.min(r.length*15, 900)));
            });
        }, 500 + Math.random()*500);
        return;
    }

    if(!chatOn)return;
    setTimeout(function(){
        typing(true);
        callAI(chatHist.slice(-8),function(r){
            typing(false);
            setTimeout(function(){addMsg(r,'them');chatHist.push({role:'assistant',content:r});},Math.max(300, Math.min(r.length*15,900)));
        });
    },600+Math.random()*600);
}

/* ── Unlock modal controls ── */
function showUnlockModal(){
    var ov = document.getElementById('unlockOverlay');
    if(!ov) return; // not on page (user already has access)
    ov.classList.add('on');
}
function closeUnlockModal(){
    var ov = document.getElementById('unlockOverlay');
    if(ov) ov.classList.remove('on');
    // Also close the (frozen) chat behind it so user returns to the grid cleanly
    if(PREVIEW_MODE) closeChat();
}

function pad(n){return n<10?'0'+n:''+n;}

function startTimer(){
    chatOn=true;timeLeft=TASK.duration;var total=timeLeft;
    var fill=document.getElementById('timerFill');
    var txt=document.getElementById('timerTxt');
    var btn=document.getElementById('earnBtn');
    fill.style.width='100%';
    if(timer)clearInterval(timer);
    timer=setInterval(function(){
        timeLeft--;
        fill.style.width=Math.max(0,timeLeft/total*100)+'%';
        txt.textContent='Time remaining: '+pad(Math.floor(timeLeft/60))+':'+pad(timeLeft%60);
        if(timeLeft<=0){
            clearInterval(timer);chatOn=false;
            txt.textContent='✅ Chat complete! Claim your reward.';
            fill.style.background='linear-gradient(90deg,#059669,#4ade80)';fill.style.width='100%';
            btn.disabled=false;
            btn.innerHTML='<i class="fa-solid fa-coins"></i> Claim '+CS+' '+parseFloat(TASK.reward).toFixed(2);
            typing(true);
            callAI(chatHist.slice(-4).concat([{role:'user',content:'Say a warm goodbye in 1 sentence.'}]),function(r){typing(false);addMsg(r,'them');});
        }
    },1000);
}

function submitTask(){
    if(chatOn)return;
    document.getElementById('formTaskId').value=TASK.id;
    document.getElementById('formProof').value='Chat completed with '+(partner?partner.n:'partner')+' at '+new Date().toISOString();
    closeChat();
    document.getElementById('taskForm').submit();
}

function closeChat(){
    if(timer)clearInterval(timer);
    if(previewTimer)clearInterval(previewTimer);
    timer=null;previewTimer=null;chatOn=false;partner=null;chatHist=[];typRow&&(typRow.remove(),typRow=null);
    document.getElementById('cfOverlay').classList.remove('on');
    document.body.style.overflow='';TASK=null;

    // Reset preview mode + restore UI for next opening (paid or preview)
    if(PREVIEW_MODE){
        PREVIEW_MODE = false;
        previewLocked = false;
        previewTimeLeft = 0;
        // Restore earn button to its original "locked / complete chat" state
        var earnBtn = document.getElementById('earnBtn');
        if(earnBtn){
            earnBtn.disabled = true;
            earnBtn.style.opacity = '';
            earnBtn.style.cursor = '';
            earnBtn.innerHTML = '<i class="fa-solid fa-lock"></i> Complete chat to earn';
        }
        // Restore timer bar appearance
        var fill = document.getElementById('timerFill');
        var txt  = document.getElementById('timerTxt');
        if(fill){ fill.style.width = '100%'; fill.style.background = 'linear-gradient(90deg,#4f46e5,#a78bfa)'; }
        if(txt){ txt.textContent = '–:--'; txt.style.color = ''; }
        // Restore the chat input
        var inp = document.getElementById('cfInput');
        if(inp){ inp.disabled = false; inp.placeholder = 'Type your message…'; }
        var send = inp && inp.nextElementSibling;
        if(send && send.classList && send.classList.contains('cf-send')){ send.disabled = false; send.style.opacity = ''; }
    }
}

var _cfPollTimer = null;

function checkPaymentStatus(){
    fetch('check_cf_payment.php')
    .then(function(r){ return r.json(); })
    .then(function(d){
        if(d.status === 'completed'){
            stopPolling();
            // Redirect to admin-configured link, or reload
            var dest = d.redirect || CF_REDIRECT || null;
            if(dest && dest.length > 5){
                window.location.href = dest;
            } else {
                location.reload();
            }
        } else if(d.status === 'failed'){
            stopPolling();
            showCfNotice('err', d.message || 'Payment failed. Please try again.');
        }
        // else pending — keep polling
    })
    .catch(function(){ /* silent — keep polling */ });
}

function stopPolling(){
    if(_cfPollTimer){ clearInterval(_cfPollTimer); _cfPollTimer = null; }
}

function showCfNotice(type, msg){
    var el = document.getElementById('cfPollNotice');
    if(!el) return;
    el.className = 'cf-poll-notice ' + type;
    el.textContent = msg;
}

// Auto-start polling if payment is pending on page load
if(CF_PENDING){
    // Poll immediately then every 6 seconds
    checkPaymentStatus();
    _cfPollTimer = setInterval(checkPaymentStatus, 6000);
}

document.getElementById('cfOverlay').addEventListener('click',function(e){if(e.target===this)closeChat();});
document.addEventListener('keydown',function(e){
    if(e.key==='Escape'){
        var uov = document.getElementById('unlockOverlay');
        if(uov && uov.classList.contains('on')){
            closeUnlockModal(); // also closes chat
        } else {
            closeChat();
        }
    }
});

// Unlock modal: click-outside-to-dismiss
var _uov = document.getElementById('unlockOverlay');
if(_uov){
    _uov.addEventListener('click', function(e){
        if(e.target === this) closeUnlockModal();
    });
}

function cfLaunchClick(btn){
    btn.innerHTML='<i class="fa-solid fa-circle-notch fa-spin"></i> Opening…';
    setTimeout(function(){
        btn.innerHTML='<i class="fa-solid fa-arrow-up-right-from-square"></i> Open Chat Platform';
    }, 2500);
}

/* ═══════════════════════════════════════════════════════════════════
   ★ LIVE FOREIGNERS GRID
   Renders a grid of foreigners. Tapping anyone opens the chat modal
   in preview mode (PREVIEW_MODE=true). After 5 user messages, the
   unlock modal appears. Only initialises if the user has no access.
═══════════════════════════════════════════════════════════════════ */
(function(){
    var liveCard = document.getElementById('liveCard');
    if(!liveCard) return; // user already has access → not rendered

    // Extra people pool — more variety than the modal-only PARTNERS array.
    // Uses the same randomuser.me + flagcdn.com sources for consistency.
    var EXTRA_PEOPLE = [
        {n:'Hannah Becker',  c:'Germany',       code:'de', img:'https://randomuser.me/api/portraits/women/68.jpg'},
        {n:'Diego Hernandez',c:'Spain',         code:'es', img:'https://randomuser.me/api/portraits/men/85.jpg'},
        {n:'Yuki Sato',      c:'Japan',         code:'jp', img:'https://randomuser.me/api/portraits/women/15.jpg'},
        {n:'Liam O\u2019Brien', c:'Ireland',    code:'ie', img:'https://randomuser.me/api/portraits/men/29.jpg'},
        {n:'Chloe Martin',   c:'France',        code:'fr', img:'https://randomuser.me/api/portraits/women/82.jpg'},
        {n:'Ahmed Hassan',   c:'UAE',           code:'ae', img:'https://randomuser.me/api/portraits/men/12.jpg'},
        {n:'Isabella Ferrari',c:'Italy',        code:'it', img:'https://randomuser.me/api/portraits/women/76.jpg'},
        {n:'Daniel Park',    c:'South Korea',   code:'kr', img:'https://randomuser.me/api/portraits/men/40.jpg'},
        {n:'Olivia Brown',   c:'New Zealand',   code:'nz', img:'https://randomuser.me/api/portraits/women/9.jpg'},
        {n:'Mateus Silva',   c:'Portugal',      code:'pt', img:'https://randomuser.me/api/portraits/men/66.jpg'},
        {n:'Zara Ahmed',     c:'Pakistan',      code:'pk', img:'https://randomuser.me/api/portraits/women/57.jpg'},
        {n:'Lukas Novak',    c:'Czechia',       code:'cz', img:'https://randomuser.me/api/portraits/men/24.jpg'}
    ];

    // Combine main PARTNERS + extras, then shuffle for variety on each load
    function shuffle(a){
        var r = a.slice();
        for(var i = r.length - 1; i > 0; i--){
            var j = Math.floor(Math.random() * (i + 1));
            var t = r[i]; r[i] = r[j]; r[j] = t;
        }
        return r;
    }
    var ALL_PEOPLE = shuffle(PARTNERS.concat(EXTRA_PEOPLE));
    var SHOW_COUNT = Math.min(12, ALL_PEOPLE.length); // show 12 on the grid
    // On larger screens we render a few more for the 3rd/4th column to look full
    if(window.innerWidth >= 560) SHOW_COUNT = Math.min(16, ALL_PEOPLE.length);

    function escapeHtml(s){
        return String(s).replace(/[&<>"']/g, function(c){
            return {'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c];
        });
    }

    function renderPeople(){
        var grid = document.getElementById('peopleGrid');
        grid.innerHTML = '';
        var rewardStr = CS + ' ' + PREVIEW_REWARD.toLocaleString();
        for(var i = 0; i < SHOW_COUNT; i++){
            var p = ALL_PEOPLE[i];
            var card = document.createElement('div');
            card.className = 'person';
            card.style.animationDelay = (i * 0.04) + 's';
            card.innerHTML =
                '<div class="person-av-wrap">' +
                    '<div class="person-av"><img src="' + p.img + '" alt=""></div>' +
                    '<div class="person-online"></div>' +
                '</div>' +
                '<div class="person-name">' + escapeHtml(p.n) + '</div>' +
                '<div class="person-country">' +
                    '<img src="https://flagcdn.com/w20/' + p.code + '.png" alt="">' +
                    '<span>' + escapeHtml(p.c) + '</span>' +
                '</div>' +
                '<div class="person-reward"><i class="fa-solid fa-coins"></i> Earn ' + rewardStr + '</div>';
            // Capture the person object for this card (closure)
            (function(person){
                card.onclick = function(){ openChatPreview(person); };
            })(p);
            grid.appendChild(card);
        }
    }

    renderPeople();
})();

</script>
</body>
</html>
<?php include 'footer.php'; ?>