<?php
// Free AI Chat Assistant - Rule-based, user-aware responses
header('Content-Type: application/json');

require_once '../config/config.php';
require_once '../classes/Database.php';
require_once '../classes/Auth.php';

$db   = Database::getInstance();
$auth = new Auth($db);

if (!$auth->isLoggedIn()) {
    echo json_encode([
        'response' => "🔒 Please login to use the assistant."
    ]);
    exit();
}

$currentUser = $auth->getCurrentUser();
$userId      = $currentUser['id'] ?? 0;

$userMessageRaw   = trim($_POST['message'] ?? '');
$userMessageLower = strtolower($userMessageRaw);

if ($userMessageRaw === '') {
    echo json_encode([
        'response' => "✍️ Please type a message first."
    ]);
    exit();
}

// ---------- Helper functions ----------
$contains = function (string $haystack, array $needles): bool {
    foreach ($needles as $needle) {
        if ($needle !== '' && strpos($haystack, $needle) !== false) {
            return true;
        }
    }
    return false;
};

$safe = function ($value) {
    return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
};

// ---------- Get user dynamic data ----------
$walletBalance = 0.0;
try {
    $wallet = $db->fetch('SELECT balance FROM wallets WHERE user_id = ?', [$userId]);
    if ($wallet && isset($wallet['balance'])) {
        $walletBalance = (float)$wallet['balance'];
    }
} catch (Throwable $e) {
    // ignore, keep default 0
}

$totalSearchCount   = 0;
$mobileSearchCount  = 0;
$aadhaarSearchCount = 0;

try {
    $row = $db->fetch(
        'SELECT 
            COUNT(*) AS total,
            SUM(CASE WHEN type = "mobile"  THEN 1 ELSE 0 END) AS mobile_count,
            SUM(CASE WHEN type = "aadhaar" THEN 1 ELSE 0 END) AS aadhaar_count
         FROM search_logs
         WHERE user_id = ?',
        [$userId]
    );

    if ($row) {
        $totalSearchCount   = (int)($row['total'] ?? 0);
        $mobileSearchCount  = (int)($row['mobile_count'] ?? 0);
        $aadhaarSearchCount = (int)($row['aadhaar_count'] ?? 0);
    }
} catch (Throwable $e) {
    // ignore
}

// Last search (for smarter replies)
$lastSearch = null;
try {
    $lastSearch = $db->fetch(
        'SELECT type, query, status, created_at 
         FROM search_logs 
         WHERE user_id = ? 
         ORDER BY created_at DESC 
         LIMIT 1',
        [$userId]
    );
} catch (Throwable $e) {
    // ignore
}

// ---------- Build responses ----------
$responses = [];

// 1) GREETING / INTRO
if ($contains($userMessageLower, ['hi', 'hello', 'hey', 'namaste', 'good morning', 'good evening'])) {
    $responses[] =
        "👋 **Welcome back, " . $safe($currentUser['name'] ?? 'User') . "!**\n\n" .
        "Here’s what I can help you with:\n" .
        "• 💰 Check wallet credits & usage\n" .
        "• 🔍 How to use **Mobile** & **Aadhaar** search\n" .
        "• 💳 Payment / add funds help\n" .
        "• 📊 Your search statistics\n" .
        "• 🆘 When to contact **Admin Support**\n\n" .
        "You can ask things like:\n" .
        "• `My balance?`\n" .
        "• `How to search mobile?`\n" .
        "• `Payment kaise karna hai?`\n" .
        "• `Show my stats`";
}

// 2) WALLET / BALANCE / CREDITS
if ($contains($userMessageLower, [
        'credit', 'credits', 'balance', 'wallet', 'amount',
        'kitna balance', 'mera balance', 'paisa', 'funds'
    ])) {

    $responses[] =
        "💰 **Wallet Details**\n\n" .
        "• Current Balance: **₹" . number_format($walletBalance, 2) . "**\n" .
        "• Mobile Search: **₹10** per search\n" .
        "• Aadhaar Search: **₹50** per search\n\n" .
        "👉 To add funds:\n" .
        "1. Open **Wallet** section in dashboard\n" .
        "2. Enter amount and create order\n" .
        "3. Pay via UPI & upload screenshot\n" .
        "4. Admin verifies and credits your wallet.\n\n" .
        "⚠️ If balance is low, your searches may fail due to insufficient credits.";
}

