<?php
/**
 * AI Chatbot Interface
 * Interactive AI assistant for withdrawal calculations and guidance
 * Kenyan Pension & Life Insurance Management System
 */

require_once 'layouts/main.php';
require_once 'includes/auth.php';
require_once 'classes/AIChatbotService.php';

requireLogin();

$member_id = $_SESSION['member_id'] ?? $_SESSION['user_id'] ?? null;
$chatbotService = new AIChatbotService($conn);

// Get member data if available
$member = null;
$member_age = null;
if ($member_id) {
    $member = $conn->query("SELECT m.*, ps.scheme_name, ps.scheme_type, ps.retirement_age, 
                           ps.early_exit_max_cash_percentage, ma.accrued_benefits, ma.available_balance
                           FROM members m
                           LEFT JOIN pension_schemes ps ON m.scheme_id = ps.scheme_id
                           LEFT JOIN member_accounts ma ON m.member_id = ma.member_id
                           WHERE m.member_id = $member_id")->fetch_assoc();
    
    if ($member) {
        $member_age = date_diff(date_create($member['date_of_birth']), date_create('today'))->y;
    }
}

$pageTitle = 'AI Assistant';
include 'layouts/topbar.php';
?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'AI Assistant')); ?>
    <link rel="stylesheet" href="assets/css/pension-dashboard.css">
    <?php include 'layouts/head-css.php'; ?>
    <style>
        .chat-container {
            height: 600px;
            overflow-y: auto;
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            padding: 1rem;
            background: #f8fafc;
        }
        .chat-message {
            margin-bottom: 1rem;
            padding: 0.75rem 1rem;
            border-radius: 8px;
            max-width: 80%;
        }
        .chat-message.user {
            background: #2563eb;
            color: white;
            margin-left: auto;
            text-align: right;
        }
        .chat-message.assistant {
            background: white;
            border: 1px solid #e2e8f0;
            color: #1e293b;
        }
        .chat-message.system {
            background: #f1f5f9;
            border: 1px solid #cbd5e1;
            color: #475569;
            font-style: italic;
            font-size: 0.875rem;
        }
        .quick-actions-chat {
            display: flex;
            flex-wrap: wrap;
            gap: 0.5rem;
            margin-bottom: 1rem;
        }
        .quick-action-btn {
            padding: 0.5rem 1rem;
            background: #f1f5f9;
            border: 1px solid #cbd5e1;
            border-radius: 6px;
            cursor: pointer;
            font-size: 0.875rem;
            transition: all 0.2s;
        }
        .quick-action-btn:hover {
            background: #e2e8f0;
            border-color: #94a3b8;
        }
        .chat-input-container {
            display: flex;
            gap: 0.5rem;
            margin-top: 1rem;
        }
        .chat-input {
            flex: 1;
            padding: 0.75rem;
            border: 1px solid #cbd5e1;
            border-radius: 6px;
        }
        .typing-indicator {
            display: none;
            padding: 0.5rem;
            color: #64748b;
            font-style: italic;
        }
    </style>
</head>

