<?php
/**
 * Live Chat AI API - Real-Time Integration
 * Handles real-time AI chat messages with streaming support
 */

require_once __DIR__ . '/../../config/env-loader.php';
require_once __DIR__ . '/../../config/db.php';

// Set JSON response header
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

// Handle CORS preflight
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

// Get request parameters
$action = isset($_GET['action']) ? sanitize($_GET['action']) : '';
$method = $_SERVER['REQUEST_METHOD'];

try {
    switch ($action) {
        case 'send_message':
            if ($method !== 'POST') {
                throw new Exception('Invalid request method');
            }
            handleSendMessage($conn);
            break;

        case 'get_messages':
            if ($method !== 'GET') {
                throw new Exception('Invalid request method');
            }
            handleGetMessages($conn);
            break;

        case 'start_chat':
            if ($method !== 'POST') {
                throw new Exception('Invalid request method');
            }
            handleStartChat($conn);
            break;

        case 'get_status':
            handleGetStatus();
            break;

        default:
            throw new Exception('Unknown action: ' . $action);
    }
} catch (Exception $e) {
    http_response_code(400);
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}

/**
 * Send a message and get AI response
 */
function handleSendMessage($conn = null)
{
    // Ensure connection exists
    if (!$conn) {
        global $connection;
        $conn = $connection ?? null;
    }
    
    if (!$conn) {
        throw new Exception('Database connection failed');
    }

    $data = json_decode(file_get_contents('php://input'), true);
    
    if (!$data || empty($data['message'])) {
        throw new Exception('Message is required');
    }

    $message = sanitize($data['message']);
    $category = sanitize($data['category'] ?? 'general');
    $session_id = sanitize($data['session_id'] ?? '');
    $user_email = sanitize($data['user_email'] ?? 'guest');

    // Create chat session if needed
    if (empty($session_id)) {
        $session_id = generateSessionId();
    }

    // Store user message
    storeMessage($conn, $session_id, 'user', $message, $category, $user_email);

    // Get AI response
    $ai_response = getAIResponse($message, $category, $session_id, $conn);

    // Store AI response
    storeMessage($conn, $session_id, 'assistant', $ai_response, $category, 'ai');

    // Return response
    echo json_encode([
        'success' => true,
        'session_id' => $session_id,
        'message' => $message,
        'response' => $ai_response,
        'timestamp' => date('Y-m-d H:i:s'),
        'category' => $category
    ]);
}

/**
 * Get chat messages for a session
 */
function handleGetMessages($conn)
{
    $session_id = sanitize($_GET['session_id'] ?? '');
    
    if (empty($session_id)) {
        throw new Exception('Session ID is required');
    }

    $query = "SELECT id, session_id, sender, message, category, created_at 
              FROM chat_messages 
              WHERE session_id = ? 
              ORDER BY created_at ASC 
              LIMIT 50";

    $stmt = $conn->prepare($query);
    if (!$stmt) {
        throw new Exception('Database error: ' . $conn->error);
    }

    $stmt->bind_param('s', $session_id);
    $stmt->execute();
    $result = $stmt->get_result();

    $messages = [];
    while ($row = $result->fetch_assoc()) {
        $messages[] = $row;
    }

    echo json_encode([
        'success' => true,
        'session_id' => $session_id,
        'messages' => $messages,
        'count' => count($messages)
    ]);
}

/**
 * Start a new chat session
 */
function handleStartChat($conn)
{
    $data = json_decode(file_get_contents('php://input'), true);
    
    $session_id = generateSessionId();
    $category = sanitize($data['category'] ?? 'general');
    $user_email = sanitize($data['user_email'] ?? 'guest');

    // Create session in database
    $query = "INSERT INTO chat_sessions (session_id, category, user_email, started_at) 
              VALUES (?, ?, ?, NOW())";

    $stmt = $conn->prepare($query);
    if (!$stmt) {
        throw new Exception('Database error: ' . $conn->error);
    }

    $stmt->bind_param('sss', $session_id, $category, $user_email);
    
    if (!$stmt->execute()) {
        throw new Exception('Failed to create chat session');
    }

    // Send welcome message
    $welcome_msg = getWelcomeMessage($category);
    storeMessage($conn, $session_id, 'assistant', $welcome_msg, $category, 'ai');

    echo json_encode([
        'success' => true,
        'session_id' => $session_id,
        'category' => $category,
        'welcome_message' => $welcome_msg
    ]);
}

