<?php

function install($site_path = SITE_PATH, $namespace_file_name = NAMESPACE_FILE_NAME)
{
    return runSql('install', $site_path, $namespace_file_name);
}

function update($site_path = SITE_PATH, $namespace_file_name = NAMESPACE_FILE_NAME)
{
    return runSql('update', $site_path, $namespace_file_name);
}

function uninstall($site_path = SITE_PATH, $namespace_file_name = NAMESPACE_FILE_NAME)
{
    return runSql('uninstall', $site_path, $namespace_file_name);
}

/**
 * 处理SQL
 * @param string $sql_type install|update|uninstall
 * @param string $site_path 站点路径
 * @param string $namespace_file_name 命名空间文件名
 * @return bool
 */
function runSql($sql_type = 'install', $site_path = SITE_PATH, $namespace_file_name = NAMESPACE_FILE_NAME)
{
    // 处理框架SQL
    $sql_file = $site_path . "app" . DIRECTORY_SEPARATOR . "common" . DIRECTORY_SEPARATOR . "install" . DIRECTORY_SEPARATOR . $sql_type . ".sql";
    if (file_exists($sql_file)) {
        $sql = trim(file_get_contents($sql_file));
        if (!empty($sql)) {
            $sql = updTablePrefix($sql, SQL_TABLE_PREFIX);
            pdo_run($sql);
        }
    }

    /*// 处理插件SQL
    $addons_path = $site_path . 'addons' . DIRECTORY_SEPARATOR;
    if (file_exists($addons_path)) {
        $files = scandir($addons_path);
        foreach ($files as $file) {
            // 过滤掉 . 和 .. 目录，避免 open_basedir 限制错误
            if ($file == '.' || $file == '..') {
                continue;
            }
            $file_path = $addons_path . $file;
            // 只处理目录，跳过文件
            if (!is_dir($file_path)) {
                continue;
            }
            $sql_file = $file_path . DIRECTORY_SEPARATOR . $sql_type . ".sql";
            if (file_exists($sql_file)) {
                $sql = trim(file_get_contents($sql_file));
                if (!empty($sql)) {
                    $sql = updTablePrefix($sql, SQL_TABLE_PREFIX);
                    pdo_run($sql);
                }
            }
        }
    }

    // 处理单个应用SQL
    $addons_path = $site_path . 'addons' . DIRECTORY_SEPARATOR . $namespace_file_name . DIRECTORY_SEPARATOR;
    if (!empty($namespace_file_name) && file_exists($addons_path)) {
        $files = scandir($addons_path);
        foreach ($files as $file) {
            // 过滤掉 . 和 .. 目录，避免 open_basedir 限制错误
            if ($file == '.' || $file == '..') {
                continue;
            }
            $file_path = $addons_path . $file;
            // 只处理目录，跳过文件
            if (!is_dir($file_path)) {
                continue;
            }
            $sql_file = $file_path . DIRECTORY_SEPARATOR . $sql_type . ".sql";
            if (file_exists($sql_file)) {
                $sql = trim(file_get_contents($sql_file));
                if (!empty($sql)) {
                    $sql = updTablePrefix($sql, SQL_TABLE_PREFIX);
                    pdo_run($sql);
                }
            }
        }
    }*/

    /*    if ($sql_type != 'uninstall') {
            // 处理菜单
            checkModule($site_path, $namespace_file_name);
        }*/

    if ($sql_type == 'install') {
        // 处理安装之后的SQL
        checkInstallAfter($site_path, $namespace_file_name);
    }
    return true;
}

/**
 * 处理安装之后的SQL
 * @param string $site_path 站点路径
 * @param string $namespace_file_name 命名空间文件名
 * @return bool
 */
function checkInstallAfter($site_path = SITE_PATH, $namespace_file_name = NAMESPACE_FILE_NAME)
{
    // 处理安装之后的SQL
    $sql_file = $site_path . 'addons' . DIRECTORY_SEPARATOR . $namespace_file_name . DIRECTORY_SEPARATOR . "index" . DIRECTORY_SEPARATOR . "install_after.sql";
    if (file_exists($sql_file)) {
        $sql = trim(file_get_contents($sql_file));
        if (!empty($sql)) {
            $sql = updTablePrefix($sql, SQL_TABLE_PREFIX);
            pdo_run($sql);
        }
    }
    return true;
}

/**
 * 处理菜单
 * @param string $site_path 站点路径
 * @param string $namespace_file_name 命名空间文件名
 * @return bool
 */
function checkModule($site_path = SITE_PATH, $namespace_file_name = NAMESPACE_FILE_NAME)
{
    // 处理应用菜单
    $sql_file = $site_path . 'addons' . DIRECTORY_SEPARATOR . $namespace_file_name . DIRECTORY_SEPARATOR . "index" . DIRECTORY_SEPARATOR . "solution.sql";
    if (file_exists($sql_file)) {
        $sql = trim(file_get_contents($sql_file));
        if (!empty($sql)) {
            $sql = updTablePrefix($sql, SQL_TABLE_PREFIX);
            pdo_run($sql);
        }
    }
    return true;
}


if (!function_exists('updTablePrefix')) {
    /**
     * 替换表前缀
     * @param string $sql SQL语句
     * @param string $prefix 表前缀
     * @return string 替换后的SQL
     */
    function updTablePrefix($sql, $prefix = '')
    {
        if (empty($sql)) {
            return $sql;
        }

        if (empty($prefix)) {
            // ThinkPHP 6 获取数据库配置
            try {
                $app = \think\facade\App::getInstance();
                $dbConfig = $app->config->get('database');
                $prefix = $dbConfig['connections'][$dbConfig['default']]['prefix'] ?? 'yb_';
            } catch (\Exception $e) {
                // 如果无法获取配置，使用默认前缀
                $prefix = 'yb_';
            }
        }

        // 替换表前缀
        $sql = str_replace(' `YB_TABLE_PREFIX_', ' `' . $prefix, $sql);
        $sql = str_replace(' YB_TABLE_PREFIX_', ' ' . $prefix, $sql);

        return $sql;
    }
}
