<?php
/**
 * User Live Chat Backend
 */
require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../includes/functions.php';

ob_clean(); // Clear the output buffer to prevent HTML header from being sent
if (!headers_sent()) {
    header('Content-Type: application/json');
}

// Check if user is logged in
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'error' => 'Unauthorized']);
    exit;
}

$userId = $_SESSION['user_id'];
$action = $_POST['action'] ?? '';

try {
    // Initialize or get active chat
    if ($action === 'init') {
        // Check for existing active chat
        $chat = dbFetch("SELECT id FROM support_chats WHERE user_id = ? AND status = 'active'", [$userId]);
        
        if (!$chat) {
            // Create new chat
            $chatId = dbInsert('support_chats', [
                'user_id' => $userId,
                'status' => 'active'
            ]);
            $chat = ['id' => $chatId];
        } else {
            // Update timestamp
             dbQuery("UPDATE support_chats SET updated_at = CURRENT_TIMESTAMP WHERE id = ?", [$chat['id']]);
        }
        
        // Get messages
        $messages = dbFetchAll("SELECT * FROM support_chat_messages WHERE chat_id = ? ORDER BY created_at ASC", [$chat['id']]);
        
        echo json_encode([
            'success' => true,
            'chat_id' => $chat['id'],
            'messages' => $messages
        ]);
        exit;
    }
    
    // Send message
    if ($action === 'send_message') {
        $message = trim($_POST['message'] ?? '');
        $chatId = $_POST['chat_id'] ?? 0;
        
        if (!$message || !$chatId) {
            throw new Exception("Message and Chat ID are required");
        }
        
        // Verify chat belongs to user
        $chat = dbFetch("SELECT id FROM support_chats WHERE id = ? AND user_id = ?", [$chatId, $userId]);
        if (!$chat) {
            throw new Exception("Invalid chat session");
        }
        
        // Insert message
        dbInsert('support_chat_messages', [
            'chat_id' => $chatId,
            'user_id' => $userId,
            'sender_type' => 'user',
            'sender_id' => $userId,
            'message' => $message,
            'is_admin' => 0,
            'is_read' => 0
        ]);
        
        // Update chat timestamp
        dbQuery("UPDATE support_chats SET updated_at = CURRENT_TIMESTAMP WHERE id = ?", [$chatId]);
        
        echo json_encode(['success' => true]);
        exit;
    }
    
    // Get new messages
    if ($action === 'get_messages') {
        $chatId = $_POST['chat_id'] ?? 0;
        $lastId = $_POST['last_id'] ?? 0;
        
        if (!$chatId) {
            throw new Exception("Chat ID required");
        }
        
        // Verify chat belongs to user
        $chat = dbFetch("SELECT id FROM support_chats WHERE id = ? AND user_id = ?", [$chatId, $userId]);
        if (!$chat) {
            throw new Exception("Invalid chat session");
        }
        
        $sql = "SELECT * FROM support_chat_messages WHERE chat_id = ? AND id > ? ORDER BY created_at ASC";
        $messages = dbFetchAll($sql, [$chatId, $lastId]);
        
        // Mark admin messages as read
        if (!empty($messages)) {
            dbQuery("UPDATE support_chat_messages SET is_read = 1 WHERE chat_id = ? AND is_admin = 1 AND is_read = 0", [$chatId]);
        }
        
        echo json_encode(['success' => true, 'messages' => $messages]);
        exit;
    }
    
    echo json_encode(['success' => false, 'error' => 'Invalid action']);

} catch (Exception $e) {
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