// 3) SEARCH HELP (MOBILE / AADHAAR HOW-TO)
if ($contains($userMessageLower, [
        'how to search', 'search kaise', 'search karna', 'search', 'mobile search', 'aadhaar search',
        'mobile kaise', 'aadhaar kaise', 'find mobile', 'number search', 'lookup'
    ])) {

    $responses[] =
        "🔍 **How to use Search**\n\n" .
        "**📱 Mobile Search**\n" .
        "1. Go to **Mobile Search** tab\n" .
        "2. Enter valid **10-digit** Indian mobile number (starts with 6–9)\n" .
        "3. Click **Search**\n" .
        "4. Results will show name, circle, address (if available)\n\n" .
        "**🆔 Aadhaar Search**\n" .
        "1. Go to **Aadhaar Search** tab\n" .
        "2. Enter **12-digit** Aadhaar number\n" .
        "3. Click **Search**\n" .
        "4. You’ll see address and household details (if available)\n\n" .
        "💡 *Pro tip:* Recent searches appear below each search box — you can tap them to re-run quickly.";
}

// 4) PAYMENT / UPI / APPROVAL FLOW
if ($contains($userMessageLower, [
        'payment', 'pay', 'upi', 'amount pay', 'transaction', 'utr', 'approve payment', 'payment status'
    ])) {

    $responses[] =
        "💳 **Payment & Add Funds Guide**\n\n" .
        "1️⃣ Go to **Wallet → Add Credits**\n" .
        "2️⃣ Enter the amount you want to add\n" .
        "3️⃣ System will show **UPI ID / QR** + an **Order ID**\n" .
        "4️⃣ Pay using your UPI app (same amount)\n" .
        "5️⃣ Enter **UTR / Transaction ID** and upload screenshot\n" .
        "6️⃣ Submit payment.\n\n" .
        "⏱️ **Verification Time:** usually **30 minutes – 2 hours** (depending on admin availability).\n\n" .
        "If it’s been long and not approved, you can:\n" .
        "• Open **Support Chat** and send your *Order ID + UTR*\n" .
        "• Or use the **Admin Chat** option from the assistant bubble.";
}

// 5) STATISTICS / USAGE / ACTIVITY
if ($contains($userMessageLower, [
        'statistic', 'stats', 'usage', 'how many', 'kitne search', 'search count', 'activity', 'history'
    ])) {

    $responses[] =
        "📊 **Your Account Stats**\n\n" .
        "• Total Searches: **{$totalSearchCount}**\n" .
        "• 📱 Mobile Searches: **{$mobileSearchCount}**\n" .
        "• 🆔 Aadhaar Searches: **{$aadhaarSearchCount}**\n" .
        "• Current Balance: **₹" . number_format($walletBalance, 2) . "**\n\n" .
        "You can also open the **Analytics** tab on your dashboard for:\n" .
        "• Credit usage\n" .
        "• Success rate\n" .
        "• Recent activity timeline.";
}

// 6) LAST SEARCH CONTEXT
if ($contains($userMessageLower, ['last search', 'previous search', 'last result', 'mera last'])) {
    if ($lastSearch) {
        $responses[] =
            "🕒 **Your Last Search**\n\n" .
            "• Type: **" . strtoupper($lastSearch['type']) . "**\n" .
            "• Query: `" . $safe($lastSearch['query']) . "`\n" .
            "• Status: **" . strtoupper($lastSearch['status']) . "**\n" .
            "• Time: `" . $safe($lastSearch['created_at']) . "`\n\n" .
            "You can open the **Dashboard → Recent Searches** table to view complete details.";
    } else {
        $responses[] = "ℹ️ You haven’t done any searches yet. Try a **Mobile** or **Aadhaar** search from dashboard.";
    }
}

// 7) AADHAAR SPECIFIC
if ($contains($userMessageLower, ['aadhaar', 'adhar', 'aadhar'])) {
    $responses[] =
        "🆔 **Aadhaar Search Info**\n\n" .
        "• Use a valid **12-digit** Aadhaar number\n" .
        "• Each Aadhaar search costs **₹50** from your wallet\n" .
        "• You’ll typically see address + household details if available\n\n" .
        "⚠️ Make sure:\n" .
        "• You have enough wallet balance\n" .
        "• You enter the Aadhaar number correctly (no spaces).";
}