/**
 * Get AI service status
 */
function handleGetStatus()
{
    $ai_service = getenv('AI_SERVICE') ?: 'openai';
    $api_key_exists = !empty(getenv('OPENAI_API_KEY'));

    echo json_encode([
        'success' => true,
        'service' => $ai_service,
        'connected' => $api_key_exists,
        'status' => $api_key_exists ? 'ready' : 'not_configured'
    ]);
}

/**
 * Get AI response using OpenAI API
 */
function getAIResponse($message, $category, $session_id, $conn)
{
    // Get conversation context
    $context = getConversationContext($session_id, $conn);
    
    // Build system prompt based on category
    $system_prompt = getCategoryPrompt($category);

    // Try to use OpenAI API first
    $api_key = getenv('OPENAI_API_KEY');
    
    if (!empty($api_key)) {
        return getOpenAIResponse($message, $system_prompt, $context, $api_key);
    }

    // Fallback to category-based responses
    return getFallbackResponse($message, $category);
}

/**
 * Get response from OpenAI API
 */
function getOpenAIResponse($message, $system_prompt, $context, $api_key)
{
    // Build messages array with conversation history
    $messages = [
        ['role' => 'system', 'content' => $system_prompt]
    ];

    // Add conversation context
    foreach ($context as $ctx_msg) {
        $messages[] = [
            'role' => $ctx_msg['sender'] === 'user' ? 'user' : 'assistant',
            'content' => $ctx_msg['message']
        ];
    }

    // Add current message
    $messages[] = ['role' => 'user', 'content' => $message];

    $request_body = [
        'model' => 'gpt-3.5-turbo',
        'messages' => $messages,
        'temperature' => 0.7,
        'max_tokens' => 500,
        'top_p' => 0.9,
        'frequency_penalty' => 0.5,
        'presence_penalty' => 0.5
    ];

    $ch = curl_init('https://api.openai.com/v1/chat/completions');
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_HTTPHEADER => [
            'Content-Type: application/json',
            'Authorization: Bearer ' . $api_key
        ],
        CURLOPT_POSTFIELDS => json_encode($request_body)
    ]);

    $response = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($http_code !== 200) {
        error_log('OpenAI API Error: ' . $response);
        return getFallbackResponse($message, 'general');
    }

    $data = json_decode($response, true);
    return $data['choices'][0]['message']['content'] ?? 'I understand. How can I assist you further?';
}

/**
 * Get fallback response when AI API is not available
 */
