<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

while (ob_get_level()) ob_end_clean();
ob_start();

require_once('ketnoi.php');

function send_json_response($data) {
    while (ob_get_level()) ob_end_clean();
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode($data, JSON_UNESCAPED_UNICODE);
    exit();
}

function create_site_directory($domain_name) {
    $sites_root = $_SERVER['DOCUMENT_ROOT'] . '/sites/';
    if(!file_exists($sites_root)) {
        mkdir($sites_root, 0755, true);
    }
    
    $site_path = $sites_root . $domain_name;
    if(!file_exists($site_path)) {
        mkdir($site_path, 0755, true);
        mkdir($site_path . '/public', 0755, true);
        mkdir($site_path . '/logs', 0755, true);
        mkdir($site_path . '/tmp', 0755, true);
    }
    
    return $site_path;
}

function copy_template_source($template, $site_path, $domain_name) {
    $template_path = $_SERVER['DOCUMENT_ROOT'] . '/templates/' . $template . '/';
    
    if(!file_exists($template_path)) {
        $template_path = $_SERVER['DOCUMENT_ROOT'] . '/templates/default/';
        if(!file_exists($template_path)) {
            create_default_template($template_path);
        }
    }
    
    copy_directory($template_path, $site_path . '/public/');
    create_site_config($site_path, $domain_name);
    return true;
}

function copy_directory($src, $dst) {
    if(!file_exists($dst)) {
        mkdir($dst, 0755, true);
    }
    
    $dir = opendir($src);
    while(false !== ($file = readdir($dir))) {
        if(($file != '.') && ($file != '..')) {
            if(is_dir($src . '/' . $file)) {
                copy_directory($src . '/' . $file, $dst . '/' . $file);
            } else {
                copy($src . '/' . $file, $dst . '/' . $file);
                $content = file_get_contents($dst . '/' . $file);
                $content = str_replace('{{DOMAIN}}', $domain_name, $content);
                $content = str_replace('{{SITE_NAME}}', $domain_name, $content);
                file_put_contents($dst . '/' . $file, $content);
            }
        }
    }
    closedir($dir);
}

function create_default_template($path) {
    mkdir($path, 0755, true);
    $index_content = '<?php $site_name = "{{DOMAIN}}"; ?>
    <!DOCTYPE html>
    <html lang="vi">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Website <?=$site_name?></title>
        <script src="https://cdn.tailwindcss.com"></script>
    </head>
    <body>
        <div class="min-h-screen flex items-center justify-center bg-gradient-to-br from-indigo-100 to-purple-100">
            <div class="bg-white rounded-2xl shadow-2xl p-8 max-w-2xl text-center">
                <h1 class="text-4xl font-bold text-indigo-600 mb-4">🚀 Website Đã Được Tạo!</h1>
                <p class="text-gray-600 text-lg mb-6">Chào mừng bạn đến với <strong><?=$site_name?></strong></p>
                <div class="bg-indigo-50 rounded-xl p-4 text-left">
                    <p class="text-sm text-gray-600">📝 Thông tin:</p>
                    <ul class="text-sm text-gray-600 mt-2 space-y-1">
                        <li>• Domain: <?=$site_name?></li>
                        <li>• Trạng thái: <span class="text-green-500">✅ Hoạt động</span></li>
                    </ul>
                </div>
            </div>
        </div>
    </body>
    </html>';
    file_put_contents($path . 'index.php', $index_content);
}

function create_site_config($site_path, $domain_name) {
    $config_content = '<?php
    define("SITE_NAME", "' . $domain_name . '");
    define("SITE_PATH", "' . $site_path . '/");
    define("SITE_URL", "http://' . $domain_name . '/");
    ?>';
    file_put_contents($site_path . '/config.php', $config_content);
}

try {
    if(!isset($_SESSION['session'])) {
        send_json_response(['status' => 'error', 'message' => 'Vui lòng đăng nhập.']);
    }

    $session = $_SESSION['session'];
    $check_user = $ketnoi->query("SELECT * FROM `users` WHERE `session` = '$session' ")->fetch_array();
    if(empty($check_user['id'])) {
        send_json_response(['status' => 'error', 'message' => 'Không tìm thấy người dùng.']);
    }
    $user = $check_user;

    $name = isset($_POST['name']) ? trim(strtolower($_POST['name'])) : '';
    $purpose = isset($_POST['purpose']) ? trim($_POST['purpose']) : 'website';
    $note = isset($_POST['note']) ? trim($_POST['note']) : '';
    $template = isset($_POST['template']) ? trim($_POST['template']) : 'shop';

    if(empty($name)) {
        send_json_response(['status' => 'error', 'message' => 'Vui lòng nhập tên website.']);
    }

    if(!preg_match('/^[a-z0-9\-]+$/', $name)) {
        send_json_response(['status' => 'error', 'message' => 'Tên chỉ được chứa chữ thường, số và dấu gạch ngang.']);
    }

    $full_domain = $name . '.khanhcoder.site';
    $site_path = create_site_directory($name);
    copy_template_source($template, $site_path, $full_domain);

    $template_names = [
        'shop' => 'Shop Đa Năng',
        'blog' => 'Blog Cá Nhân',
        'landing' => 'Landing Page',
        'portfolio' => 'Portfolio'
    ];
    $template_name = $template_names[$template] ?? 'Mặc Định';

    send_json_response([
        'status' => 'success',
        'domain' => $full_domain,
        'template' => $template_name,
        'site_path' => $site_path,
        'message' => 'Khởi tạo thành công!'
    ]);
} catch (Exception $e) {
    send_json_response([
        'status' => 'error',
        'message' => 'Lỗi hệ thống: ' . $e->getMessage()
    ]);
}
?>