<?php
// Free AI Chat Assistant - Rule-based 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 chat.']);
    exit();
}

$currentUser = $auth->getCurrentUser();
$userId = $currentUser['id'];
$userMessage = strtolower(trim($_POST['message'] ?? ''));

if (empty($userMessage)) {
    echo json_encode(['response' => 'Please type a message.']);
    exit();
}

// Get user info for dynamic responses
$wallet = $db->fetch('SELECT balance FROM wallets WHERE user_id = ?', [$userId]);
$walletBalance = $wallet ? $wallet['balance'] : 0;

$searches = $db->fetchAll("SELECT COUNT(*) as count FROM search_logs WHERE user_id = $userId");
$searchCount = $searches[0]['count'] ?? 0;

// Free AI - Rule-based responses
$responses = [];

// Credit/Wallet queries
if (strpos($userMessage, 'credit') !== false || strpos($userMessage, 'balance') !== false || strpos($userMessage, 'wallet') !== false) {
    $responses[] = "💰 **Wallet Balance:** ₹" . number_format($walletBalance, 2) . "\n\n📱 **Mobile Search:** ₹10 per search\n🆔 **Aadhaar Search:** ₹50 per search\n\nLow on credits? Click **Add Funds** in Wallet section!";
}

// Search help
if (strpos($userMessage, 'how to search') !== false || strpos($userMessage, 'search') !== false || strpos($userMessage, 'mobile') !== false) {
    $responses[] = "🔍 **Search Steps:**\n\n**Mobile Search:**\n1. Go to Mobile Search\n2. Enter 10-digit number\n3. Click Search button\n4. Get instant results\n\n**Aadhaar Search:**\n1. Go to Aadhaar Search\n2. Enter 12-digit number\n3. Click Search button\n4. View person info\n\n💡 **Pro tip:** Use suggestions dropdown for faster searching!";
}

// Payment queries
if (strpos($userMessage, 'payment') !== false || strpos($userMessage, 'approve') !== false || strpos($userMessage, 'pay') !== false) {
    $responses[] = "💳 **How to Make Payment:**\n\n**Step 1:** Go to Wallet → Add Funds\n**Step 2:** Choose amount\n**Step 3:** Click payment method\n**Step 4:** Upload payment proof\n**Step 5:** Admin reviews (2 hours)\n**Step 6:** Credits added!\n\n⏱️ **Wait time:** Usually 30 mins to 2 hours\n\n❓ Issues? Open Support Chat!";
}

// Usage statistics
if (strpos($userMessage, 'statistic') !== false || strpos($userMessage, 'usage') !== false || strpos($userMessage, 'how many') !== false) {
    $responses[] = "📊 **Your Stats:**\n\n🔍 Total Searches: **$searchCount**\n💰 Current Balance: **₹" . number_format($walletBalance, 2) . "**\n📱 Account: **Active & Verified**\n\n➡️ **View detailed analytics** in Analytics section!";
}

// Greeting
if (strpos($userMessage, 'hi') !== false || strpos($userMessage, 'hello') !== false || strpos($userMessage, 'hey') !== false) {
    $responses[] = "👋 **Welcome back, " . htmlspecialchars($currentUser['name']) . "!**\n\nI can help with:\n📱 **Search** - How searches work\n💰 **Credits** - Check balance & add funds\n💳 **Payments** - Payment process\n📊 **Stats** - View your analytics\n\nJust click the buttons above or ask me anything!";
}

// Help menu
if (strpos($userMessage, 'help') !== false || strpos($userMessage, 'what') !== false) {
    $responses[] = "📚 **I can help with:**\n\n✓ Credit balance queries\n✓ How to search\n✓ Payment information\n✓ Account statistics\n✓ Feature explanations\n\n📞 For urgent issues, use **Support Chat** to talk with admin!";
}

// Contact support / Escalate to admin
if (strpos($userMessage, 'support') !== false || strpos($userMessage, 'issue') !== false || strpos($userMessage, 'problem') !== false || strpos($userMessage, 'admin') !== false || strpos($userMessage, 'chat with admin') !== false) {
    $responses[] = "🆘 **Need Direct Support?**\n\n**Option 1: Chat with Admin**\n➡️ Click button 'Chat with Admin' to start direct conversation\n\n**Option 2: Support Chat**\n1. Go to Support Chat from dashboard\n2. Chat with our admin team\n3. Get instant help\n\n⚡ Admin typically responds within 30 minutes!";
}

// Features
if (strpos($userMessage, 'feature') !== false || strpos($userMessage, 'can i') !== false) {
    $responses[] = "⭐ **Cool Features:**\n\n✨ Mobile Search\n✨ Aadhaar Search  \n✨ Search History\n✨ Favorites/Saved Results\n✨ Real-time Chat Support\n✨ Transaction History\n✨ Account Management\n\nMore features coming soon!";
}

// Premium/Plan questions
if (strpos($userMessage, 'plan') !== false || strpos($userMessage, 'premium') !== false) {
    $responses[] = "🎯 **Plans Coming Soon!**\n\nCurrently using pay-per-search model.\n\nWe're working on:\n💎 Monthly Plans\n💎 Unlimited searches\n💎 Exclusive features\n💎 Better pricing\n\nStay tuned! 🚀";
}

// Aadhaar questions
if (strpos($userMessage, 'aadhaar') !== false) {
    $responses[] = "🆔 **Aadhaar Search:**\n\n• Enter valid 12-digit Aadhaar number\n• Costs ₹50 per search\n• Get instant results\n• View personal information\n\n✓ 100% Secure & Private\n✓ Data never stored\n✓ Instant results";
}

// Account/Profile
if (strpos($userMessage, 'account') !== false || strpos($userMessage, 'profile') !== false) {
    $responses[] = "👤 **Account Management:**\n\n1. Go to **Profile** section\n2. View/Edit your information\n3. Change password\n4. Update contact details\n\n🔒 Your data is secure!";
}

// If no match, give general response
if (empty($responses)) {
    $responses[] = "😊 I'm not sure about that. Here are things I can help with:\n\n💰 Check credit balance\n🔍 Search help\n💳 Payment info\n📊 Your statistics\n📞 Contact support\n\nType any of these keywords or say 'help'!";
}

// Pick random response from matches
$response = $responses[array_rand($responses)];

// Log the conversation (optional - table may not exist)
$logSql = "INSERT INTO chat_logs (user_id, user_message, ai_response, created_at) 
           VALUES ($userId, '" . addslashes($userMessage) . "', '" . addslashes($response) . "', NOW())";
@$db->query($logSql); // Suppress error if table doesn't exist

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