<?php
// Admin AI Assistant - Help admin respond to users better
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);

// Check if admin
if (!$auth->isLoggedIn() || !$auth->isAdmin()) {
    echo json_encode(['success' => false, 'message' => 'Admin access required']);
    exit();
}

$action = $_POST['action'] ?? '';
$data = $_POST['data'] ?? '';

// Action: Get suggested responses for a user query
if ($action === 'suggest_response') {
    $ticketId = $_POST['ticket_id'] ?? 0;
    $userMessage = strtolower(trim($_POST['user_message'] ?? ''));
    
    if (empty($userMessage)) {
        echo json_encode(['success' => false, 'message' => 'No message provided']);
        exit();
    }
    
    $suggestions = [];
    
    // Keyword-based suggestions
    if (strpos($userMessage, 'credit') !== false || strpos($userMessage, 'balance') !== false) {
        $suggestions[] = "You can check your wallet balance in the Wallet section. Mobile searches cost ₹10 and Aadhaar searches cost ₹50. Need more credits? Click 'Add Funds' to make a payment.";
        $suggestions[] = "Your current balance will be displayed in the Wallet section. Would you like me to help you add more credits?";
    }
    
    if (strpos($userMessage, 'search') !== false || strpos($userMessage, 'how') !== false) {
        $suggestions[] = "**Mobile Search:** Enter the 10-digit phone number and click search. You'll get instant results.\n\n**Aadhaar Search:** Enter the 12-digit Aadhaar number. Results will appear immediately.";
        $suggestions[] = "Mobile Search is for finding info by phone number (₹10). Aadhaar Search is for finding info by Aadhaar number (₹50). Both are instant!";
    }
    
    if (strpos($userMessage, 'payment') !== false || strpos($userMessage, 'pay') !== false || strpos($userMessage, 'approve') !== false) {
        $suggestions[] = "To add credits:\n1. Go to Wallet\n2. Click 'Add Funds'\n3. Choose your payment method\n4. Upload payment proof\n5. We'll verify within 2 hours\n\nOnce approved, credits are instant!";
        $suggestions[] = "Payment usually takes 30 mins to 2 hours to verify. You'll get a notification once approved. Can I help with anything else?";
    }
    
    if (strpos($userMessage, 'error') !== false || strpos($userMessage, 'not working') !== false || strpos($userMessage, 'issue') !== false) {
        $suggestions[] = "I understand you're facing an issue. Can you please share:\n1. What were you trying to do?\n2. What error message did you see?\n3. When did this happen?\n\nThis will help me assist you better.";
        $suggestions[] = "Let me investigate this for you. Can you provide more details about what's happening?";
    }
    
    if (strpos($userMessage, 'result') !== false || strpos($userMessage, 'data') !== false || strpos($userMessage, 'information') !== false) {
        $suggestions[] = "Results are provided instantly. If you're not seeing them, it could mean:\n1. The number/Aadhaar might not be in our database\n2. You might have insufficient credits\n3. There could be a temporary issue\n\nLet me check your account...";
        $suggestions[] = "The search system checks our database and returns results in seconds. If no results appear, the information might not be available for that number.";
    }
    
    if (strpos($userMessage, 'history') !== false || strpos($userMessage, 'previous') !== false) {
        $suggestions[] = "Your search history is available in the dashboard. You can view all your past searches and clear history if needed. Is there a specific search you're looking for?";
        $suggestions[] = "All your searches are logged with timestamps. You can see them in your Search History section anytime.";
    }
    
    if (strpos($userMessage, 'account') !== false || strpos($userMessage, 'profile') !== false) {
        $suggestions[] = "You can manage your account in the Profile section:\n• View your details\n• Change password\n• Update contact information\n• Manage preferences\n\nNeed help with something specific?";
        $suggestions[] = "Your account is secure and verified. You can update your profile information anytime from the Profile section.";
    }
    
    if (strpos($userMessage, 'feedback') !== false || strpos($userMessage, 'suggest') !== false || strpos($userMessage, 'feature') !== false) {
        $suggestions[] = "Thank you for your feedback! We're always working to improve our platform. Your suggestions help us serve you better. Is there anything specific you'd like to suggest?";
        $suggestions[] = "We appreciate your input! Features are constantly being added based on user feedback. Keep the ideas coming! 🚀";
    }
    
    // If no specific match, give general helpful response
    if (empty($suggestions)) {
        $suggestions[] = "Thank you for reaching out. I'm here to help. Could you provide more details about your question so I can assist you better?";
        $suggestions[] = "I understand. Let me help you with that. Can you tell me a bit more about what you need?";
    }
    
    echo json_encode([
        'success' => true,
        'suggestions' => $suggestions
    ]);
    exit();
}

// Action: Get response template
if ($action === 'get_templates') {
    $templates = [
        [
            'title' => 'Welcome Response',
            'text' => 'Hello! 👋 Thank you for reaching out. How can I help you today?'
        ],
        [
            'title' => 'Under Investigation',
            'text' => 'I\'m looking into your issue right now. Let me check your account details and I\'ll get back to you shortly.'
        ],
        [
            'title' => 'Issue Resolved',
            'text' => '✅ Great news! I\'ve resolved your issue. Your credits should be updated now. Please refresh and check. Let me know if you need anything else!'
        ],
        [
            'title' => 'Need More Info',
            'text' => 'Thank you for providing those details. I need a bit more information to help you better. Could you please share...'
        ],
        [
            'title' => 'Technical Issue',
            'text' => 'I understand you\'re experiencing a technical issue. Let me escalate this to our technical team. We\'ll get this fixed for you ASAP!'
        ],
        [
            'title' => 'Payment Pending',
            'text' => '⏳ Your payment is being verified. Usually takes 30 mins to 2 hours. You\'ll receive a notification once it\'s approved!'
        ],
        [
            'title' => 'Payment Approved',
            'text' => '✅ Payment approved! Your credits have been added to your wallet. You can start searching immediately!'
        ],
        [
            'title' => 'Follow Up',
            'text' => 'Just checking in! Is everything working smoothly now? Let me know if you need further assistance.'
        ]
    ];
    
    echo json_encode([
        'success' => true,
        'templates' => $templates
    ]);
    exit();
}

echo json_encode(['success' => false, 'message' => 'Invalid action']);
?>
