import os
import subprocess
import uuid
import yaml
import paramiko
from flask import Flask, jsonify, request, render_template
from flask_cors import CORS
from flask_jwt_extended import (
    JWTManager, create_access_token,
    jwt_required, get_jwt_identity
)
from passlib.hash import pbkdf2_sha256
from logging.handlers import RotatingFileHandler
import json
from datetime import datetime, timedelta
import random
import logging
import string
import user_agents
import traceback
from werkzeug.exceptions import BadRequest
from jinja2 import Template

SSH_CONFIG = {
    'hostname': '78.46.62.242',
    'port': 22,
    'username': 'root',
    'password': '',  # Ensure this is securely stored and handled
    # 'key_filepath': '/path/to/your/private/key',  # Remove or keep commented out
}

app = Flask(__name__, static_folder='static', template_folder='templates')
CORS(app)

# JWT Configuration
app.config['JWT_SECRET_KEY'] = 'gbauy45bguyab3e4gbaehrbghbg'  # Измените в продакшене
app.config['JWT_ACCESS_TOKEN_EXPIRES'] = timedelta(hours=1)
jwt = JWTManager(app)

OS_OPTIONS = {
    'win2020': 'Windows Server 2020',
    'win2022': 'Windows Server 2022',
    'win2025': 'Windows Server 2025',
    'win10': 'Windows 10',
    'win11': 'Windows 11'
}

IP_POOL_START = [192, 168, 1, 100]  # Starting IP address
current_ip = IP_POOL_START.copy()

CONTAINERS_DIR = os.path.join(os.getcwd(), 'containers')
TEMPLATES_DIR = os.path.join(CONTAINERS_DIR, 'templates')
os.makedirs(TEMPLATES_DIR, exist_ok=True)

# Ensure the Docker Compose template exists
TEMPLATE_PATH = os.path.join(TEMPLATES_DIR, 'docker-compose-template.yml')
if not os.path.exists(TEMPLATE_PATH):
    with open(TEMPLATE_PATH, 'w') as f:
        f.write("""version: '3'
services:
  windows:
    image: dockurr/windows  # Ensure this image exists or adjust to the correct one
    container_name: {{ container_name }}
    environment:
      VERSION: "{{ version }}"
      DISK_SIZE: "{{ disk_size }}"
      RAM_SIZE: "{{ ram_size }}"
      CPU_CORES: "{{ cpu_cores }}"
      USERNAME: "{{ username }}"
      PASSWORD: "{{ password }}"
      KEYBOARD: "{{ keyboard }}"
    devices:
      - /dev/kvm
    cap_add:
      - NET_ADMIN
    ports:
      - "{{ public_port_8006 }}:8006/tcp"
      - "{{ public_port_rdp_tcp }}:3389/tcp"
      - "{{ public_port_rdp_udp }}:3389/udp"
    stop_grace_period: 2m
    restart: unless-stopped
""")

def generate_unique_ip():
    global current_ip
    ip = '.'.join(map(str, current_ip))
    current_ip[3] += 1
    if current_ip[3] > 254:
        current_ip[3] = 1
        current_ip[2] += 1
        if current_ip[2] > 254:
            current_ip[2] = 1
            current_ip[1] += 1
            if current_ip[1] > 254:
                current_ip[1] = 1
                current_ip[0] += 1
                if current_ip[0] > 254:
                    raise Exception("IP Pool Exhausted")
    return ip

@app.route('/')
def home():
    return render_template('index.html')

def setup_logging():
    # Create logs directory if it doesn't exist
    if not os.path.exists('logs'):
        os.makedirs('logs')
    
    # Configure main application logger
    formatter = logging.Formatter(
        '[%(asctime)s] %(levelname)s in %(module)s: %(message)s'
    )
    
    # File handler for general logs
    file_handler = RotatingFileHandler(
        'logs/app.log', 
        maxBytes=1024 * 1024,  # 1MB
        backupCount=10
    )
    file_handler.setFormatter(formatter)
    file_handler.setLevel(logging.INFO)
    
    # File handler for errors
    error_file_handler = RotatingFileHandler(
        'logs/error.log',
        maxBytes=1024 * 1024,  # 1MB
        backupCount=10
    )
    error_file_handler.setFormatter(formatter)
    error_file_handler.setLevel(logging.ERROR)
    
    # Configure Flask logger
    app.logger.addHandler(file_handler)
    app.logger.addHandler(error_file_handler)
    app.logger.setLevel(logging.INFO)
    
    # Log basic request info
    @app.before_request
    def log_request_info():
        app.logger.info(f'Request: {request.method} {request.url} from {request.remote_addr}')
        app.logger.debug(f'Headers: {dict(request.headers)}')
    
    # Error handler
    @app.errorhandler(Exception)
    def handle_exception(e):
        app.logger.error(f'Unhandled Exception: {str(e)}')
        app.logger.error(traceback.format_exc())
        return jsonify({
            'error': 'An internal server error occurred',
            'details': str(e) if app.debug else None
        }), 500

def load_db():
    try:
        if not os.path.exists('db.json'):
            with open('db.json', 'w') as f:
                json.dump({'users': {}, 'server_plans': [], 'logs': []}, f)
        with open('db.json', 'r') as f:
            db = json.load(f)
        return db
    except Exception as e:
        app.logger.error(f'Database load error: {str(e)}')
        app.logger.error(traceback.format_exc())
        raise

def save_db(db):
    with open('db.json', 'w') as f:
        json.dump(db, f, indent=2)

def log_activity(username, action, user_agent_string):
    try:
        db = load_db()
        ua = user_agents.parse(user_agent_string)
        log_entry = {
            'timestamp': datetime.now().isoformat(),
            'username': username,
            'action': action,
            'browser': ua.browser.family,
            'os': ua.os.family,
            'device': ua.device.family,
            'ip': request.remote_addr
        }
        db['logs'].append(log_entry)
        save_db(db)
    except Exception as e:
        app.logger.error(f'Error logging activity: {str(e)}')
        app.logger.error(traceback.format_exc())

def generate_password():
    return ''.join(random.choices(string.ascii_letters + string.digits, k=12))

def execute_ssh_command(command):
    try:
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        
        connect_params = {
            'hostname': SSH_CONFIG['hostname'],
            'port': SSH_CONFIG.get('port', 22),
            'username': SSH_CONFIG['username']
        }
        
        if 'key_filepath' in SSH_CONFIG and SSH_CONFIG['key_filepath']:
            connect_params['key_filename'] = SSH_CONFIG['key_filepath']
        elif 'password' in SSH_CONFIG and SSH_CONFIG['password']:
            connect_params['password'] = SSH_CONFIG['password']
        else:
            raise ValueError("Either 'key_filepath' or 'password' must be provided in SSH_CONFIG.")
        
        ssh.connect(**connect_params)
        
        stdin, stdout, stderr = ssh.exec_command(command)
        stdout_str = stdout.read().decode()
        stderr_str = stderr.read().decode()
        ssh.close()
        return stdout_str, stderr_str
    except Exception as e:
        app.logger.error(f'SSH command execution error: {e}')
        return None, str(e)

def create_docker_compose_content(container_name, version, plan_details, rdp_username, rdp_password, public_port_8006, public_port_rdp_tcp, public_port_rdp_udp):
    return f"""
    version: '3'
    services:
      windows:
        image: dockurr/windows
        container_name: {container_name}
        environment:
          VERSION: "{version}"
          DISK_SIZE: "{plan_details['DISK']}"
          RAM_SIZE: "{plan_details['RAM']}"
          CPU_CORES: "{plan_details['CPU']}"
          USERNAME: "{rdp_username}"
          PASSWORD: "{rdp_password}"
        devices:
          - /dev/kvm
        cap_add:
          - NET_ADMIN
        ports:
          - "{public_port_8006}:8006/tcp"
          - "{public_port_rdp_tcp}:3389/tcp"
          - "{public_port_rdp_udp}:3389/udp"
        stop_grace_period: 2m
        restart: unless-stopped
    """
  
def connect_via_ssh():
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    connect_params = {
        'hostname': SSH_CONFIG['hostname'],
        'port': SSH_CONFIG.get('port', 22),
        'username': SSH_CONFIG['username'],
        'password': SSH_CONFIG['password']
    }
    try:
        ssh.connect(**connect_params)
    except Exception as e:
        app.logger.error(f'SSH connection failed: {e}')
        return None
    return ssh

