<?php
error_reporting(0);
include 'fns/filters/load.php';
include 'fns/license/load.php';
include 'fns/sql/Medoo.php';
use Medoo\Medoo;
$result = array();
$result['success'] = false;
$result['error_message'] = '输入值无效';
$result['error_variables'] = [];
$noerror = true;
$currentTimestamp = time();
$formattedTimestamp = date('Y-m-d H:i:s', $currentTimestamp);
if (!isset($data["purchase_code"]) || empty($data["purchase_code"])) {
    $noerror = false;
    $result['error_message'] = '请输入您的授权码';
} elseif (!isset($data["database_hostname"]) || empty($data["database_hostname"])) {
    $noerror = false;
    $result['error_message'] = '数据库主机名无效';
} elseif (!isset($data["database_name"]) || empty($data["database_name"])) {
    $noerror = false;
    $result['error_message'] = '数据库名称无效';
} elseif (!isset($data["database_username"]) || empty($data["database_username"])) {
    $noerror = false;
    $result['error_message'] = '数据库用户名无效';
} elseif (!isset($data["email_address"]) || empty($data["email_address"])) {
    $noerror = false;
    $result['error_message'] = 'Email地址无效';
} elseif (!filter_var($data["email_address"], FILTER_VALIDATE_EMAIL)) {
    $noerror = false;
    $result['error_message'] = 'Email地址无效';
} elseif (!isset($data["username"]) || empty($data["username"])) {
    $noerror = false;
    $result['error_message'] = '请输入超管用户名';
} elseif (!isset($data["password"]) || empty($data["password"])) {
    $noerror = false;
    $result['error_message'] = '请输入超管密码';
}
if (!isset($data["database_password"])) {
    $data["database_password"] = '';
}

if (isset($data["database_type"]) && $data["database_type"] === 'mariadb') {
    $data["database_type"] = 'mariadb';
} else {
    $data["database_type"] = 'mysql';
}

if (!isset($data["database_port"]) || empty($data["database_port"])) {
    $data["database_port"] = '3306';
}

if ($noerror) {
    $data['purchase_code'] = trim($data['purchase_code']);
	$purchase_code = $data['purchase_code'];
	$licenseAPI = new License();
    $licenseCode = $purchase_code; 
    $clientName = 'MeiChatProUser';
    if (empty($licenseCode) || empty($clientName)) {
        $noerror = false;
        $result['error_message'] = "请输入授权码和客户名称。";
    }
}

