<?php
// Clean any previous output
if (ob_get_level()) {
    ob_end_clean();
}

// Include header dependencies without HTML output
include 'includes/header.php';

// Check if live chat is enabled
if (!defined('LIVE_CHAT') || !LIVE_CHAT) {
    http_response_code(403);
    header('Content-Type: application/json');
    echo json_encode(['error' => 'Live chat is disabled']);
    exit;
}

// Set content type to JSON
header('Content-Type: application/json');

// Get current user info
$current_user = [
    'id' => isLoggedIn() ? $_SESSION['user_id'] : 'guest_' . session_id(),
    'name' => isLoggedIn() ? $_SESSION['name'] : 'Guest',
    'avatar' => isLoggedIn() && !empty($_SESSION['avatar']) ? $_SESSION['avatar'] : null,
    'role' => isLoggedIn() ? $_SESSION['role'] : 'guest',
    'is_operator' => isLoggedIn() && (isAdmin() || isStaff())
];

// Create chat storage directory
$chat_dir = __DIR__ . '/data/chat/';
if (!is_dir($chat_dir)) {
    mkdir($chat_dir, 0755, true);
}

$users_file = $chat_dir . 'users.json';
$messages_file = $chat_dir . 'messages.json';

// Helper functions
function readJsonFile($file)
{
    if (!file_exists($file)) {
        return [];
    }
    $content = file_get_contents($file);
    if (empty($content)) {
        return [];
    }
    $decoded = json_decode($content, true);
    if (json_last_error() !== JSON_ERROR_NONE) {
        error_log("JSON decode error in $file: " . json_last_error_msg());
        return [];
    }
    return is_array($decoded) ? $decoded : [];
}

function writeJsonFile($file, $data)
{
    return file_put_contents($file, json_encode($data, JSON_PRETTY_PRINT));
}

function cleanOldData()
{
    global $users_file, $messages_file;
    $now = time();

    try {
        // Clean old users (inactive for more than 1 minute)
        $users = readJsonFile($users_file);
        if (is_array($users)) {
            foreach ($users as $userId => $user) {
                if (is_array($user) && isset($user['lastSeen']) && ($now - $user['lastSeen']) > 60) {
                    unset($users[$userId]);
                }
            }
            writeJsonFile($users_file, $users);
        }

        // Clean old messages (older than 24 hours)
        $messages = readJsonFile($messages_file);
        if (is_array($messages)) {
            $messages = array_filter($messages, function ($msg) use ($now) {
                return is_array($msg) && isset($msg['timestamp']) && ($now - ($msg['timestamp'] / 1000)) < 86400;
            });
            writeJsonFile($messages_file, array_values($messages));
        }
    } catch (Exception $e) {
        error_log("Error in cleanOldData: " . $e->getMessage());
    }
}

// Handle different actions
$action = $_POST['action'] ?? $_GET['action'] ?? '';

// Global CSRF Protection for all POST requests
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!isset($_POST['csrf_token']) || !validate_csrf_token($_POST['csrf_token'])) {
        http_response_code(403);
        echo json_encode(['success' => false, 'error' => 'Invalid CSRF token']);
        exit;
    }
}