@app.route('/api/servers', methods=['POST'])
@jwt_required()
def servers():
    current_user = get_jwt_identity()
    db = load_db()

    data = request.get_json()
    if not data or 'plan' not in data or 'os' not in data or 'name' not in data:
        app.logger.error('Invalid request data')
        return jsonify({'error': 'Invalid request data'}), 400

    # Retrieve plan details, ensuring the plan.name is compared correctly
    plan_name = data['plan']['name']
    selected_plan = next((p for p in db['server_plans'] if p['name'] == plan_name), None)
    if not selected_plan:
        app.logger.error('Invalid plan selected')
    return jsonify({'error': 'Invalid plan selected'}), 400

    if user_data['balance'] < selected_plan['price']:
            return jsonify({'error': 'Insufficient funds'}), 400

    if data['os'] not in OS_OPTIONS:
            return jsonify({'error': 'Invalid operating system selected'}), 400

        # Generate unique properties for the new server
    server_ip = generate_unique_ip()
    container_name = f"server_{uuid.uuid4().hex[:8]}"
    rdp_password = generate_password()
    public_port_8006 = random.randint(10000, 60000)
    public_port_rdp_tcp = random.randint(10000, 60000)
    public_port_rdp_udp = public_port_rdp_tcp

    # Generate Docker Compose content
    docker_compose_content = create_docker_compose_content(
        container_name, data['os'], selected_plan,
        data.get('rdp_username', 'admin'), rdp_password,
        public_port_8006, public_port_rdp_tcp, public_port_rdp_udp
    )

    # Create server directory
    server_dir = os.path.join(CONTAINERS_DIR, container_name)
    os.makedirs(server_dir, exist_ok=True)
    docker_compose_path = os.path.join(server_dir, 'docker-compose.yml')
    with open(docker_compose_path, 'w') as f:
            f.write(docker_compose_content)

        # Connect via SSH and deploy the server
        ssh_client = connect_via_ssh()
        if not ssh_client:
            return jsonify({'error': 'Failed to establish SSH connection'}), 500

        try:
            sftp = ssh_client.open_sftp()
            remote_path = f"/root/{container_name}"
            sftp.mkdir(remote_path)
            sftp.put(docker_compose_path, os.path.join(remote_path, 'docker-compose.yml'))
            sftp.close()

            commands = [
                f"cd {remote_path}",
                f"docker-compose up -d"
            ]
            stdout, stderr = execute_ssh_command(' && '.join(commands))
            if stderr:
                app.logger.error(f'Error executing remote commands: {stderr}')
                raise Exception(f'Remote command error: {stderr}')
        except Exception as e:
            app.logger.error(f'Error during SSH operation: {e}')
            return jsonify({'error': f'Failed to deploy server: {str(e)}'}), 500
        finally:
            ssh_client.close()

        # Register the new server
        new_server = {
            'id': len(user_data['servers']) + 1,
            'name': data['name'],
            'plan': selected_plan,
            'os': OS_OPTIONS[data['os']],
            'status': 'active',
            'ip': server_ip,
            'created_at': datetime.now().isoformat(),
            'container_name': container_name,
            'ports': {
                '8006/tcp': public_port_8006,
                '3389/tcp': public_port_rdp_tcp,
                '3389/udp': public_port_rdp_udp
            }
        }

        user_data['balance'] -= selected_plan['price']
        user_data['servers'].append(new_server)
        save_db(db)
        log_activity(current_user, 'create_server', request.headers.get('User-Agent', ''))
        return jsonify(new_server), 201


@app.route('/api/login', methods=['POST'])
def login():
    try:
        app.logger.info('Processing login request')
        db = load_db()
        data = request.get_json()
        
        if not data:
            app.logger.warning('No JSON data in login request')
            return jsonify({'error': 'No JSON data provided'}), 400
        
        username = data.get('username')
        password = data.get('password')
        
        app.logger.info(f'Login attempt for user: {username}')
        
        if not username or not password:
            app.logger.warning('Missing username or password in login request')
            return jsonify({'error': 'Username and password are required'}), 400
        
        user_data = db['users'].get(username)
        if not user_data:
            app.logger.warning(f'Login failed: User {username} not found')
            return jsonify({'error': 'Invalid credentials'}), 401
            
        if pbkdf2_sha256.verify(password, user_data['password']):
            app.logger.info(f'Login successful for user: {username}')
            access_token = create_access_token(identity=username)
            try:
                log_activity(username, 'login', request.headers.get('User-Agent', ''))
            except Exception as e:
                app.logger.error(f'Failed to log login activity: {str(e)}')
                # Continue with login even if logging fails
            return jsonify({
                'token': access_token,
                'username': username,
                'balance': user_data.get('balance', 0)
            })
        
        app.logger.warning(f'Login failed: Invalid password for user {username}')
        return jsonify({'error': 'Invalid credentials'}), 401
        
    except Exception as e:
        app.logger.error(f'Login error: {str(e)}')
        app.logger.error(traceback.format_exc())
        return jsonify({'error': 'An internal server error occurred'}), 500

@app.route('/api/register', methods=['POST'])
def register():
    try:
        app.logger.info('Processing registration request')
        db = load_db()
        data = request.get_json()
        
        if not data:
            app.logger.warning('No JSON data in registration request')
            return jsonify({'error': 'No JSON data provided'}), 400
        
        username = data.get('username')
        password = data.get('password')
        
        app.logger.info(f'Registration attempt for username: {username}')
        
        if not username or not password:
            app.logger.warning('Missing username or password in registration request')
            return jsonify({'error': 'Username and password are required'}), 400
        
        if username in db['users']:
            app.logger.warning(f'Registration failed: Username {username} already exists')
            return jsonify({'error': 'Username already taken'}), 400
        
        hashed_password = pbkdf2_sha256.hash(password)
        
        db['users'][username] = {
            'password': hashed_password,
            'servers': [],
            'balance': 0,
            'tickets': [],
            'created_at': datetime.now().isoformat()
        }
        
        save_db(db)
        app.logger.info(f'Registration successful for user: {username}')
        log_activity(username, 'register', request.headers.get('User-Agent', ''))
        return jsonify({'message': 'Registration successful'}), 201
        
    except Exception as e:
        app.logger.error(f'Registration error: {str(e)}')
        app.logger.error(traceback.format_exc())
        return jsonify({'error': 'An internal server error occurred'}), 500


@app.route('/api/servers/<int:server_id>', methods=['GET'])
@jwt_required()
def get_server(server_id):
    current_user = get_jwt_identity()
    db = load_db()
    user_data = db['users'].get(current_user)

    if not user_data:
        return jsonify({'error': 'User not found'}), 404

    server = next((s for s in user_data['servers'] if s['id'] == server_id), None)
    if not server:
        return jsonify({'error': 'Server not found'}), 404

    return jsonify(server), 200

@app.route('/api/servers/<int:server_id>/toggle', methods=['POST'])
@jwt_required()
def toggle_server(server_id):
    current_user = get_jwt_identity()
    db = load_db()
    user_data = db['users'].get(current_user)

    if not user_data:
        return jsonify({'error': 'User not found'}), 404

    server = next((s for s in user_data['servers'] if s['id'] == server_id), None)
    if not server:
        return jsonify({'error': 'Server not found'}), 404

    container_name = server.get('container_name')
    if not container_name:
        return jsonify({'error': 'Container name not found for this server'}), 400

    # Определение команды для остановки или запуска контейнера
    if server['status'] == 'active':
        cmd = f"cd {os.path.join(CONTAINERS_DIR, container_name)} && docker-compose stop"
    else:
        cmd = f"cd {os.path.join(CONTAINERS_DIR, container_name)} && docker-compose start"
    
    stdout, stderr = execute_ssh_command(cmd)
    if stderr:
        app.logger.error(f'SSH command error: {stderr}')
        return jsonify({'error': f'Failed to toggle server status: {stderr}'}), 500
    
    # Обновление статуса
    server['status'] = 'frozen' if server['status'] == 'active' else 'active'
    save_db(db)
    log_activity(current_user, f'toggle_server_{server_id}', request.headers.get('User-Agent', ''))
    return jsonify({'message': f"Server status changed to {server['status']}"}), 200

@app.route('/api/servers/<int:server_id>', methods=['DELETE'])
@jwt_required()
def delete_server(server_id):
    current_user = get_jwt_identity()
    db = load_db()
    user_data = db['users'].get(current_user)

    if not user_data:
        return jsonify({'error': 'User not found'}), 404

    server = next((s for s in user_data['servers'] if s['id'] == server_id), None)
    if not server:
        return jsonify({'error': 'Server not found'}), 404

    container_name = server.get('container_name')
    if not container_name:
        return jsonify({'error': 'Container name not found for this server'}), 400

    # Команды для остановки и удаления контейнера на удалённом сервере
    commands = [
        f"cd {os.path.join(CONTAINERS_DIR, container_name)} && docker-compose down",
        f"rm -rf {os.path.join(CONTAINERS_DIR, container_name)}"
    ]
    full_command = ' && '.join(commands)
    
    stdout, stderr = execute_ssh_command(full_command)
    if stderr:
        app.logger.error(f'SSH command error: {stderr}')
        return jsonify({'error': f'Failed to delete server: {stderr}'}), 500

    # Удаление локальных архива (если есть)
    zip_filename = f"{container_name}.tar.gz"
    if os.path.exists(zip_filename):
        os.remove(zip_filename)
    
    # Удаление сервера из базы данных
    user_data['servers'].remove(server)
    save_db(db)
    log_activity(current_user, f'delete_server_{server_id}', request.headers.get('User-Agent', ''))
    return jsonify({'message': 'Server deleted successfully'}), 200