// 8) ACCOUNT / PROFILE
if ($contains($userMessageLower, ['account', 'profile', 'name change', 'email change', 'password'])) {
    $responses[] =
        "👤 **Account & Profile Management**\n\n" .
        "• To edit name/email → open **Profile** tab\n" .
        "• To change password → click **Change Password** button in Profile\n" .
        "• Your Account ID: `SSNT" . (int)$userId . "`\n\n" .
        "🔒 We don’t show your password anywhere. You can only reset/change it using the profile section.";
}

// 9) FEATURES / WHAT CAN I DO
if ($contains($userMessageLower, ['feature', 'can i', 'kya kar sakta', 'what can you do'])) {
    $responses[] =
        "⭐ **Things I can help you with (inside this dashboard):**\n\n" .
        "• 💰 Wallet balance, credits, and pricing\n" .
        "• 🔍 How to use **Mobile / Aadhaar** search\n" .
        "• 💳 Payment & add-funds process\n" .
        "• 📊 Your usage and statistics\n" .
        "• 👤 Profile / account related info\n" .
        "• 🆘 When to use **Support Chat** / **Admin Chat**\n\n" .
        "For technical or complex issues, I will guide you to contact **Admin**.";
}

// 10) SUPPORT / ADMIN / ISSUE
if ($contains($userMessageLower, [
        'support', 'issue', 'problem', 'error', 'bug',
        'admin', 'chat with admin', 'contact admin', 'help me', 'urgent'
    ])) {

    $responses[] =
        "🆘 **Need human support?**\n\n" .
        "You have two options:\n\n" .
        "1️⃣ **Admin Chat (inside this bubble)**\n" .
        "• Click **Contact Admin** button in the assistant bubble\n" .
        "• You’ll chat directly with support team\n\n" .
        "2️⃣ **Support Chat (Dashboard)**\n" .
        "• Open **Support** section from sidebar\n" .
        "• Click **Open Chat** to start conversation\n\n" .
        "💡 When you message admin, always include:\n" .
        "• Your **Account ID** (SSNT$userId)\n" .
        "• Any **Order ID / UTR** if it is payment related.\n";
}

// 11) HELP / MENU
if ($contains($userMessageLower, ['help', 'guide', 'menu', 'options', 'how work'])) {
    $responses[] =
        "📚 **Help Menu**\n\n" .
        "You can ask me:\n" .
        "• `My balance`\n" .
        "• `How to use mobile search`\n" .
        "• `Aadhaar search details`\n" .
        "• `How to add funds`\n" .
        "• `Show my stats`\n" .
        "• `Last search info`\n" .
        "• `How to contact admin`\n\n" .
        "Just type your question in simple English or Hinglish, I’ll understand 🙂";
}

// 12) If NOTHING matched → General smart fallback
if (empty($responses)) {
    $responses[] =
        "🤔 I’m not fully sure about that.\n\n" .
        "But here are topics I *do* understand well:\n\n" .
        "• 💰 Wallet / credits / balance\n" .
        "• 🔍 Mobile & Aadhaar search usage\n" .
        "• 💳 Payments, UPI, and add funds\n" .
        "• 📊 Your search statistics\n" .
        "• 🆘 How to contact admin / support\n\n" .
        "Try asking something like:\n" .
        "`How many credits I have?`\n" .
        "`Search kaise karna hai?`\n" .
        "`Payment help`\n" .
        "`Show my stats`";
}

// Pick one response (if multiple matched)
$responseText = $responses[array_rand($responses)];

// ---------- Log the conversation (safe insert) ----------
try {
    if (method_exists($db, 'insert')) {
        $db->insert('chat_logs', [
            'user_id'      => $userId,
            'user_message' => $userMessageRaw,
            'ai_response'  => $responseText,
            'created_at'   => date('Y-m-d H:i:s')
        ]);
    } else {
        // Fallback if insert() is not available
        $db->query(
            'INSERT INTO chat_logs (user_id, user_message, ai_response, created_at) VALUES (?, ?, ?, NOW())',
            [$userId, $userMessageRaw, $responseText]
        );
    }
} catch (Throwable $e) {
    // Silently ignore logging errors
}

echo json_encode([
    'response'  => $responseText,
    'isAI'      => true,
    'timestamp' => date('H:i')
]);
?>