<body data-sidebar="dark">
    <div id="layout-wrapper">
        <?php include 'layouts/sidebar.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <div class="welcome-header" style="background: linear-gradient(135deg, #8b5cf6 0%, #7c3aed 100%); margin-bottom: 2rem;">
                        <div class="welcome-content">
                            <div class="welcome-text">
                                <h2>AI Assistant</h2>
                                <p>Get help with withdrawal calculations and pension questions</p>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-8">
                            <div class="page-card">
                                <div class="page-card-header">
                                    <h4 class="page-card-title">
                                        <i class="ri-robot-line me-2"></i>Chat with AI Assistant
                                    </h4>
                                </div>
                                <div class="page-card-body">
                                    <div class="chat-container" id="chatContainer">
                                        <div class="chat-message system">
                                            <strong>AI Assistant:</strong> Hello! I'm here to help you understand pension withdrawal calculations, eligibility requirements, and answer questions about your pension account. How can I assist you today?
                                        </div>
                                        <?php if ($member): ?>
                                        <div class="chat-message system">
                                            <strong>Your Account Info:</strong> Age: <?php echo $member_age; ?> years | 
                                            Accrued Benefits: KES <?php echo number_format($member['accrued_benefits'], 2); ?> | 
                                            Available Balance: KES <?php echo number_format($member['available_balance'], 2); ?>
                                        </div>
                                        <?php endif; ?>
                                    </div>
                                    
                                    <div class="quick-actions-chat">
                                        <button class="quick-action-btn" onclick="askQuestion('How is my withdrawal amount calculated?')">
                                            How is withdrawal calculated?
                                        </button>
                                        <button class="quick-action-btn" onclick="askQuestion('Am I eligible for early exit withdrawal?')">
                                            Check Early Exit Eligibility
                                        </button>
                                        <button class="quick-action-btn" onclick="askQuestion('What is the difference between accrued benefits and available balance?')">
                                            Accrued vs Available Balance
                                        </button>
                                        <button class="quick-action-btn" onclick="askQuestion('What are the Kenyan pension withdrawal rules?')">
                                            Kenyan Pension Rules
                                        </button>
                                        <?php if ($member): ?>
                                        <button class="quick-action-btn" onclick="checkEligibility('EARLY_EXIT')">
                                            Check My Eligibility
                                        </button>
                                        <button class="quick-action-btn" onclick="explainMyCalculation()">
                                            Explain My Calculation
                                        </button>
                                        <?php endif; ?>
                                    </div>
                                    
                                    <div class="chat-input-container">
                                        <input type="text" 
                                               class="chat-input" 
                                               id="chatInput" 
                                               placeholder="Ask me anything about pension withdrawals..."
                                               onkeypress="if(event.key === 'Enter') sendMessage()">
                                        <button class="btn btn-primary" onclick="sendMessage()">
                                            <i class="ri-send-plane-line"></i> Send
                                        </button>
                                    </div>
                                    
                                    <div class="typing-indicator" id="typingIndicator">
                                        AI is thinking...
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-md-4">
                            <div class="page-card">
                                <div class="page-card-header">
                                    <h4 class="page-card-title">Quick Help</h4>
                                </div>
                                <div class="page-card-body">
                                    <h6>Common Questions:</h6>
                                    <ul class="list-unstyled">
                                        <li class="mb-2">
                                            <i class="ri-question-line me-2"></i>
                                            <a href="#" onclick="askQuestion('What is accrued benefits?'); return false;">What is accrued benefits?</a>
                                        </li>
                                        <li class="mb-2">
                                            <i class="ri-question-line me-2"></i>
                                            <a href="#" onclick="askQuestion('How are investment returns allocated?'); return false;">Investment returns allocation</a>
                                        </li>
                                        <li class="mb-2">
                                            <i class="ri-question-line me-2"></i>
                                            <a href="#" onclick="askQuestion('What is the maximum I can withdraw for early exit?'); return false;">Early exit limits</a>
                                        </li>
                                        <li class="mb-2">
                                            <i class="ri-question-line me-2"></i>
                                            <a href="#" onclick="askQuestion('What happens to my balance after withdrawal?'); return false;">Balance after withdrawal</a>
                                        </li>
                                    </ul>
                                    
                                    <hr>
                                    
                                    <div class="alert alert-info">
                                        <i class="ri-information-line me-2"></i>
                                        <strong>Note:</strong> AI responses are for guidance only. 
                                        Final calculations are performed by the system's stored procedures.
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>
    <?php include 'layouts/vendor-scripts.php'; ?>
    <script>
    const memberId = <?php echo $member_id ?? 'null'; ?>;
    
    function addMessage(message, type = 'assistant') {
        const container = document.getElementById('chatContainer');
        const messageDiv = document.createElement('div');
        messageDiv.className = `chat-message ${type}`;
        messageDiv.innerHTML = `<strong>${type === 'user' ? 'You' : 'AI Assistant'}:</strong> ${message}`;
        container.appendChild(messageDiv);
        container.scrollTop = container.scrollHeight;
    }
    
    function showTyping() {
        document.getElementById('typingIndicator').style.display = 'block';
    }
    
    function hideTyping() {
        document.getElementById('typingIndicator').style.display = 'none';
    }
    
    function askQuestion(question) {
        document.getElementById('chatInput').value = question;
        sendMessage();
    }
    
    function sendMessage() {
        const input = document.getElementById('chatInput');
        const question = input.value.trim();
        
        if (!question) return;
        
        addMessage(question, 'user');
        input.value = '';
        showTyping();
        
        fetch('ajax/ai_chatbot_query.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                question: question,
                member_id: memberId
            })
        })
        .then(response => response.json())
        .then(data => {
            hideTyping();
            if (data.success) {
                addMessage(data.response, 'assistant');
            } else {
                addMessage('Sorry, I encountered an error: ' + (data.message || 'Unknown error'), 'assistant');
            }
        })
        .catch(error => {
            hideTyping();
            addMessage('Sorry, I encountered an error. Please try again.', 'assistant');
            console.error('Error:', error);
        });
    }
    
    function checkEligibility(withdrawalType) {
        if (!memberId) {
            addMessage('Please log in as a member to check eligibility.', 'assistant');
            return;
        }
        
        showTyping();
        addMessage(`Checking my eligibility for ${withdrawalType} withdrawal...`, 'user');
        
        fetch('ajax/ai_check_eligibility.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                member_id: memberId,
                withdrawal_type: withdrawalType
            })
        })
        .then(response => response.json())
        .then(data => {
            hideTyping();
            if (data.success) {
                let message = `Eligibility Check Results:\n\n`;
                message += `Status: ${data.is_eligible ? '✅ Eligible' : '❌ Not Eligible'}\n`;
                message += `Eligible Amount: KES ${parseFloat(data.eligible_amount || 0).toLocaleString('en-KE', {minimumFractionDigits: 2})}\n\n`;
                
                if (data.ai_explanation) {
                    message += `Explanation:\n${data.ai_explanation}`;
                } else if (data.rejection_reason) {
                    message += `Reason: ${data.rejection_reason}`;
                }
                
                addMessage(message, 'assistant');
            } else {
                addMessage('Error checking eligibility: ' + (data.message || 'Unknown error'), 'assistant');
            }
        })
        .catch(error => {
            hideTyping();
            addMessage('Error checking eligibility. Please try again.', 'assistant');
            console.error('Error:', error);
        });
    }
    
    function explainMyCalculation() {
        if (!memberId) {
            addMessage('Please log in as a member to get calculation explanations.', 'assistant');
            return;
        }
        
        showTyping();
        addMessage('Explain how my withdrawal amount is calculated...', 'user');
        
        fetch('ajax/ai_explain_calculation.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                member_id: memberId,
                withdrawal_type: 'EARLY_EXIT' // Default, can be made dynamic
            })
        })
        .then(response => response.json())
        .then(data => {
            hideTyping();
            if (data.success && data.response) {
                addMessage(data.response, 'assistant');
            } else {
                addMessage('Error getting calculation explanation: ' + (data.message || 'Unknown error'), 'assistant');
            }
        })
        .catch(error => {
            hideTyping();
            addMessage('Error getting explanation. Please try again.', 'assistant');
            console.error('Error:', error);
        });
    }
    </script>
</body>
</html>