@app.route('/api/servers/<int:server_id>', methods=['PUT'])
@jwt_required()
def update_server(server_id):
    current_user = get_jwt_identity()
    db = load_db()
    user_data = db['users'].get(current_user)

    if not user_data:
        return jsonify({'error': 'User not found'}), 404

    server = next((s for s in user_data['servers'] if s['id'] == server_id), None)
    if not server:
        return jsonify({'error': 'Server not found'}), 404

    data = request.get_json()
    if not data:
        return jsonify({'error': 'No data provided'}), 400

    # Example: Allow updating server name and OS
    new_name = data.get('name')
    new_os = data.get('os')

    if new_name:
        server['name'] = new_name

    if new_os:
        if new_os not in OS_OPTIONS:
            return jsonify({'error': 'Invalid operating system selected'}), 400
        # Обновление Docker Compose файла
        container_name = server.get('container_name')
        server_dir = os.path.join(CONTAINERS_DIR, container_name)
        docker_compose_path = os.path.join(server_dir, 'docker-compose.yml')
        
        if not os.path.exists(docker_compose_path):
            return jsonify({'error': 'docker-compose.yml not found for this server'}), 400
        
        # Загрузка текущего docker-compose.yml
        try:
            with open(docker_compose_path, 'r') as f:
                compose_data = yaml.safe_load(f)
        except Exception as e:
            app.logger.error(f'Error reading docker-compose.yml: {e}')
            return jsonify({'error': 'Failed to read docker-compose.yml'}), 500
        
        # Обновление версии ОС
        compose_data['services']['windows']['environment']['VERSION'] = new_os
        compose_data['services']['windows']['os'] = OS_OPTIONS[new_os]
        
        # Запись обновленного docker-compose.yml
        try:
            with open(docker_compose_path, 'w') as f:
                yaml.dump(compose_data, f)
        except Exception as e:
            app.logger.error(f'Error writing docker-compose.yml: {e}')
            return jsonify({'error': 'Failed to update docker-compose.yml'}), 500
        
        # Перезапуск контейнера на удалённом сервере для применения изменений
        cmd = f"cd {server_dir} && docker-compose up -d"
        stdout, stderr = execute_ssh_command(cmd)
        if stderr:
            app.logger.error(f'SSH command error: {stderr}')
            return jsonify({'error': f'Failed to restart server: {stderr}'}), 500

        # Обновление поля ОС в базе данных
        server['os'] = OS_OPTIONS[new_os]

    save_db(db)
    log_activity(current_user, f'update_server_{server_id}', request.headers.get('User-Agent', ''))
    return jsonify({'message': 'Server updated successfully', 'server': server}), 200

@app.route('/api/userinfo', methods=['GET', 'PUT'])
@jwt_required()
def userinfo():
    current_user = get_jwt_identity()
    db = load_db()
    user_data = db['users'].get(current_user)

    if not user_data:
        return jsonify({'error': 'User not found'}), 404

    if request.method == 'GET':
        return jsonify({'username': current_user, 'balance': user_data.get('balance', 0)}), 200
    
    elif request.method == 'PUT':
        data = request.get_json()
        if not data:
            return jsonify({'error': 'No data provided'}), 400
        
        current_password = data.get('current_password')
        new_username = data.get('new_username')
        new_password = data.get('new_password')

        if not current_password:
            return jsonify({'error': 'Current password is required'}), 400

        # Verify current password
        if not pbkdf2_sha256.verify(current_password, user_data['password']):
            return jsonify({'error': 'Current password is incorrect'}), 401

        # Update username if provided
        if new_username:
            if new_username in db['users']:
                return jsonify({'error': 'Username already taken'}), 400
            db['users'][new_username] = db['users'].pop(current_user)
            current_user = new_username

        # Update password if provided
        if new_password:
            db['users'][current_user]['password'] = pbkdf2_sha256.hash(new_password)

        save_db(db)
        log_activity(current_user, 'update_userinfo', request.headers.get('User-Agent', ''))
        return jsonify({'message': 'User information updated successfully', 'username': current_user}), 200

@app.route('/api/tickets', methods=['GET', 'POST'])
@jwt_required()
def tickets():
    current_user = get_jwt_identity()
    db = load_db()
    
    if request.method == 'GET':
        user_data = db['users'].get(current_user)
        if not user_data:
            return jsonify({'error': 'User not found'}), 404
            
        return jsonify(user_data.get('tickets', []))
    
    elif request.method == 'POST':
        data = request.get_json()
        if not data or 'title' not in data or 'description' not in data:
            return jsonify({'error': 'Invalid request data'}), 400
            
        user_data = db['users'].get(current_user)
        if not user_data:
            return jsonify({'error': 'User not found'}), 404
            
        new_ticket = {
            'id': len(user_data['tickets']) + 1,
            'title': data['title'],
            'description': data.get('description', ''),
            'status': 'open',
            'created_at': datetime.now().isoformat(),
            'messages': []
        }
        
        user_data['tickets'].append(new_ticket)
        save_db(db)
        log_activity(current_user, 'create_ticket', request.headers.get('User-Agent', ''))
        return jsonify(new_ticket), 201

@app.route('/api/tickets/<int:ticket_id>', methods=['GET'])
@jwt_required()
def get_ticket(ticket_id):
    current_user = get_jwt_identity()
    db = load_db()
    user_data = db['users'].get(current_user)

    if not user_data:
        return jsonify({'error': 'User not found'}), 404

    ticket = next((t for t in user_data['tickets'] if t['id'] == ticket_id), None)
    if not ticket:
        return jsonify({'error': 'Ticket not found'}), 404

    return jsonify(ticket), 200

@app.route('/api/tickets/<int:ticket_id>/reply', methods=['POST'])
@jwt_required()
def reply_ticket(ticket_id):
    current_user = get_jwt_identity()
    db = load_db()
    
    user_data = db['users'].get(current_user)
    if not user_data:
        return jsonify({'error': 'User not found'}), 404
        
    ticket = next((t for t in user_data['tickets'] if t['id'] == ticket_id), None)
    if not ticket:
        return jsonify({'error': 'Ticket not found'}), 404
        
    data = request.get_json()
    if not data or 'message' not in data:
        return jsonify({'error': 'Message is required'}), 400
        
    message = {
        'content': data['message'],
        'sender': current_user,
        'timestamp': datetime.now().isoformat()
    }
    
    ticket['messages'].append(message)
    save_db(db)
    log_activity(current_user, f'reply_ticket_{ticket_id}', request.headers.get('User-Agent', ''))
    return jsonify(message), 201

if __name__ == '__main__':
    setup_logging()
    app.run(debug=True)



// Глобальные переменные
let currentUser = null;
const API_URL = '/api';

// Утилиты
const showElement = (id) => document.getElementById(id).classList.remove('hidden');
const hideElement = (id) => document.getElementById(id).classList.add('hidden');
const setActiveTab = (tabId) => {
    document.querySelectorAll('.tab-content').forEach(tab => tab.classList.add('hidden'));
    document.querySelectorAll('.tab-btn').forEach(btn => btn.classList.remove('active'));
    document.getElementById(tabId).classList.remove('hidden');
    document.querySelector(`[data-tab="${tabId}"]`).classList.add('active');
};

// Helper function to get auth headers
const getAuthHeaders = () => {
    const token = localStorage.getItem('authToken');
    return {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
    };
};

// Function to show notifications
function showNotification(message, type = 'error') {
    const container = document.getElementById('notification-container');
    const notification = document.createElement('div');
    notification.className = `notification ${type}`;
    notification.innerHTML = `
        <span>${message}</span>
        <button class="close-notification">&times;</button>
    `;
    container.appendChild(notification);

    // Show the notification
    setTimeout(() => {
        notification.classList.add('show');
    }, 100);

    // Remove the notification after 5 seconds
    setTimeout(() => {
        notification.classList.remove('show');
        setTimeout(() => {
            notification.remove();
        }, 500);
    }, 5000);

    // Close button functionality
    notification.querySelector('.close-notification').addEventListener('click', () => {
        notification.classList.remove('show');
        setTimeout(() => {
            notification.remove();
        }, 500);
    });
}

// Function to logout
function logout() {
    localStorage.removeItem('authToken');
    localStorage.removeItem('username');
    localStorage.removeItem('balance');
    currentUser = null;
    updateUserInterface();
    location.reload(); // Reload the page after logout
}

// Обработчик регистрации
document.getElementById('register').addEventListener('submit', async (e) => {
    e.preventDefault();
    const username = document.getElementById('reg-username').value;
    const password = document.getElementById('reg-password').value;

    if (!username || !password) {
        showNotification('Пожалуйста, заполните все поля', 'error');
        return;
    }

    try {
        const response = await fetch(`${API_URL}/register`, {
            method: 'POST',
            headers: { 
                'Content-Type': 'application/json',
                'Accept': 'application/json'
            },
            body: JSON.stringify({ username, password })
        });

        const data = await response.json();

        if (response.ok) {
            showNotification('Регистрация успешна! Теперь вы можете войти.', 'success');
            showElement('login-form');
            hideElement('register-form');
        } else {
            showNotification(data.error || 'Ошибка регистрации', 'error');
        }
    } catch (error) {
        console.error('Ошибка регистрации:', error);
        showNotification('Ошибка при регистрации', 'error');
    }
});

