<?php
// 1. Nạp tệp cấu hình hệ thống
$config = require_once __DIR__ . '/config.php';

// Bung các biến cấu hình ra môi trường ngoài để dashboard.php đọc trực tiếp
$log_file   = $config['log_file'];
$gateway_ip = $config['gateway_ip'];
$db_file    = $config['db_file'];

// 🔄 TỰ ĐỘNG PARSE DANH SÁCH SERVER TỪ FILE UPSTREAM CONFIG
$server_list = [];
$upstream_file = $config['upstream_file'] ?? '/etc/nginx/conf.d/upstream_map.conf';
if (file_exists($upstream_file)) {
    $upstream_content = file_get_contents($upstream_file);
    preg_match_all('/upstream\s+([^\s{]+)\s*{\s*server\s+([^;]+);/s', $upstream_content, $upstream_matches, PREG_SET_ORDER);
    foreach ($upstream_matches as $item) {
        $server_list[$item[1]] = trim($item[2]);
    }
}

// 2. Tự động nạp (Autoload) các Module chức năng
require_once __DIR__ . '/src/Helpers.php';
require_once __DIR__ . '/src/NginxConfig.php';
require_once __DIR__ . '/src/Actions.php';

// 3. Khởi tạo Action Engine xử lý Request POST (nếu có)
$actionEngine = new SachiAction($config);
$executionResult = $actionEngine->handleRequest();

// 4. Giải nén dữ liệu danh sách domain đồng bộ với tên biến $domains_list của Dashboard
$domains_list = $executionResult['domains']; 
$msg          = $executionResult['msg'];

// 5. Khởi chạy và render giao diện Dashboard điều khiển toàn diện
include_once __DIR__ . '/templates/dashboard.php';