switch ($action) {
    case 'update_user':
        // Update user activity
        $users = readJsonFile($users_file);
        $users[$current_user['id']] = array_merge($current_user, [
            'lastSeen' => time(),
            'status' => 'online'
        ]);
        writeJsonFile($users_file, $users);

        cleanOldData();



        echo json_encode(['success' => true, 'user' => $users[$current_user['id']]]);
        break;

    case 'get_users':
        try {
            // Get all active users
            cleanOldData();
            $users = readJsonFile($users_file);
            if (!is_array($users)) {
                $users = [];
            }

            // Filter out users inactive for more than 30 seconds
            $now = time();
            $activeUsers = array_filter($users, function ($user) use ($now) {
                return is_array($user) && isset($user['lastSeen']) && ($now - $user['lastSeen']) < 30;
            });



            echo json_encode(array_values($activeUsers));
        } catch (Exception $e) {
            error_log("Error in get_users: " . $e->getMessage());
            echo json_encode([]);
        }
        break;

    case 'send_message':
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            http_response_code(405);
            echo json_encode(['error' => 'Method not allowed']);
            break;
        }

        $message = trim($_POST['message'] ?? '');
        $targetUserId = $_POST['target_user_id'] ?? '';

        if (empty($message)) {
            http_response_code(400);
            echo json_encode(['error' => 'Message cannot be empty']);
            break;
        }

        if (empty($targetUserId)) {
            http_response_code(400);
            echo json_encode(['error' => 'Target user ID required']);
            break;
        }

        // For non-operators, find an available operator
        if (!$current_user['is_operator']) {
            $users = readJsonFile($users_file);
            $operators = array_filter($users, function ($user) {
                $now = time();
                return isset($user['is_operator']) && $user['is_operator'] &&
                    isset($user['lastSeen']) && ($now - $user['lastSeen']) < 30;
            });

            if (empty($operators)) {
                http_response_code(400);
                echo json_encode(['error' => 'No operators available']);
                break;
            }

            $targetUserId = array_keys($operators)[0];
        }

        $newMessage = [
            'id' => uniqid() . '_' . time(),
            'from' => $current_user['id'],
            'to' => $targetUserId,
            'message' => htmlspecialchars($message, ENT_QUOTES, 'UTF-8'),
            'timestamp' => time() * 1000, // JavaScript timestamp format
            'read' => false
        ];

        $messages = readJsonFile($messages_file);
        $messages[] = $newMessage;
        writeJsonFile($messages_file, $messages);

        echo json_encode(['success' => true, 'message' => $newMessage]);
        break;

    case 'get_messages':
        try {
            $messages = readJsonFile($messages_file);
            if (!is_array($messages)) {
                $messages = [];
            }

            $userId = $_GET['user_id'] ?? $current_user['id'];

            // Filter messages for current user
            if ($current_user['is_operator'] && isset($_GET['selected_user'])) {
                $selectedUser = $_GET['selected_user'];
                $relevantMessages = array_filter($messages, function ($msg) use ($current_user, $selectedUser) {
                    return is_array($msg) && isset($msg['from'], $msg['to']) &&
                        (($msg['from'] === $current_user['id'] && $msg['to'] === $selectedUser) ||
                            ($msg['from'] === $selectedUser && $msg['to'] === $current_user['id']));
                });
            } else {
                $relevantMessages = array_filter($messages, function ($msg) use ($current_user) {
                    return is_array($msg) && isset($msg['from'], $msg['to']) &&
                        ($msg['from'] === $current_user['id'] || $msg['to'] === $current_user['id']);
                });
            }

            echo json_encode(array_values($relevantMessages));
        } catch (Exception $e) {
            error_log("Error in get_messages: " . $e->getMessage());
            echo json_encode([]);
        }
        break;

    case 'mark_read':
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            http_response_code(405);
            echo json_encode(['error' => 'Method not allowed']);
            break;
        }

        $fromUserId = $_POST['from_user_id'] ?? '';

        $messages = readJsonFile($messages_file);
        foreach ($messages as &$msg) {
            if ($msg['from'] === $fromUserId && $msg['to'] === $current_user['id']) {
                $msg['read'] = true;
            }
        }
        writeJsonFile($messages_file, $messages);

        echo json_encode(['success' => true]);
        break;

    case 'clear_chat':
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            http_response_code(405);
            echo json_encode(['error' => 'Method not allowed']);
            break;
        }

        $selectedUserId = $_POST['selected_user_id'] ?? '';

        $messages = readJsonFile($messages_file);

        if ($current_user['is_operator'] && !empty($selectedUserId)) {
            // Clear only messages with selected user
            $messages = array_filter($messages, function ($msg) use ($current_user, $selectedUserId) {
                return !(($msg['from'] === $current_user['id'] && $msg['to'] === $selectedUserId) ||
                    ($msg['from'] === $selectedUserId && $msg['to'] === $current_user['id']));
            });
        } else {
            // Clear all user's messages
            $messages = array_filter($messages, function ($msg) use ($current_user) {
                return $msg['from'] !== $current_user['id'] && $msg['to'] !== $current_user['id'];
            });
        }

        writeJsonFile($messages_file, array_values($messages));
        echo json_encode(['success' => true]);
        break;



    default:
        http_response_code(400);
        echo json_encode(['error' => 'Invalid action']);
        break;
}

// End of API
?>