// Обработчик входа
document.getElementById('login').addEventListener('submit', async (e) => {
    e.preventDefault();
    const username = document.getElementById('login-username').value;
    const password = document.getElementById('login-password').value;

    if (!username || !password) {
        showNotification('Пожалуйста, заполните все поля', 'error');
        return;
    }

    try {
        const response = await fetch(`${API_URL}/login`, {
            method: 'POST',
            headers: { 
                'Content-Type': 'application/json',
                'Accept': 'application/json',
                'X-Requested-With': 'XMLHttpRequest' // Add this header
            },
            credentials: 'same-origin', // Add credentials
            body: JSON.stringify({ username, password })
        });

        if (!response.ok) {
            const data = await response.json();
            throw new Error(data.error || `HTTP error! status: ${response.status}`);
        }

        const data = await response.json();

        if (data.token) {
            // Store the token and user data in localStorage
            localStorage.setItem('authToken', data.token);
            localStorage.setItem('username', data.username);
            localStorage.setItem('balance', data.balance); // Assuming balance is a number
            currentUser = {
                username: data.username,
                balance: data.balance
            };
            updateUserInterface();
            setActiveTab('servers');
            showNotification('Вход выполнен успешно!', 'success');
        } else {
            showNotification('Неверные учетные данные', 'error');
        }
    } catch (error) {
        console.error('Ошибка входа:', error);
        showNotification(`Ошибка при входе в систему: ${error.message}`, 'error');
    }
});

// Add a function to check if user is authenticated
function isAuthenticated() {
    return localStorage.getItem('authToken') !== null;
}

// Управление серверами
async function loadServers() {
    try {
        const response = await fetch(`${API_URL}/servers`, {
            method: 'GET',
            headers: getAuthHeaders()
        });

        if (!response.ok) {
            const errorData = await response.json();
            throw new Error(errorData.error || `HTTP error! status: ${response.status}`);
        }

        const servers = await response.json();
        displayServers(servers);
    } catch (error) {
        console.error('Ошибка загрузки серверов:', error);
        showNotification(error.message, 'error');
    }
}

function displayServers(servers) {
    const serversList = document.getElementById('servers-list');
    serversList.innerHTML = '';

    if (servers.length === 0) {
        serversList.innerHTML = '<p>У вас нет серверов.</p>';
        return;
    }

    servers.forEach(server => {
        const serverCard = document.createElement('div');
        serverCard.className = 'server-card';
        serverCard.innerHTML = `
            <h3>${server.name}</h3>
            <span class="server-status status-${server.status}">${server.status}</span>
            <p><strong>IP:</strong> ${server.ip}</p>
            <p>План: ${server.plan.name}</p>
            <p>CPU: ${server.plan.cpu} / RAM: ${server.plan.ram}GB</p>
            <button class="btn primary view-server" data-server-id="${server.id}">Просмотреть</button>
        `;
        serversList.appendChild(serverCard);
    });

    // Attach event listeners to view server buttons
    document.querySelectorAll('.view-server').forEach(button => {
        button.addEventListener('click', () => {
            const serverId = button.getAttribute('data-server-id');
            openServerDetailsModal(serverId);
        });
    });
}

// Function to toggle server status
async function toggleServer(serverId, currentStatus) {
    try {
        const newStatus = currentStatus === 'active' ? 'stop' : 'start';
        const response = await fetch(`${API_URL}/servers/${serverId}/toggle`, {
            method: 'POST',
            headers: getAuthHeaders()
        });

        if (!response.ok) {
            const errorData = await response.json();
            throw new Error(errorData.error || `HTTP error! status: ${response.status}`);
        }

        await loadServers();
        showNotification(`Сервер ${newStatus === 'start' ? 'запущен' : 'остановлен'} успешно!`, 'success');
    } catch (error) {
        console.error('Ошибка при переключении сервера:', error);
        showNotification(error.message, 'error');
    }
}

// Function to delete a server
async function deleteServer(serverId) {
    if (!confirm('Вы уверены, что хотите удалить этот сервер?')) return;

    try {
        const response = await fetch(`${API_URL}/servers/${serverId}`, {
            method: 'DELETE',
            headers: getAuthHeaders()
        });

        if (!response.ok) {
            const errorData = await response.json();
            throw new Error(errorData.error || `HTTP error! status: ${response.status}`);
        }

        await loadServers();
        showNotification('Сервер успешно удален!', 'success');
    } catch (error) {
        console.error('Ошибка при удалении сервера:', error);
        showNotification(error.message, 'error');
    }
}

// Обработчик отправки тикетов
document.getElementById('ticket-form').addEventListener('submit', async (e) => {
    e.preventDefault();
    const title = document.getElementById('ticket-title').value;
    const description = document.getElementById('ticket-description').value;

    if (!title || !description) {
        showNotification('Пожалуйста, заполните все поля', 'error');
        return;
    }

    try {
        const response = await fetch(`${API_URL}/tickets`, {
            method: 'POST',
            headers: getAuthHeaders(),
            body: JSON.stringify({
                title,
                description
            })
        });

        if (!response.ok) {
            const data = await response.json();
            throw new Error(data.error || 'Ошибка при создании тикета');
        }

        showNotification('Тикет успешно создан!', 'success');
        document.getElementById('ticket-form').reset();
        loadTickets();
    } catch (error) {
        console.error('Ошибка создания тикета:', error);
        showNotification(error.message, 'error');
    }
});

// Function to load all tickets
async function loadTickets() {
    try {
        const response = await fetch(`${API_URL}/tickets`, {
            method: 'GET',
            headers: getAuthHeaders()
        });

        if (!response.ok) {
            const errorData = await response.json();
            throw new Error(errorData.error || `HTTP error! status: ${response.status}`);
        }

        const tickets = await response.json();
        displayTickets(tickets);
    } catch (error) {
        console.error('Ошибка загрузки тикетов:', error);
        showNotification(error.message, 'error');
    }
}

// Function to display all tickets
function displayTickets(tickets) {
    const ticketsList = document.getElementById('tickets-list');
    ticketsList.innerHTML = '';

    if (tickets.length === 0) {
        ticketsList.innerHTML = '<p>У вас нет тикетов.</p>';
        return;
    }

    tickets.forEach(ticket => {
        const ticketCard = document.createElement('div');
        ticketCard.className = 'ticket-card';
        ticketCard.innerHTML = `
            <div class="ticket-header">
                <h3>${ticket.title}</h3>
                <span class="ticket-status status-${ticket.status}">${ticket.status}</span>
            </div>
            <p>${ticket.description}</p>
            <small>Создан: ${new Date(ticket.created_at).toLocaleString()}</small>
            <button class="btn primary view-ticket" data-ticket-id="${ticket.id}">Просмотреть</button>
        `;
        ticketsList.appendChild(ticketCard);
    });

    // Attach event listeners to view buttons
    document.querySelectorAll('.view-ticket').forEach(button => {
        button.addEventListener('click', () => {
            const ticketId = button.getAttribute('data-ticket-id');
            openTicketModal(ticketId);
        });
    });
}

// Function to open ticket modal and load ticket details
async function openTicketModal(ticketId) {
    try {
        const response = await fetch(`${API_URL}/tickets/${ticketId}`, {
            method: 'GET',
            headers: getAuthHeaders()
        });

        if (!response.ok) {
            const errorData = await response.json();
            throw new Error(errorData.error || `HTTP error! status: ${response.status}`);
        }

        const ticket = await response.json();
        displayTicketDetails(ticket);
    } catch (error) {
        console.error('Ошибка загрузки тикета:', error);
        showNotification(error.message, 'error');
    }
}

// Function to display ticket details in modal
function displayTicketDetails(ticket) {
    // Populate modal fields
    document.getElementById('modal-ticket-title').textContent = ticket.title;
    document.getElementById('modal-ticket-description').textContent = ticket.description;

    const messagesContainer = document.getElementById('modal-ticket-messages');
    messagesContainer.innerHTML = '';

    if (ticket.messages.length === 0) {
        messagesContainer.innerHTML = '<p>Нет сообщений.</p>';
    } else {
        ticket.messages.forEach(msg => {
            const msgDiv = document.createElement('div');
            msgDiv.className = 'ticket-message';
            msgDiv.innerHTML = `
                <p><span class="sender">${msg.sender}</span> <span class="timestamp">${new Date(msg.timestamp).toLocaleString()}</span></p>
                <p>${msg.content}</p>
            `;
            messagesContainer.appendChild(msgDiv);
        });
    }

    // Show modal
    showElement('ticket-modal');
}

// Обработчик ответа на тикет
document.getElementById('reply-form').addEventListener('submit', async (e) => {
    e.preventDefault();
    const message = document.getElementById('reply-message').value.trim();
    const ticketId = document.querySelector('.view-ticket').getAttribute('data-ticket-id'); // Adjust as needed

    if (!message) {
        showNotification('Пожалуйста, введите сообщение', 'error');
        return;
    }

    try {
        const response = await fetch(`${API_URL}/tickets/${ticketId}/reply`, {
            method: 'POST',
            headers: getAuthHeaders(),
            body: JSON.stringify({ message })
        });

        if (!response.ok) {
            const data = await response.json();
            throw new Error(data.error || 'Ошибка при отправке ответа');
        }

        // Reload ticket details
        openTicketModal(ticketId);
        showNotification('Ответ отправлен успешно!', 'success');
    } catch (error) {
        console.error('Ошибка отправки ответа:', error);
        showNotification(error.message, 'error');
    }
});