function getFallbackResponse($message, $category)
{
    $keywords = strtolower($message);
    
    $responses = [
        'service' => [
            'What services are available?' => 'We offer residential interior design, commercial design, and consultation packages.',
            'price' => 'Our pricing varies based on project scope. Please contact us for a custom quote.',
            'how long' => 'Project timelines range from 2-6 months depending on complexity.',
            'book' => 'You can book a consultation through our website or by contacting us directly.',
            'design' => 'Our design process includes consultation, concept creation, 3D visualization, and implementation.',
            'default' => 'Thank you for your interest in our services! What specifically would you like to know?'
        ],
        'project' => [
            'portfolio' => 'We have completed over 100+ interior design projects. Visit our portfolio to see examples.',
            'past' => 'Our projects include residential, commercial, and hospitality designs.',
            'timeline' => 'Most projects take 3-6 months from planning to completion.',
            'process' => 'Our process: consultation → design → approval → implementation → final walkthrough.',
            'default' => 'I\'d love to help with your project! Could you tell me more about what you\'re looking for?'
        ],
        'order' => [
            'track' => 'You can track your order in your account dashboard under "Orders".',
            'delivery' => 'Standard delivery is 5-7 business days. Expedited options available.',
            'return' => 'We offer 30-day returns on all products in original condition.',
            'ship' => 'We ship nationwide with free shipping on orders over $500.',
            'modify' => 'Orders can be modified within 24 hours of purchase.',
            'default' => 'I\'m here to help with your order! What would you like to know?'
        ],
        'contact' => [
            'phone' => 'You can reach us at (555) 123-4567 during business hours.',
            'email' => 'Email us at support@faren.com for detailed inquiries.',
            'meeting' => 'We offer virtual and in-person consultations. Which would you prefer?',
            'hours' => 'We\'re available Monday-Friday, 9am-6pm EST.',
            'location' => 'Our office is located in downtown at 123 Design Avenue.',
            'default' => 'Thank you for reaching out! How can I assist you today?'
        ]
    ];

    $category_responses = $responses[$category] ?? $responses['contact'];
    
    foreach ($category_responses as $keyword => $response) {
        if ($keyword === 'default') continue;
        if (strpos($keywords, $keyword) !== false) {
            return $response;
        }
    }

    return $category_responses['default'] ?? 'How can I help you?';
}

/**
 * Get category-specific system prompt
 */
function getCategoryPrompt($category)
{
    $prompts = [
        'service' => 'You are a helpful interior design service assistant for FAREN. Help customers understand our design services, pricing, and consultation process. Be professional and informative.',
        'project' => 'You are a project manager assistant for FAREN interior design. Help clients discuss their project ideas, timelines, and requirements. Be creative and encouraging.',
        'order' => 'You are a customer support assistant for FAREN shop. Help customers with orders, tracking, shipping, and returns. Be helpful and efficient.',
        'contact' => 'You are a general customer service assistant for FAREN. Provide helpful information and direct customers to the right resources.'
    ];

    return $prompts[$category] ?? $prompts['contact'];
}

/**
 * Get welcome message based on category
 */
function getWelcomeMessage($category)
{
    $messages = [
        'service' => '👋 Welcome to FAREN Service Support! I\'m here to help you learn about our interior design services, pricing, and consultation process. What would you like to know?',
        'project' => '📐 Welcome to FAREN Project Support! Let\'s discuss your interior design project ideas, timeline, and vision. Tell me more about what you\'re looking to create.',
        'order' => '📦 Welcome to FAREN Order Support! I can help you with tracking, shipping, returns, and any order-related questions. What do you need?',
        'contact' => '📧 Welcome to FAREN Support! How can I assist you today? Feel free to ask about our services, projects, orders, or anything else.'
    ];

    return $messages[$category] ?? $messages['contact'];
}

/**
 * Get conversation context for better AI responses
 */
function getConversationContext($session_id, $conn)
{
    $query = "SELECT sender, message FROM chat_messages 
              WHERE session_id = ? 
              ORDER BY created_at ASC 
              LIMIT 10";

    $stmt = $conn->prepare($query);
    $stmt->bind_param('s', $session_id);
    $stmt->execute();
    $result = $stmt->get_result();

    $context = [];
    while ($row = $result->fetch_assoc()) {
        $context[] = $row;
    }

    return $context;
}

/**
 * Store message in database
 */
function storeMessage($conn, $session_id, $sender, $message, $category, $user_identifier)
{
    $query = "INSERT INTO chat_messages (session_id, sender, message, category, user_identifier) 
              VALUES (?, ?, ?, ?, ?)";

    $stmt = $conn->prepare($query);
    if (!$stmt) {
        error_log('Database error: ' . $conn->error);
        return false;
    }

    $stmt->bind_param('sssss', $session_id, $sender, $message, $category, $user_identifier);
    return $stmt->execute();
}

/**
 * Generate unique session ID
 */
function generateSessionId()
{
    return 'chat_' . bin2hex(random_bytes(16)) . '_' . time();
}

/**
 * Sanitize input
 */
function sanitize($input)
{
    return htmlspecialchars(trim($input), ENT_QUOTES, 'UTF-8');
}