if ($noerror) {
	if (!empty($data["database_password"])) {
		$pass_pattern = '/^[a-zA-Z0-9@#$%&*!]+$/';
		if (!preg_match($pass_pattern, $data["database_password"])) {
			$noerror = false;
            $result['error_message'] = "数据库密码仅可包含以下字符：字母数字字符及特殊字符 @, #, $, %, &, *, !";
        }
    }

    if (!empty($data["database_name"])) {
        $db_name_pattern = '/^[a-zA-Z0-9_]+$/';
        if (!preg_match($db_name_pattern, $data["database_name"])) {
            $noerror = false;
            $result['error_message'] = "数据库名称仅可包含字母数字字符和下划线";
        }
    }
            
    if (!empty($data["database_username"])) {
        $db_name_pattern = '/^[a-zA-Z0-9_]+$/';
        if (!preg_match($db_name_pattern, $data["database_username"])) {
            $noerror = false;
            $result['error_message'] = "数据库用户名仅可包含字母数字字符和下划线";
        }
    }
}
if ($noerror) {
    $activationResult = $licenseAPI->activate_license($licenseCode, $clientName);
	if (!$activationResult['status']) {
        $noerror = false;
        $result['error_message'] = '授权码无效！请登录【美粉儿社区】获取！';
    } 
}
if ($noerror) {
    $array = json_decode("{".$activationResult['data']."}", true);
    if($array['license_type'] != 'free_license'){
        $noerror = false;
        $result['error_message'] = '非专业版授权码！请登录【美粉儿社区】获取！';
    }
}
if ($noerror) {
    $response = "{'purchase_code':'".$licenseCode."',";
    $response .= "'pro_license':true,";
    $response .= "'license':'".$clientName."','sold_at':'".date('Y.m.d')."','supported_until':'".date('Y-m-d', strtotime($array['support_expiry']))."','buyer':'".$clientName."'}";
    $response = str_replace("'", "\"", $response);
    $license_info_file = 'assets/cache/license_record.cache';
    file_put_contents($license_info_file, $response);
    
}
if ($noerror) {
    $configFile = 'include/config.php';
    $currentConfig = file_get_contents($configFile);
    $newLine = "\n\$config->pro_version = 'pro';\n";
    $pattern = '/(\$db_error_mode\s*=\s*PDO::ERRMODE_SILENT\s*;)/';
    if (preg_match($pattern, $currentConfig, $matches, PREG_OFFSET_CAPTURE)) {
        $position = $matches[0][1];
        $newConfig = substr_replace($currentConfig, $newLine, $position, 0);
        file_put_contents($configFile, $newConfig);
    }
}
if ($noerror) {
    try {
        $db_instance = new Medoo([
            'type' => $data["database_type"],
            'host' => $data["database_hostname"],
            'database' => $data["database_name"],
            'username' => $data["database_username"],
            'password' => $data["database_password"],
            'port' => $data["database_port"],
            'error' => PDO::ERRMODE_SILENT,
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_general_ci',
        ]);
    } catch (PDOException $exception) {
        $noerror = false;
        $result['error_message'] = '数据库登录凭据无效';

        if (!empty($exception->getMessage())) {
            $result['error_message'] = $exception->getMessage();
        }
    }
}
if ($noerror) {
    $config_file = 'include/config.php';
    if (is_writable($config_file)) {
        $file_contents = file_get_contents($config_file);
        $file_contents = preg_replace("/'type' => '([^']+(?='))'/", "'type' => '".$data['database_type']."'", $file_contents);
        $file_contents = preg_replace("/'host' => '([^']+(?='))'/", "'host' => '".$data['database_hostname']."'", $file_contents);
        $file_contents = preg_replace("/'database' => '([^']+(?='))'/", "'database' => '".$data['database_name']."'", $file_contents);
        $file_contents = preg_replace("/'username' => '([^']+(?='))'/", "'username' => '".$data['database_username']."'", $file_contents);
        $file_contents = preg_replace("/'password' => '([^']+(?='))'/", "'password' => '".$data['database_password']."'", $file_contents);
        $file_contents = preg_replace("/'port' => '([^']+(?='))'/", "'port' => '".$data['database_port']."'", $file_contents);
		$protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' ? 'https' : 'http';
		$host = $_SERVER['HTTP_HOST'];
		$newDomain = $protocol . '://' . $host . '/'; 
		$file_contents = str_replace('"http://localhost/MeiChat/"', '"'.$newDomain.'"', $file_contents);
		file_put_contents($config_file, $file_contents);
    } else {
        $noerror = false;
        $result['error_message'] = '权限不足：无法向 include/config.php 文件写入内容';
    }
}
if ($noerror) {
    $import_sql = file_get_contents('layouts/installer/installer.sql');

    try {
        $db_instance->query($import_sql);
    } catch (PDOException $exception) {
        $noerror = false;
        $result['error_message'] = '数据库文件导入失败！';
    }
}
if ($noerror) {
    $data["username"] = sanitize_username($data["username"]);

    if (empty($data["username"])) {
        $data["username"] = 'admin';
    }

    try {
        $db_instance = new Medoo([
            'type' => $data["database_type"],
            'host' => $data["database_hostname"],
            'database' => $data["database_name"],
            'username' => $data["database_username"],
            'password' => $data["database_password"],
            'port' => $data["database_port"],
            'error' => PDO::ERRMODE_SILENT,
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_general_ci',
        ]);

        $update_data = array();
        $update_data["email_address"] = $data['email_address'];
        $update_data["username"] = $data['username'];
        $update_data["password"] = password_hash($data['password'], PASSWORD_BCRYPT);
        $update_data["encrypt_type"] = 'php_password_hash';
        $update_data["salt"] = '';

        $update_data["created_on"] = $formattedTimestamp;
        $update_data["updated_on"] = $formattedTimestamp;

        $db_instance->update("gr_site_users", $update_data, ["OR" => ["username" => "admin", "user_id" => 1]]);
    } catch (PDOException $exception) {
        $data["username"] = 'admin';
        $data["password"] = 'pass';
    }

    $api_secret_key = random_string('15');
    $db_instance->update("gr_settings", ['value' => $api_secret_key], ["setting" => "api_secret_key"]);


    $cs_where = ['string_constant[~]' => 'custom_page_%'];
    $cs_columns = ['string_id', 'string_constant'];
    $custom_page_contents = $db_instance->select("gr_language_strings", $cs_columns, $cs_where);
    $string_ids = array();
    $string_value = '[您可以修改该页面的内容在 模块 功能部分]';

    foreach ($custom_page_contents as $custom_page_content) {
        $string_constant = $custom_page_content['string_constant'];
        if (strpos($string_constant, '_content') !== false) {
            $string_ids[] = $custom_page_content['string_id'];
        }
    }
    if (!empty($string_ids)) {
        $db_instance->update("gr_language_strings", ['string_value' => $string_value], ["string_id" => $string_ids]);
    }

    if (file_exists('layouts/installer/cache_rebuild.php')) {
        include 'layouts/installer/cache_rebuild.php';
    }

    if (file_exists('pages/installer.php')) {
        $rename_to = 'pages/installer_'.strtolower(random_string('10')).'.php';
        rename('pages/installer.php', $rename_to);
    }

    if (file_exists('htaccess.backup')) {
        unlink('htaccess.backup');
    }

    if (file_exists('assets/cache/ws_transmit_code.cache')) {
        unlink('assets/cache/ws_transmit_code.cache');
    }

    if (file_exists('assets/cache/total_cloud_storage_size.cache')) {
        unlink('assets/cache/total_cloud_storage_size.cache');
    }

    $robotsTxtContent = "User-agent: *\n";
    $robotsTxtContent .= "Disallow: \n";
    $robotsTxtContent .= "Disallow: /cgi-bin/\n";
    $robotsTxtContent .= "Disallow: /*?*login_session_id=\n";
    $robotsTxtContent .= "Disallow: /*?*session_time_stamp=\n";
    $robotsTxtContent .= "Disallow: /*?*access_code=\n";
    $robotsTxtContent .= "Sitemap: " . Registry::load('config')->site_url . "sitemap/";

    $robotsTxtFilePath = 'robots.txt';
    file_put_contents($robotsTxtFilePath, $robotsTxtContent);

    $result = array();
    $result['success'] = true;
    $result['alert_message'] = "安装成功 . \n\n登录信息如下:\n";
    $result['alert_message'] .= "超管账号 : ".$data["username"]."\n";
    $result['alert_message'] .= "超管密码 : ".strip_tags($data["password"])."\n";
}
$result = json_encode($result);
echo $result;