// Close ticket modal
document.getElementById('close-ticket-modal').addEventListener('click', () => {
    hideElement('ticket-modal');
    document.getElementById('reply-form').reset();
});

// Settings Modal Functionality
document.getElementById('settings-btn').addEventListener('click', () => {
    showElement('settings-modal');
});

document.getElementById('close-settings-modal').addEventListener('click', () => {
    hideElement('settings-modal');
    document.getElementById('settings-form').reset();
});

// Обработчик настроек
document.getElementById('settings-form').addEventListener('submit', async (e) => {
    e.preventDefault();
    const newUsername = document.getElementById('new-username').value.trim();
    const currentPassword = document.getElementById('current-password').value;
    const newPassword = document.getElementById('new-password').value.trim();

    if (!currentPassword) {
        showNotification('Текущий пароль обязателен', 'error');
        return;
    }

    if (!newUsername && !newPassword) {
        showNotification('Пожалуйста, введите новое имя пользователя или пароль', 'error');
        return;
    }

    const payload = {
        current_password: currentPassword
    };

    if (newUsername) payload.new_username = newUsername;
    if (newPassword) payload.new_password = newPassword;

    try {
        const response = await fetch(`${API_URL}/userinfo`, {
            method: 'PUT',
            headers: getAuthHeaders(),
            body: JSON.stringify(payload)
        });

        if (!response.ok) {
            const data = await response.json();
            throw new Error(data.error || `HTTP error! status: ${response.status}`);
        }

        const data = await response.json();

        // Update local storage and UI
        if (data.username) {
            localStorage.setItem('username', data.username);
            currentUser.username = data.username;
            document.getElementById('username').textContent = `Пользователь: ${currentUser.username}`;
        }

        if (data.balance !== undefined) {
            localStorage.setItem('balance', data.balance);
            currentUser.balance = data.balance;
            document.getElementById('balance').textContent = `Баланс: ${currentUser.balance} ₽`;
        }

        hideElement('settings-modal');
        document.getElementById('settings-form').reset();
        showNotification('Настройки успешно обновлены!', 'success');
    } catch (error) {
        console.error('Ошибка обновления настроек:', error);
        showNotification(error.message, 'error');
    }
});

// Function to open Buy Server Modal
document.querySelectorAll('.buy-server').forEach(btn => {
    btn.addEventListener('click', () => {
        showElement('buy-server-modal');
    });
});

// Handle Buy Server Form Submission
document.getElementById('buy-server-form').addEventListener('submit', async (e) => {
    e.preventDefault();
    const serverName = document.getElementById('server-name').value.trim();
    const serverOS = document.getElementById('server-os').value;

    if (!serverName || !serverOS) {
        showNotification('Пожалуйста, заполните все поля', 'error');
        return;
    }

    const plan = document.querySelector('.buy-server.active')?.dataset.plan || 'basic';
    const planConfigs = {
        basic: { name: 'Базовый', cpu: 2, ram: 4, price: 500 },
        advanced: { name: 'Продвинутый', cpu: 4, ram: 8, price: 1000 },
        premium: { name: 'Премиум', cpu: 8, ram: 16, price: 2000 }
    };

    try {
        const response = await fetch(`${API_URL}/servers`, {
            method: 'POST',
            headers: getAuthHeaders(),
            body: JSON.stringify({
                name: serverName,
                plan: planConfigs[plan],
                os: serverOS
            })
        });

        if (!response.ok) {
            const errorData = await response.json();
            throw new Error(errorData.error || 'Ошибка при создании сервера');
        }

        const newServer = await response.json();
        showNotification('Сервер успешно создан!', 'success');
        hideElement('buy-server-modal');
        document.getElementById('buy-server-form').reset();
        loadServers();

        // Update the user balance
        currentUser.balance -= planConfigs[plan].price;
        localStorage.setItem('balance', currentUser.balance); // Update localStorage
        document.getElementById('balance').textContent = `Баланс: ${currentUser.balance} ₽`;
    } catch (error) {
        console.error('Ошибка покупки сервера:', error);
        showNotification(error.message, 'error');
    }
});

// Function to open Server Details Modal
async function openServerDetailsModal(serverId) {
    try {
        const response = await fetch(`${API_URL}/servers/${serverId}`, {
            method: 'GET',
            headers: getAuthHeaders()
        });

        if (!response.ok) {
            const errorData = await response.json();
            throw new Error(errorData.error || `HTTP error! status: ${response.status}`);
        }

        const server = await response.json();
        displayServerDetails(server);
    } catch (error) {
        console.error('Ошибка загрузки сервера:', error);
        showNotification(error.message, 'error');
    }
}

// Function to display server details in modal
function displayServerDetails(server) {
    // Populate modal fields
    document.getElementById('modal-server-name').textContent = server.name;
    document.getElementById('modal-server-ip').textContent = server.ip;
    document.getElementById('modal-server-plan').textContent = server.plan.name;
    document.getElementById('modal-server-os').textContent = server.os;
    document.getElementById('modal-server-status').textContent = server.status;

    const passwordElement = document.getElementById('modal-server-password');
    passwordElement.textContent = server.password;
    passwordElement.classList.add('hidden-password');

    const togglePasswordBtn = document.getElementById('toggle-password-btn');
    togglePasswordBtn.textContent = 'Показать пароль';

    togglePasswordBtn.onclick = () => {
        if (passwordElement.classList.contains('hidden-password')) {
            passwordElement.classList.remove('hidden-password');
            togglePasswordBtn.textContent = 'Скрыть пароль';
        } else {
            passwordElement.classList.add('hidden-password');
            togglePasswordBtn.textContent = 'Показать пароль';
        }
    };

    // Show modal
    showElement('server-details-modal');
}

// Close Server Details Modal
document.getElementById('close-server-details-modal').addEventListener('click', () => {
    hideElement('server-details-modal');
});

// updateUserInterface function
function updateUserInterface() {
    const authContainer = document.getElementById('auth-container');
    const mainContent = document.getElementById('main-content');
    const usernameElement = document.getElementById('username');
    const balanceElement = document.getElementById('balance');

    if (isAuthenticated()) {
        if (!currentUser) {
            const username = localStorage.getItem('username');
            const balance = parseFloat(localStorage.getItem('balance'));

            if (username && !isNaN(balance)) {
                currentUser = {
                    username: username,
                    balance: balance
                };
            } else {
                // Optionally, fetch user info from backend (recommended)
                const token = localStorage.getItem('authToken');
                fetch(`${API_URL}/userinfo`, {
                    method: 'GET',
                    headers: getAuthHeaders()
                })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('Failed to fetch user info');
                    }
                    return response.json();
                })
                .then(data => {
                    currentUser = {
                        username: data.username,
                        balance: data.balance
                    };
                    // Optionally, store these details in localStorage
                    localStorage.setItem('username', data.username);
                    localStorage.setItem('balance', data.balance);
                    // Update UI
                    authContainer?.classList.add('hidden');
                    mainContent?.classList.remove('hidden');
                    if (usernameElement) usernameElement.textContent = `Пользователь: ${currentUser.username}`;
                    if (balanceElement) balanceElement.textContent = `Баланс: ${currentUser.balance} ₽`;
                    // Load user data
                    loadServers();
                    loadTickets();
                })
                .catch(error => {
                    console.error('Failed to fetch user info:', error);
                    logout(); // Optionally, log out the user if fetching fails
                });
            }
        } else {
            authContainer?.classList.add('hidden');
            mainContent?.classList.remove('hidden');

            // Update user information in the header
            if (usernameElement) usernameElement.textContent = `Пользователь: ${currentUser.username}`;
            if (balanceElement) balanceElement.textContent = `Баланс: ${currentUser.balance} ₽`;

            // Load user data
            loadServers();
            loadTickets();
        }
    } else {
        // Show auth container and hide main content
        authContainer?.classList.remove('hidden');
        mainContent?.classList.add('hidden');
    }
}

// Обработчики переключения форм
document.getElementById('show-register').addEventListener('click', (e) => {
    e.preventDefault();
    hideElement('login-form');
    showElement('register-form');
});

document.getElementById('show-login').addEventListener('click', (e) => {
    e.preventDefault();
    hideElement('register-form');
    showElement('login-form');
});

// Обработчики вкладок
document.querySelectorAll('.tab-btn').forEach(btn => {
    btn.addEventListener('click', () => setActiveTab(btn.dataset.tab));
});

// Покупка сервера (Open Buy Server Modal)
document.querySelectorAll('.buy-server').forEach(btn => {
    btn.addEventListener('click', () => {
        showElement('buy-server-modal');
    });
});

