<?php
/**
 * Live Chat AI API - Robust Version with Better Error Handling
 * Real-Time AI Integration for FAREN Interior Design
 */

// Enable error logging
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/../../chat-api-errors.log');

// Load environment first
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;
}

// Global error handler
set_error_handler(function($errno, $errstr, $errfile, $errline) {
    error_log("Chat API Error [$errno]: $errstr in $errfile on line $errline");
    if ($errno >= E_WARNING) {
        http_response_code(500);
        echo json_encode([
            'success' => false,
            'error' => 'Server error occurred. Please try again.'
        ]);
        exit;
    }
    return false;
});

// Main handler
try {
    $action = isset($_GET['action']) ? sanitizeInput($_GET['action']) : '';
    $method = $_SERVER['REQUEST_METHOD'];

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

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

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

        case 'get_status':
            handleGetStatus();
            break;

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

/**
 * Send message and get AI response
 */
function handleSendMessage()
{
    global $connection;
    
    if (!$connection) {
        throw new Exception('Database connection unavailable');
    }

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

    $message = sanitizeInput($input['message']);
    $category = sanitizeInput($input['category'] ?? 'service');
    $session_id = sanitizeInput($input['session_id'] ?? '');
    $user_email = sanitizeInput($input['user_email'] ?? 'guest@faren.chat');

    // Validate inputs
    if (strlen($message) > 1000) {
        throw new Exception('Message exceeds maximum length');
    }

    // Create session if needed
    if (empty($session_id)) {
        $session_id = 'chat_' . uniqid() . '_' . time();
        
        // Insert session
        $query = "INSERT INTO chat_sessions (session_id, category, user_email, started_at, is_active) 
                  VALUES (?, ?, ?, NOW(), 1)";
        $stmt = $connection->prepare($query);
        if (!$stmt) {
            throw new Exception('Failed to create session: ' . $connection->error);
        }
        $stmt->bind_param('sss', $session_id, $category, $user_email);
        $stmt->execute();
        $stmt->close();
    }

    // Store user message
    $query = "INSERT INTO chat_messages (session_id, sender, message, category, user_identifier, created_at) 
              VALUES (?, 'user', ?, ?, ?, NOW())";
    $stmt = $connection->prepare($query);
    if (!$stmt) {
        throw new Exception('Failed to store message: ' . $connection->error);
    }
    $stmt->bind_param('ssss', $session_id, $message, $category, $user_email);
    if (!$stmt->execute()) {
        throw new Exception('Failed to execute message insert: ' . $stmt->error);
    }
    $stmt->close();

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

    // Store AI response
    $query = "INSERT INTO chat_messages (session_id, sender, message, category, user_identifier, created_at) 
              VALUES (?, 'assistant', ?, ?, 'ai', NOW())";
    $stmt = $connection->prepare($query);
    if (!$stmt) {
        throw new Exception('Failed to store AI response: ' . $connection->error);
    }
    $stmt->bind_param('sss', $session_id, $ai_response, $category);
    $stmt->execute();
    $stmt->close();

    // Return success
    http_response_code(200);
    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()
{
    global $connection;
    
    if (!$connection) {
        throw new Exception('Database connection unavailable');
    }

    $session_id = sanitizeInput($_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 = $connection->prepare($query);
    if (!$stmt) {
        throw new Exception('Database error: ' . $connection->error);
    }

    $stmt->bind_param('s', $session_id);
    if (!$stmt->execute()) {
        throw new Exception('Query failed: ' . $stmt->error);
    }
    
    $result = $stmt->get_result();
    $messages = [];
    
    while ($row = $result->fetch_assoc()) {
        $messages[] = $row;
    }
    
    $stmt->close();

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

/**
 * Start a new chat session
 */
function handleStartChat()
{
    global $connection;
    
    if (!$connection) {
        throw new Exception('Database connection unavailable');
    }

    $input = json_decode(file_get_contents('php://input'), true);
    
    $session_id = 'chat_' . uniqid() . '_' . time();
    $category = sanitizeInput($input['category'] ?? 'service');
    $user_email = sanitizeInput($input['user_email'] ?? 'guest@faren.chat');

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

    $stmt = $connection->prepare($query);
    if (!$stmt) {
        throw new Exception('Failed to prepare statement: ' . $connection->error);
    }

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

    // Send welcome message
    $welcome_msg = getWelcomeMessage($category);
    
    $query = "INSERT INTO chat_messages (session_id, sender, message, category, user_identifier, created_at) 
              VALUES (?, 'assistant', ?, ?, 'ai', NOW())";
    $stmt = $connection->prepare($query);
    if (!$stmt) {
        throw new Exception('Failed to store welcome: ' . $connection->error);
    }
    $stmt->bind_param('sss', $session_id, $welcome_msg, $category);
    $stmt->execute();
    $stmt->close();

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

/**
 * Get API status
 */
function handleGetStatus()
{
    global $connection;
    
    $api_key = getenv('OPENAI_API_KEY');
    $has_key = !empty($api_key);
    $db_connected = ($connection !== null && !$connection->connect_error);

    http_response_code(200);
    echo json_encode([
        'success' => true,
        'service' => 'openai',
        'connected' => $has_key && $db_connected,
        'status' => ($has_key && $db_connected) ? 'ready' : 'not_configured',
        'has_api_key' => $has_key,
        'has_database' => $db_connected
    ]);
}

/**
 * Get AI response
 */
function getAIResponse($message, $category, $session_id)
{
    $api_key = getenv('OPENAI_API_KEY');
    
    if (!empty($api_key)) {
        return getOpenAIResponse($message, $category);
    }

    // Fallback
    return getFallbackResponse($message, $category);
}

/**
 * Get OpenAI response via API
 */
function getOpenAIResponse($message, $category)
{
    $api_key = getenv('OPENAI_API_KEY');
    
    $system_prompt = getCategoryPrompt($category);

    $request = [
        'model' => 'gpt-3.5-turbo',
        'messages' => [
            ['role' => 'system', 'content' => $system_prompt],
            ['role' => 'user', 'content' => $message]
        ],
        'temperature' => 0.7,
        'max_tokens' => 500
    ];

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

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

    if ($http_code !== 200) {
        error_log("OpenAI API Error ($http_code): $response");
        if (!empty($curl_error)) {
            error_log("cURL Error: $curl_error");
        }
        return getFallbackResponse($message, $category);
    }

    $data = json_decode($response, true);
    
    if (isset($data['choices'][0]['message']['content'])) {
        return $data['choices'][0]['message']['content'];
    }

    return getFallbackResponse($message, $category);
}

/**
 * Get fallback response (when API unavailable)
 */
function getFallbackResponse($message, $category)
{
    $responses = [
        'service' => "Thank you for reaching out! We offer comprehensive interior design services. Please contact us at +91 (123) 666 000 666 for more details about our services and pricing.",
        'project' => "We'd love to help with your project! Each project is unique, and our team creates custom solutions. Please share more details about your vision.",
        'order' => "For order information, please check your account dashboard or contact our support team.",
        'contact' => "Thank you for contacting FAREN! You can reach us at +91 (123) 666 000 666 or info@faren.com. We're here to help!"
    ];

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

/**
 * Get category prompt
 */
function getCategoryPrompt($category)
{
    $prompts = [
        'service' => 'You are a helpful assistant for FAREN Interior Design. Help customers learn about interior design services, consultation processes, and design solutions. Be professional and creative.',
        'project' => 'You are a project advisor for FAREN Interior Design. Help clients discuss their interior design projects, ideas, and requirements. Be encouraging and insightful.',
        'order' => 'You are a customer support specialist for FAREN Shop. Help customers with orders, shipping, and product information. Be helpful and efficient.',
        'contact' => 'You are a customer service representative for FAREN. Provide helpful information and direct customers to appropriate resources.'
    ];

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

/**
 * Get welcome message
 */
function getWelcomeMessage($category)
{
    $messages = [
        'service' => '👋 Welcome to FAREN Services! How can we help with your interior design needs today?',
        'project' => '📐 Welcome to FAREN Projects! Let\'s discuss your interior design vision.',
        'order' => '🛍️ Welcome to FAREN Shop Support! Can I assist with an order?',
        'contact' => '📧 Welcome to FAREN Support! How can I help you?'
    ];

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

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

?>
