<?php
/**
 * FAREN Chat AI API v3
 * Simplified, robust real-time chat API
 * Production-ready with proper error handling
 */

// Start output buffering to prevent headers being sent too early
ob_start();

// Set error handler
error_reporting(E_ALL);
ini_set('display_errors', 0);
ini_set('log_errors', 1);

// Load environment variables FIRST
$envFile = __DIR__ . '/../../.env';
if (file_exists($envFile)) {
    $lines = file($envFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    foreach ($lines as $line) {
        if (strpos(trim($line), '#') === 0) continue;
        if (strpos($line, '=') !== false) {
            list($key, $value) = explode('=', $line, 2);
            $key = trim($key);
            $value = trim(trim($value), '"\'');
            putenv("$key=$value");
            $_ENV[$key] = $value;
        }
    }
}

// Load database
require_once __DIR__ . '/../../config/db.php';

// Clear any previous output
ob_clean();

// Create necessary tables if they don't exist
if (isset($connection) && !$connection->connect_error) {
    // Create chat_sessions table
    $connection->query("CREATE TABLE IF NOT EXISTS chat_sessions (
        id INT AUTO_INCREMENT PRIMARY KEY,
        session_id VARCHAR(100) UNIQUE NOT NULL,
        category VARCHAR(50) NOT NULL,
        user_email VARCHAR(100),
        started_at DATETIME DEFAULT CURRENT_TIMESTAMP,
        ended_at DATETIME NULL,
        is_active TINYINT DEFAULT 1,
        INDEX idx_session_id (session_id),
        INDEX idx_user_email (user_email)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");
    
    // Create chat_messages table
    $connection->query("CREATE TABLE IF NOT EXISTS chat_messages (
        id INT AUTO_INCREMENT PRIMARY KEY,
        session_id VARCHAR(100) NOT NULL,
        sender VARCHAR(50) NOT NULL,
        message LONGTEXT NOT NULL,
        category VARCHAR(50),
        user_identifier VARCHAR(100),
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
        INDEX idx_session_id (session_id),
        INDEX idx_created_at (created_at),
        FOREIGN KEY (session_id) REFERENCES chat_sessions(session_id) ON DELETE CASCADE
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");
}

// Check database connection
if (!isset($connection) || $connection->connect_error) {
    // Set headers early to prevent "headers already sent" error
    header('Content-Type: application/json; charset=utf-8');
    http_response_code(500);
    die(json_encode(['success' => false, 'error' => 'Database connection failed']));
}

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

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

try {
    $action = $_GET['action'] ?? '';
    
    switch ($action) {
        case 'get_status':
            getStatus();
            break;
        case 'start_chat':
            startChat();
            break;
        case 'send_message':
            sendMessage();
            break;
        case 'get_messages':
            getMessages();
            break;
        default:
            throw new Exception("Unknown action: $action");
    }
} catch (Exception $e) {
    http_response_code(400);
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}

/**
 * Get API status
 */
function getStatus() {
    $apiKey = getenv('OPENAI_API_KEY');
    $hasKey = !empty($apiKey);
    
    http_response_code(200);
    echo json_encode([
        'success' => true,
        'connected' => $hasKey,
        'status' => $hasKey ? 'ready' : 'not_configured',
        'service' => 'openai',
        'timestamp' => date('Y-m-d H:i:s')
    ]);
}

/**
 * Start a new chat session
 */
function startChat() {
    global $connection;
    
    $data = json_decode(file_get_contents('php://input'), true) ?? [];
    $sessionId = 'chat_' . uniqid() . '_' . time();
    $category = htmlspecialchars($data['category'] ?? 'service', ENT_QUOTES);
    $userEmail = htmlspecialchars($data['user_email'] ?? 'guest', ENT_QUOTES);
    
    // 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("Prepare failed: " . $connection->error);
    
    $stmt->bind_param('sss', $sessionId, $category, $userEmail);
    if (!$stmt->execute()) {
        throw new Exception("Insert failed: " . $stmt->error);
    }
    $stmt->close();
    
    // Get welcome message
    $welcome = getWelcomeMessage($category);
    
    // Store welcome message
    $query = "INSERT INTO chat_messages (session_id, sender, message, category, user_identifier, created_at) 
              VALUES (?, ?, ?, ?, ?, NOW())";
    $stmt = $connection->prepare($query);
    if (!$stmt) throw new Exception("Prepare failed: " . $connection->error);
    
    $sender = 'assistant';
    $identifier = 'ai';
    $stmt->bind_param('sssss', $sessionId, $sender, $welcome, $category, $identifier);
    if (!$stmt->execute()) {
        throw new Exception("Insert failed: " . $stmt->error);
    }
    $stmt->close();
    
    http_response_code(200);
    echo json_encode([
        'success' => true,
        'session_id' => $sessionId,
        'category' => $category,
        'welcome_message' => $welcome,
        'timestamp' => date('Y-m-d H:i:s')
    ]);
}

/**
 * Send a message and get AI response
 */
function sendMessage() {
    global $connection;
    
    $data = json_decode(file_get_contents('php://input'), true) ?? [];
    
    $message = htmlspecialchars($data['message'] ?? '', ENT_QUOTES);
    $category = htmlspecialchars($data['category'] ?? 'service', ENT_QUOTES);
    $sessionId = htmlspecialchars($data['session_id'] ?? '', ENT_QUOTES);
    $userEmail = htmlspecialchars($data['user_email'] ?? 'guest', ENT_QUOTES);
    
    if (empty($message)) {
        throw new Exception('Message is required');
    }
    if (strlen($message) > 1000) {
        throw new Exception('Message too long');
    }
    
    // Create session if needed
    if (empty($sessionId)) {
        $sessionId = 'chat_' . uniqid() . '_' . time();
        $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("Prepare failed: " . $connection->error);
        $stmt->bind_param('sss', $sessionId, $category, $userEmail);
        if (!$stmt->execute()) throw new Exception("Insert failed: " . $stmt->error);
        $stmt->close();
    }
    
    // Store user message
    $query = "INSERT INTO chat_messages (session_id, sender, message, category, user_identifier, created_at) 
              VALUES (?, ?, ?, ?, ?, NOW())";
    $stmt = $connection->prepare($query);
    if (!$stmt) throw new Exception("Prepare failed: " . $connection->error);
    $sender = 'user';
    $stmt->bind_param('sssss', $sessionId, $sender, $message, $category, $userEmail);
    if (!$stmt->execute()) throw new Exception("Insert failed: " . $stmt->error);
    $stmt->close();
    
    // Get AI response
    $aiResponse = getAIResponse($message, $category);
    
    // Store AI response
    $query = "INSERT INTO chat_messages (session_id, sender, message, category, user_identifier, created_at) 
              VALUES (?, ?, ?, ?, ?, NOW())";
    $stmt = $connection->prepare($query);
    if (!$stmt) throw new Exception("Prepare failed: " . $connection->error);
    $sender = 'assistant';
    $identifier = 'ai';
    $stmt->bind_param('sssss', $sessionId, $sender, $aiResponse, $category, $identifier);
    if (!$stmt->execute()) throw new Exception("Insert failed: " . $stmt->error);
    $stmt->close();
    
    http_response_code(200);
    echo json_encode([
        'success' => true,
        'session_id' => $sessionId,
        'message' => $message,
        'response' => $aiResponse,
        'category' => $category,
        'timestamp' => date('Y-m-d H:i:s')
    ]);
}

/**
 * Get chat messages
 */
function getMessages() {
    global $connection;
    
    $sessionId = htmlspecialchars($_GET['session_id'] ?? '', ENT_QUOTES);
    if (empty($sessionId)) {
        throw new Exception('Session ID required');
    }
    
    $query = "SELECT id, session_id, sender, message, created_at FROM chat_messages 
              WHERE session_id = ? ORDER BY created_at ASC LIMIT 50";
    $stmt = $connection->prepare($query);
    if (!$stmt) throw new Exception("Prepare failed: " . $connection->error);
    
    $stmt->bind_param('s', $sessionId);
    if (!$stmt->execute()) throw new Exception("Select 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' => $sessionId,
        'messages' => $messages,
        'count' => count($messages)
    ]);
}

/**
 * Get AI response
 */
function getAIResponse($message, $category) {
    $apiKey = getenv('OPENAI_API_KEY');
    
    if (!empty($apiKey)) {
        $response = callOpenAI($message, $category, $apiKey);
        if ($response) return $response;
    }
    
    // Fallback
    return getFallbackResponse($message, $category);
}

/**
 * Call OpenAI API
 */
function callOpenAI($message, $category, $apiKey) {
    $systemPrompt = getCategoryPrompt($category);
    
    $payload = [
        'model' => 'gpt-3.5-turbo',
        'messages' => [
            ['role' => 'system', 'content' => $systemPrompt],
            ['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_POSTFIELDS => json_encode($payload),
        CURLOPT_HTTPHEADER => [
            'Content-Type: application/json',
            'Authorization: Bearer ' . $apiKey
        ],
        CURLOPT_SSL_VERIFYPEER => false
    ]);
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    if ($httpCode === 200) {
        $data = json_decode($response, true);
        return $data['choices'][0]['message']['content'] ?? null;
    }
    
    return null;
}

/**
 * Get fallback response
 */
function getFallbackResponse($message, $category) {
    $responses = [
        'service' => 'Thank you for your interest! Our team specializes in residential and commercial interior design. Feel free to contact us for a consultation.',
        'project' => 'We would love to help with your project! Our experienced designers create custom solutions tailored to your needs.',
        'order' => 'For order inquiries, please contact our sales team and they will be happy to assist you.',
        'contact' => 'Thank you for reaching out to FAREN! You can contact us at +91 (123) 666 000 666 or info@faren.com.'
    ];
    
    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. Be professional and creative.',
        'project' => 'You are a project advisor for FAREN. Help discuss interior design projects and ideas.',
        'order' => 'You are a customer support specialist. Help with orders and shopping inquiries.',
        'contact' => 'You are a customer service representative. Provide helpful information.'
    ];
    
    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?',
        'project' => 'Welcome to FAREN Projects! Let\'s discuss your interior design vision.',
        'order' => 'Welcome to FAREN Shop! How can I assist you?',
        'contact' => 'Welcome to FAREN Support! How can I help?'
    ];
    
    return $messages[$category] ?? $messages['contact'];
}