// Handle Buy Server Form Submission
document.getElementById('buy-server-form').addEventListener('submit', async (e) => {
    e.preventDefault();
    const serverName = document.getElementById('server-name').value.trim();
    const serverOS = document.getElementById('server-os').value;

    if (!serverName || !serverOS) {
        showNotification('Пожалуйста, заполните все поля', 'error');
        return;
    }

    // Determine which plan is selected based on active tab or button data
    const activePlanBtn = document.querySelector('.buy-server.active');
    const plan = activePlanBtn ? activePlanBtn.dataset.plan : 'basic';
    const planConfigs = {
        basic: { name: 'Базовый', cpu: 2, ram: 4, price: 500 },
        advanced: { name: 'Продвинутый', cpu: 4, ram: 8, price: 1000 },
        premium: { name: 'Премиум', cpu: 8, ram: 16, price: 2000 }
    };

    try {
        const response = await fetch(`${API_URL}/servers`, {
            method: 'POST',
            headers: getAuthHeaders(),
            body: JSON.stringify({
                name: serverName,
                plan: planConfigs[plan],
                os: serverOS
            })
        });

        if (!response.ok) {
            const errorData = await response.json();
            throw new Error(errorData.error || 'Ошибка при создании сервера');
        }

        const newServer = await response.json();
        showNotification('Сервер успешно создан!', 'success');
        hideElement('buy-server-modal');
        document.getElementById('buy-server-form').reset();
        loadServers();

        // Update the user balance
        currentUser.balance -= planConfigs[plan].price;
        localStorage.setItem('balance', currentUser.balance); // Update localStorage
        document.getElementById('balance').textContent = `Баланс: ${currentUser.balance} ₽`;
    } catch (error) {
        console.error('Ошибка покупки сервера:', error);
        showNotification(error.message, 'error');
    }
});

// Function to open Server Details Modal
async function openServerDetailsModal(serverId) {
    try {
        const response = await fetch(`${API_URL}/servers/${serverId}`, {
            method: 'GET',
            headers: getAuthHeaders()
        });

        if (!response.ok) {
            const errorData = await response.json();
            throw new Error(errorData.error || `HTTP error! status: ${response.status}`);
        }

        const server = await response.json();
        displayServerDetails(server);
    } catch (error) {
        console.error('Ошибка загрузки сервера:', error);
        showNotification(error.message, 'error');
    }
}

// Function to display server details in modal
function displayServerDetails(server) {
    // Populate modal fields
    document.getElementById('modal-server-name').textContent = server.name;
    document.getElementById('modal-server-ip').textContent = server.ip;
    document.getElementById('modal-server-plan').textContent = server.plan.name;
    document.getElementById('modal-server-os').textContent = server.os;
    document.getElementById('modal-server-status').textContent = server.status;

    const passwordElement = document.getElementById('modal-server-password');
    passwordElement.textContent = server.password;
    passwordElement.classList.add('hidden-password');

    const togglePasswordBtn = document.getElementById('toggle-password-btn');
    togglePasswordBtn.textContent = 'Показать пароль';

    togglePasswordBtn.onclick = () => {
        if (passwordElement.classList.contains('hidden-password')) {
            passwordElement.classList.remove('hidden-password');
            togglePasswordBtn.textContent = 'Скрыть пароль';
        } else {
            passwordElement.classList.add('hidden-password');
            togglePasswordBtn.textContent = 'Показать пароль';
        }
    };

    // Show modal
    showElement('server-details-modal');
}

// Close Server Details Modal
document.getElementById('close-server-details-modal').addEventListener('click', () => {
    hideElement('server-details-modal');
});

// Инициализация при загрузке страницы
document.addEventListener('DOMContentLoaded', function() {
    const logoutBtn = document.getElementById('logout-btn');
    if (logoutBtn) {
        logoutBtn.addEventListener('click', logout);
    }

    updateUserInterface();
});



{
  "users": {
    "test": {
      "password": "test",
      "servers": [
        {
          "id": 1,
          "name": "Server-1730443463374",
          "plan": {
            "name": "\u041f\u0440\u043e\u0434\u0432\u0438\u043d\u0443\u0442\u044b\u0439",
            "cpu": 4,
            "ram": 8,
            "price": 1000
          },
          "status": "active",
          "password": "SVBes7qlNc40",
          "created_at": "2024-11-01T13:44:23.380705",
          "auto_renewal": true
        }
      ],
      "balance": 34765734657833657,
      "tickets": [
        {
          "id": 1,
          "title": "test",
          "description": "test",
          "status": "open",
          "created_at": "2024-11-01T13:34:30.026514"
        }
      ],
      "logs": [],
      "created_at": "2024-11-01T13:23:04.989224"
    },
    "test47": {
      "password": "$pbkdf2-sha256$29000$wHgvxRhDSIkRQsjZu9caIw$cMYTrGY5hm.RKAilJmMHgEwZA3WjuDeGoBjwGDsfryY",
      "servers": [],
      "balance": 0,
      "tickets": [],
      "created_at": "2024-11-01T14:16:46.398342"
    },
    "root": {
      "password": "$pbkdf2-sha256$29000$CyHkvFcKgZAyZoxRqvVeSw$Ia2SkYeNPfIR7t.hSL6Iddbpjce6xhXlRSN1BQ6ORFStE",
      "servers": [],
      "created_at": "2024-11-01T20:48:24.685767"
    },
    "sdfgsdfgsdf": {
      "password": "$pbkdf2-sha256$29000$7X1PKYVwzplTak3pXUuJcQ$t9lQHDe4it6i90B.g/o33Pq1I9C172El0xQIgoJRCig",
      "servers": [],
      "balance": 0,
      "tickets": [],
      "created_at": "2024-11-01T20:54:43.226355"
    },
    "test4453": {
      "password": "$pbkdf2-sha256$29000$DqH0nhPiPKe09t6bs5YSYg$oUtN3nRJKAo3y6taOgvk9JsJbilW/5JzWe/7ZyFoyhM",
      "servers": [
        {
          "id": 1,
          "name": "Server-1730470683877",
          "plan": {
            "name": "\u041f\u0440\u043e\u0434\u0432\u0438\u043d\u0443\u0442\u044b\u0439",
            "cpu": 4,
            "ram": 8,
            "price": 1000
          },
          "os": "Windows Server 2022",
          "status": "active",
          "password": "Ry6G7xdxEdgJ",
          "created_at": "2024-11-01T21:18:04.038807",
          "auto_renewal": true
        },
        {
          "id": 2,
          "name": "Server-1730470708511",
          "plan": {
            "name": "\u041f\u0440\u043e\u0434\u0432\u0438\u043d\u0443\u0442\u044b\u0439",
            "cpu": 4,
            "ram": 8,
            "price": 1000
          },
          "os": "Windows Server 2022",
          "status": "active",
          "password": "wRLWLik4YbCQ",
          "created_at": "2024-11-01T21:18:28.675348",
          "auto_renewal": true
        }
      ],
      "balance": 6995000,
      "tickets": [
        {
          "id": 1,
          "title": "test supp",
          "description": "test oke da da",
          "status": "open",
          "created_at": "2024-11-01T14:45:03.348993",
          "messages": [
            {
              "content": "lol test",
              "sender": "nigger",
              "timestamp": "2024-11-01T21:13:22.314963"
            },
            {
              "content": "bro wtfsdsd",
              "sender": "nigger",
              "timestamp": "2024-11-01T21:13:32.032827"
            },
            {
              "content": "xd xd test test",
              "sender": "nigger",
              "timestamp": "2024-11-01T21:14:30.812600"
            }
          ]
        }
      ],
      "created_at": "2024-11-01T14:32:36.132607"
    }
  },
  "server_plans": [
    {
      "name": "\u041f\u043b\u0430\u043d 1",
      "specs": "1 vCPU, 2 GB RAM",
      "price": 10
    },
    {
      "name": "\u041f\u043b\u0430\u043d 2",
      "specs": "2 vCPU, 4 GB RAM",
      "price": 20
    }
  ],
  "logs": [
    {
      "timestamp": "2024-11-01T14:32:36.142610",
      "username": "test4453",
      "action": "register",
      "browser": "Chrome",
      "os": "Windows",
      "device": "Other",
      "ip": "127.0.0.1"
    },
    {
      "timestamp": "2024-11-01T14:32:40.835576",
      "username": "test4453",
      "action": "login",
      "browser": "Chrome",
      "os": "Windows",
      "device": "Other",
      "ip": "127.0.0.1"
    },
    {
      "timestamp": "2024-11-01T14:33:31.349385",
      "username": "test4453",
      "action": "login",
      "browser": "Chrome",
      "os": "Windows",
      "device": "Other",
      "ip": "127.0.0.1"
    },
    {
      "timestamp": "2024-11-01T14:39:23.799863",
      "username": "test4453",
      "action": "login",
      "browser": "Chrome",
      "os": "Windows",
      "device": "Other",
      "ip": "127.0.0.1"
    },
    {
      "timestamp": "2024-11-01T14:44:47.422889",
      "username": "test4453",
      "action": "login",
      "browser": "Chrome",
      "os": "Windows",
      "device": "Other",
      "ip": "127.0.0.1"
    },
    {
      "timestamp": "2024-11-01T14:45:03.356971",
      "username": "test4453",
      "action": "create_ticket",
      "browser": "Chrome",
      "os": "Windows",
      "device": "Other",
      "ip": "127.0.0.1"
    },
    {
      "timestamp": "2024-11-01T20:48:19.544146",
      "username": "test4453",
      "action": "login",
      "browser": "Chrome",
      "os": "Windows",
      "device": "Other",
      "ip": "127.0.0.1"
    },
    {
      "timestamp": "2024-11-01T20:48:24.695532",
      "username": "root",
      "action": "register",
      "browser": "Chrome",
      "os": "Windows",
      "device": "Other",
      "ip": "127.0.0.1"
    },
    {
      "timestamp": "2024-11-01T20:48:37.954109",
      "username": "root",
      "action": "login",
      "browser": "Chrome",
      "os": "Windows",
      "device": "Other",
      "ip": "127.0.0.1"
    },
    {
      "timestamp": "2024-11-01T20:48:48.717128",
      "username": "root",
      "action": "create_ticket",
      "browser": "Chrome",
      "os": "Windows",
      "device": "Other",
      "ip": "127.0.0.1"
    },
    {
      "timestamp": "2024-11-01T20:49:47.317213",
      "username": "root",
      "action": "create_server",
      "browser": "Chrome",
      "os": "Windows",
      "device": "Other",
      "ip": "127.0.0.1"
    },
    {
      "timestamp": "2024-11-01T20:50:03.664990",
      "username": "root",
      "action": "create_server",
      "browser": "Chrome",
      "os": "Windows",
      "device": "Other",
      "ip": "127.0.0.1"
    },
    {
      "timestamp": "2024-11-01T20:50:06.326324",
      "username": "root",
      "action": "create_server",
      "browser": "Chrome",
      "os": "Windows",
      "device": "Other",
      "ip": "127.0.0.1"
    },
    {
      "timestamp": "2024-11-01T20:50:08.417534",
      "username": "root",
      "action": "create_server",
      "browser": "Chrome",
      "os": "Windows",
      "device": "Other",
      "ip": "127.0.0.1"
    },
    {
      "timestamp": "2024-11-01T20:50:10.569951",
      "username": "root",
      "action": "create_server",
      "browser": "Chrome",
      "os": "Windows",
      "device": "Other",
      "ip": "127.0.0.1"
    },
    {
      "timestamp": "2024-11-01T20:50:10.740979",
      "username": "root",
      "action": "create_server",
      "browser": "Chrome",
      "os": "Windows",
      "device": "Other",
      "ip": "127.0.0.1"
    },
    {
      "timestamp": "2024-11-01T20:50:14.040738",
      "username": "root",
      "action": "create_server",
      "browser": "Chrome",
      "os": "Windows",
      "device": "Other",
      "ip": "127.0.0.1"
    },
    {
      "timestamp": "2024-11-01T20:50:14.349935",
      "username": "root",
      "action": "create_server",
      "browser": "Chrome",
      "os": "Windows",
      "device": "Other",
      "ip": "127.0.0.1"
    },
    {
      "timestamp": "2024-11-01T20:50:18.862408",
      "username": "root",
      "action": "create_server",
      "browser": "Chrome",
      "os": "Windows",
      "device": "Other",
      "ip": "127.0.0.1"
    },
    {
      "timestamp": "2024-11-01T20:50:31.491974",
      "username": "root",
      "action": "create_server",
      "browser": "Chrome",
      "os": "Windows",
      "device": "Other",
      "ip": "127.0.0.1"
    },
    {
      "timestamp": "2024-11-01T20:51:01.499242",
      "username": "root",
      "action": "login",
      "browser": "Chrome",
      "os": "Windows",
      "device": "Other",
      "ip": "127.0.0.1"
    },
    {
      "timestamp": "2024-11-01T20:51:13.442373",
      "username": "root",
      "action": "create_server",
      "browser": "Chrome",
      "os": "Windows",
      "device": "Other",
      "ip": "127.0.0.1"
    },
    {
      "timestamp": "2024-11-01T20:52:19.305104",
      "username": "root",
      "action": "create_server",
      "browser": "Chrome",
      "os": "Windows",
      "device": "Other",
      "ip": "127.0.0.1"
    },
    {
      "timestamp": "2024-11-01T20:52:21.009966",
      "username": "root",
      "action": "create_server",
      "browser": "Chrome",
      "os": "Windows",
      "device": "Other",
      "ip": "127.0.0.1"
    },
    {
      "timestamp": "2024-11-01T20:52:22.741393",
      "username": "root",
      "action": "create_server",
      "browser": "Chrome",
      "os": "Windows",
      "device": "Other",
      "ip": "127.0.0.1"
    },
    {
      "timestamp": "2024-11-01T20:52:24.553724",
      "username": "root",
      "action": "create_server",
      "browser": "Chrome",
      "os": "Windows",
      "device": "Other",
      "ip": "127.0.0.1"
    },
    {
      "timestamp": "2024-11-01T20:52:27.102851",
      "username": "root",
      "action": "create_server",
      "browser": "Chrome",
      "os": "Windows",
      "device": "Other",
      "ip": "127.0.0.1"
    },
    {
      "timestamp": "2024-11-01T20:52:28.822780",
      "username": "root",
      "action": "create_server",
      "browser": "Chrome",
      "os": "Windows",
      "device": "Other",
      "ip": "127.0.0.1"
    },
    {
      "timestamp": "2024-11-01T20:52:30.550532",
      "username": "root",
      "action": "create_server",
      "browser": "Chrome",
      "os": "Windows",
      "device": "Other",
      "ip": "127.0.0.1"
    },
    {
      "timestamp": "2024-11-01T20:52:33.369865",
      "username": "root",
      "action": "create_server",
      "browser": "Chrome",
      "os": "Windows",
      "device": "Other",
      "ip": "127.0.0.1"
    },
    {
      "timestamp": "2024-11-01T20:52:35.224460",
      "username": "root",
      "action": "create_server",
      "browser": "Chrome",
      "os": "Windows",
      "device": "Other",
      "ip": "127.0.0.1"
    },
    {
      "timestamp": "2024-11-01T20:53:15.296781",
      "username": "root",
      "action": "login",
      "browser": "Chrome",
      "os": "Windows",
      "device": "Other",
      "ip": "127.0.0.1"
    },
    {
      "timestamp": "2024-11-01T20:53:20.213626",
      "username": "root",
      "action": "create_server",
      "browser": "Chrome",
      "os": "Windows",
      "device": "Other",
      "ip": "127.0.0.1"
    },
    {
      "timestamp": "2024-11-01T20:53:22.211460",
      "username": "root",
      "action": "create_server",
      "browser": "Chrome",
      "os": "Windows",
      "device": "Other",
      "ip": "127.0.0.1"
    },
    {
      "timestamp": "2024-11-01T20:53:23.906212",
      "username": "root",
      "action": "create_server",
      "browser": "Chrome",
      "os": "Windows",
      "device": "Other",
      "ip": "127.0.0.1"
    },
    {
      "timestamp": "2024-11-01T20:53:25.607781",
      "username": "root",
      "action": "create_server",
      "browser": "Chrome",
      "os": "Windows",
      "device": "Other",
      "ip": "127.0.0.1"
    },
    {
      "timestamp": "2024-11-01T20:53:27.145068",
      "username": "root",
      "action": "create_server",
      "browser": "Chrome",
      "os": "Windows",
      "device": "Other",
      "ip": "127.0.0.1"
    },
    {
      "timestamp": "2024-11-01T20:53:29.887940",
      "username": "test4453",
      "action": "login",
      "browser": "Chrome",
      "os": "Windows",
      "device": "Other",
      "ip": "127.0.0.1"
    },
    {
      "timestamp": "2024-11-01T20:53:30.075342",
      "username": "root",
      "action": "create_server",
      "browser": "Chrome",
      "os": "Windows",
      "device": "Other",
      "ip": "127.0.0.1"
    },
    {
      "timestamp": "2024-11-01T20:53:32.157342",
      "username": "root",
      "action": "create_server",
      "browser": "Chrome",
      "os": "Windows",
      "device": "Other",
      "ip": "127.0.0.1"
    },
    {
      "timestamp": "2024-11-01T20:53:45.955139",
      "username": "root",
      "action": "create_server",
      "browser": "Chrome",
      "os": "Windows",
      "device": "Other",
      "ip": "127.0.0.1"
    },
    {
      "timestamp": "2024-11-01T20:53:48.143456",
      "username": "root",
      "action": "create_server",
      "browser": "Chrome",
      "os": "Windows",
      "device": "Other",
      "ip": "127.0.0.1"
    },
    {
      "timestamp": "2024-11-01T20:53:50.033988",
      "username": "root",
      "action": "create_server",
      "browser": "Chrome",
      "os": "Windows",
      "device": "Other",
      "ip": "127.0.0.1"
    },
    {
      "timestamp": "2024-11-01T20:53:51.823643",
      "username": "root",
      "action": "create_server",
      "browser": "Chrome",
      "os": "Windows",
      "device": "Other",
      "ip": "127.0.0.1"
    },
    {
      "timestamp": "2024-11-01T20:53:54.171391",
      "username": "root",
      "action": "create_server",
      "browser": "Chrome",
      "os": "Windows",
      "device": "Other",
      "ip": "127.0.0.1"
    },
    {
      "timestamp": "2024-11-01T20:54:43.240790",
      "username": "sdfgsdfgsdf",
      "action": "register",
      "browser": "Chrome",
      "os": "Windows",
      "device": "Other",
      "ip": "127.0.0.1"
    },
    {
      "timestamp": "2024-11-01T20:54:47.064831",
      "username": "sdfgsdfgsdf",
      "action": "login",
      "browser": "Chrome",
      "os": "Windows",
      "device": "Other",
      "ip": "127.0.0.1"
    },
    {
      "timestamp": "2024-11-01T20:54:47.462689",
      "username": "sdfgsdfgsdf",
      "action": "login",
      "browser": "Chrome",
      "os": "Windows",
      "device": "Other",
      "ip": "127.0.0.1"
    },
    {
      "timestamp": "2024-11-01T20:55:31.311108",
      "username": "test4453",
      "action": "login",
      "browser": "Chrome",
      "os": "Windows",
      "device": "Other",
      "ip": "127.0.0.1"
    },
    {
      "timestamp": "2024-11-01T21:11:32.257462",
      "username": "test4453",
      "action": "login",
      "browser": "Chrome",
      "os": "Windows",
      "device": "Other",
      "ip": "127.0.0.1"
    },
    {
      "timestamp": "2024-11-01T21:12:11.641341",
      "username": "nigger",
      "action": "update_userinfo",
      "browser": "Chrome",
      "os": "Windows",
      "device": "Other",
      "ip": "127.0.0.1"
    },
    {
      "timestamp": "2024-11-01T21:12:28.946506",
      "username": "nigger",
      "action": "login",
      "browser": "Chrome",
      "os": "Windows",
      "device": "Other",
      "ip": "127.0.0.1"
    },
    {
      "timestamp": "2024-11-01T21:13:22.325933",
      "username": "nigger",
      "action": "reply_ticket_1",
      "browser": "Chrome",
      "os": "Windows",
      "device": "Other",
      "ip": "127.0.0.1"
    },
    {
      "timestamp": "2024-11-01T21:13:32.046816",
      "username": "nigger",
      "action": "reply_ticket_1",
      "browser": "Chrome",
      "os": "Windows",
      "device": "Other",
      "ip": "127.0.0.1"
    },
    {
      "timestamp": "2024-11-01T21:14:05.433402",
      "username": "nigger",
      "action": "login",
      "browser": "Chrome",
      "os": "Windows",
      "device": "Other",
      "ip": "127.0.0.1"
    },
    {
      "timestamp": "2024-11-01T21:14:30.822573",
      "username": "nigger",
      "action": "reply_ticket_1",
      "browser": "Chrome",
      "os": "Windows",
      "device": "Other",
      "ip": "127.0.0.1"
    },
    {
      "timestamp": "2024-11-01T21:16:18.926730",
      "username": "test4453",
      "action": "login",
      "browser": "Chrome",
      "os": "Windows",
      "device": "Other",
      "ip": "127.0.0.1"
    },
    {
      "timestamp": "2024-11-01T21:16:24.937540",
      "username": "test4453",
      "action": "create_server",
      "browser": "Chrome",
      "os": "Windows",
      "device": "Other",
      "ip": "127.0.0.1"
    },
    {
      "timestamp": "2024-11-01T21:16:27.749704",
      "username": "test4453",
      "action": "toggle_server_1",
      "browser": "Chrome",
      "os": "Windows",
      "device": "Other",
      "ip": "127.0.0.1"
    },
    {
      "timestamp": "2024-11-01T21:16:29.867492",
      "username": "test4453",
      "action": "delete_server_1",
      "browser": "Chrome",
      "os": "Windows",
      "device": "Other",
      "ip": "127.0.0.1"
    },
    {
      "timestamp": "2024-11-01T21:16:41.232193",
      "username": "test4453",
      "action": "create_server",
      "browser": "Chrome",
      "os": "Windows",
      "device": "Other",
      "ip": "127.0.0.1"
    },
    {
      "timestamp": "2024-11-01T21:16:43.765487",
      "username": "test4453",
      "action": "toggle_server_1",
      "browser": "Chrome",
      "os": "Windows",
      "device": "Other",
      "ip": "127.0.0.1"
    },
    {
      "timestamp": "2024-11-01T21:16:44.328450",
      "username": "test4453",
      "action": "toggle_server_1",
      "browser": "Chrome",
      "os": "Windows",
      "device": "Other",
      "ip": "127.0.0.1"
    },
    {
      "timestamp": "2024-11-01T21:16:44.490759",
      "username": "test4453",
      "action": "toggle_server_1",
      "browser": "Chrome",
      "os": "Windows",
      "device": "Other",
      "ip": "127.0.0.1"
    },
    {
      "timestamp": "2024-11-01T21:16:45.779561",
      "username": "test4453",
      "action": "toggle_server_1",
      "browser": "Chrome",
      "os": "Windows",
      "device": "Other",
      "ip": "127.0.0.1"
    },
    {
      "timestamp": "2024-11-01T21:16:47.292192",
      "username": "test4453",
      "action": "toggle_server_1",
      "browser": "Chrome",
      "os": "Windows",
      "device": "Other",
      "ip": "127.0.0.1"
    },
    {
      "timestamp": "2024-11-01T21:16:48.931452",
      "username": "test4453",
      "action": "toggle_server_1",
      "browser": "Chrome",
      "os": "Windows",
      "device": "Other",
      "ip": "127.0.0.1"
    },
    {
      "timestamp": "2024-11-01T21:17:19.222597",
      "username": "test4453",
      "action": "delete_server_1",
      "browser": "Chrome",
      "os": "Windows",
      "device": "Other",
      "ip": "127.0.0.1"
    },
    {
      "timestamp": "2024-11-01T21:18:04.051771",
      "username": "test4453",
      "action": "create_server",
      "browser": "Chrome",
      "os": "Windows",
      "device": "Other",
      "ip": "127.0.0.1"
    },
    {
      "timestamp": "2024-11-01T21:18:16.806402",
      "username": "test4453",
      "action": "toggle_server_1",
      "browser": "Chrome",
      "os": "Windows",
      "device": "Other",
      "ip": "127.0.0.1"
    },
    {
      "timestamp": "2024-11-01T21:18:21.803735",
      "username": "test4453",
      "action": "toggle_server_1",
      "browser": "Chrome",
      "os": "Windows",
      "device": "Other",
      "ip": "127.0.0.1"
    },
    {
      "timestamp": "2024-11-01T21:18:28.690149",
      "username": "test4453",
      "action": "create_server",
      "browser": "Chrome",
      "os": "Windows",
      "device": "Other",
      "ip": "127.0.0.1"
    },
    {
      "timestamp": "2024-11-01T21:30:35.405035",
      "username": "test4453",
      "action": "login",
      "browser": "Chrome",
      "os": "Windows",
      "device": "Other",
      "ip": "127.0.0.1"
    },
    {
      "timestamp": "2024-11-01T21:31:11.611327",
      "username": "test4453",
      "action": "login",
      "browser": "Chrome",
      "os": "Windows",
      "device": "Other",
      "ip": "127.0.0.1"
    },
    {
      "timestamp": "2024-11-01T22:01:43.631426",
      "username": "test4453",
      "action": "login",
      "browser": "Chrome",
      "os": "Windows",
      "device": "Other",
      "ip": "127.0.0.1"
    },
    {
      "timestamp": "2024-11-01T22:20:11.950689",
      "username": "test4453",
      "action": "login",
      "browser": "Chrome",
      "os": "Windows",
      "device": "Other",
      "ip": "127.0.0.1"
    },
    {
      "timestamp": "2024-11-01T22:45:48.556343",
      "username": "test4453",
      "action": "login",
      "browser": "Chrome",
      "os": "Windows",
      "device": "Other",
      "ip": "127.0.0.1"
    },
    {
      "timestamp": "2024-11-01T22:57:27.285335",
      "username": "test4453",
      "action": "login",
      "browser": "Chrome",
      "os": "Windows",
      "device": "Other",
      "ip": "127.0.0.1"
    },
    {
      "timestamp": "2024-11-01T22:58:00.339594",
      "username": "test4453",
      "action": "login",
      "browser": "Chrome",
      "os": "Windows",
      "device": "Other",
      "ip": "127.0.0.1"
    },
    {
      "timestamp": "2024-11-01T23:07:20.071026",
      "username": "test4453",
      "action": "login",
      "browser": "Chrome",
      "os": "Windows",
      "device": "Other",
      "ip": "127.0.0.1"
    }
  ]
}



POST https://niggers.drugdeal.store/api/servers 400 (Bad Request)
(anonymous) @ script.js:733
script.js:529 
        
        
       POST https://niggers.drugdeal.store/api/servers 400 (Bad Request)
(anonymous) @ script.js:529
script.js:759 Ошибка покупки сервера: Error: Invalid plan selected
    at HTMLFormElement.<anonymous> (script.js:745:19)
(anonymous) @ script.js:759
script.js:555 Ошибка покупки сервера: Error: Invalid plan selected
    at HTMLFormElement.<anonymous> (script.js:541:19)