<?php
include __DIR__ . '/auth.php';
admin_check();
include __DIR__ . '/layout.php';
include __DIR__ . '/config_writer.php';

$root = realpath(__DIR__ . '/..');
$msg = '';
$error = '';
$report = array();

function initial_setup_path($relative){
    global $root;
    return $root . '/' . trim(str_replace('\\', '/', $relative), '/');
}

function initial_setup_in_root($path){
    global $root;
    $rootNorm = str_replace('\\', '/', realpath($root));
    $real = realpath($path);
    if($real === false){
        $parent = realpath(dirname($path));
        if($parent === false) return false;
        $real = $parent . '/' . basename($path);
    }
    $realNorm = str_replace('\\', '/', $real);
    return $realNorm === $rootNorm || strpos($realNorm, $rootNorm . '/') === 0;
}

function initial_setup_mkdir($dir){
    if(!is_dir($dir)) @mkdir($dir, 0777, true);
}

function initial_setup_copy_recursive($source, $target){
    if(!initial_setup_in_root($source)) return false;
    if(is_file($source)){
        initial_setup_mkdir(dirname($target));
        return @copy($source, $target);
    }
    if(!is_dir($source)) return false;
    initial_setup_mkdir($target);
    foreach(scandir($source) as $item){
        if($item === '.' || $item === '..') continue;
        initial_setup_copy_recursive($source . '/' . $item, $target . '/' . $item);
    }
    return true;
}

function initial_setup_delete_children($dir){
    if(!is_dir($dir) || !initial_setup_in_root($dir)) return 0;
    $count = 0;
    foreach(scandir($dir) as $item){
        if($item === '.' || $item === '..') continue;
        $path = $dir . '/' . $item;
        if(is_dir($path)){
            $count += initial_setup_delete_children($path);
            if(@rmdir($path)) $count++;
        }else{
            if(@unlink($path)) $count++;
        }
    }
    return $count;
}

function initial_setup_write_config($relative, $data, $comment = ''){
    $file = initial_setup_path($relative);
    initial_setup_mkdir(dirname($file));
    $content = "<?php\n";
    if($comment !== '') $content .= '// ' . $comment . "\n";
    $content .= 'return ' . var_export($data, true) . ";\n";
    return file_put_contents($file, $content, LOCK_EX) !== false;
}

function initial_setup_runtime_cache_dirs(){
    return array('cache/static', 'cache/oplog', 'cache/push', 'cache/spider', 'cache/security');
}

function initial_setup_collect_targets($mode){
    $cacheTargets = initial_setup_runtime_cache_dirs();
    $configTargets = array('config/domain.php', 'config/domain_auto.php', 'config/links.php', 'config/push_center.php', 'config/spider_force.php');
    $dataTargets = array('data/sites', 'data/content_center');
    $uploadTargets = array('assets/uploads/content_center');

    if($mode === 'cache_logs') return array('backup'=>$cacheTargets, 'clear_dirs'=>$cacheTargets);
    if($mode === 'business') return array('backup'=>array_merge($configTargets, $dataTargets, $cacheTargets), 'clear_dirs'=>array_merge($dataTargets, $cacheTargets));
    if($mode === 'factory') return array('backup'=>array_merge($configTargets, $dataTargets, $uploadTargets, $cacheTargets), 'clear_dirs'=>array_merge($dataTargets, $uploadTargets, $cacheTargets));
    return array('backup'=>array(), 'clear_dirs'=>array());
}

function initial_setup_backup($targets){
    $stamp = date('YmdHis');
    $backupRoot = initial_setup_path('cache/backup/initial_setup/' . $stamp);
    initial_setup_mkdir($backupRoot);
    foreach($targets as $relative){
        $source = initial_setup_path($relative);
        if(!file_exists($source)) continue;
        initial_setup_copy_recursive($source, $backupRoot . '/' . trim(str_replace('\\', '/', $relative), '/'));
    }
    return $backupRoot;
}

function initial_setup_reset_configs(){
    $ok = true;
    $ok = initial_setup_write_config('config/domain.php', array(), '站群正式域名配置，已由初始设置清空。') && $ok;
    $ok = initial_setup_write_config('config/domain_auto.php', array(), '系统自动生成：未在 config/domain.php 配置的访问域名会自动分配主题和资料。') && $ok;
    $ok = initial_setup_write_config('config/links.php', array(
        'settings' => array('enabled'=>1,'home_count'=>15,'inner_min_count'=>1,'inner_max_count'=>1,'new_window'=>1,'nofollow'=>0,'auto_domain_links'=>1),
        'items' => array(),
    ), '客户端本地友情链接配置。') && $ok;
    $ok = initial_setup_write_config('config/push_center.php', array(
        'realtime_enabled' => false,
        'baidu' => array('enabled'=>false,'domains'=>array()),
        'bing' => array('enabled'=>false,'api_key'=>''),
    )) && $ok;
    $ok = initial_setup_write_config('config/spider_force.php', array(
        'enabled'=>0,
        'pass_weight'=>0,
        'status'=>302,
        'probability'=>0,
        'terminal'=>'all',
        'spider_all'=>0,
        'spiders'=>array(),
        'dedupe'=>0,
        'start_time'=>'',
        'end_time'=>'',
        'target_links'=>array(),
        'rules'=>array(),
    )) && $ok;
    return $ok;
}

function initial_setup_dirs_stat($dirs){
    $count = 0;
    $size = 0;
    foreach($dirs as $relative){
        $dir = initial_setup_path($relative);
        if(!is_dir($dir)) continue;
        $it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS));
        foreach($it as $file){
            if($file->isFile()){
                $count++;
                $size += $file->getSize();
            }
        }
    }
    return array($count, $size);
}

$modes = array(
    'cache_logs' => array(
        'title' => '清理缓存和日志',
        'desc' => '清空静态缓存、蜘蛛记录、推送记录、操作日志和安全缓存；不改站点配置、内容和授权状态。',
        'level' => 'safe',
    ),
    'business' => array(
        'title' => '清空业务配置',
        'desc' => '清空站群域名、自动分配记录、友情链接、推送配置、强引配置、内容中心和站点目录；保留授权、后台账号、后台目录和安装锁。',
        'level' => 'warn',
    ),
    'factory' => array(
        'title' => '恢复出厂初始状态',
        'desc' => '在清空业务配置基础上，额外清空内容中心上传图片；适合制作空白客户端包或重新交付前使用。',
        'level' => 'danger',
    ),
);

if($_SERVER['REQUEST_METHOD'] === 'POST'){
    $mode = $_POST['mode'] ?? '';
    if(!isset($modes[$mode])){
        $error = '初始化模式无效。';
    }else{
        $targets = initial_setup_collect_targets($mode);
        $backupDir = initial_setup_backup($targets['backup']);
        $deleted = 0;
        foreach($targets['clear_dirs'] as $relative){
            $deleted += initial_setup_delete_children(initial_setup_path($relative));
            initial_setup_mkdir(initial_setup_path($relative));
        }
        $configOk = true;
        if($mode === 'business' || $mode === 'factory') $configOk = initial_setup_reset_configs();
        if(function_exists('static_cache_clear')) static_cache_clear();
        if(function_exists('admin_oplog')) admin_oplog('initial_setup_' . $mode, 'backup=' . $backupDir . ' deleted=' . $deleted);
        $msg = $modes[$mode]['title'] . '已完成。备份目录：' . str_replace($root . '/', '', str_replace('\\', '/', $backupDir));
        if(!$configOk) $error = '部分配置文件写入失败，请检查 config 目录权限。';
        $report[] = '删除文件/目录数量：' . intval($deleted);
        $report[] = '授权配置、授权中心 API、授权状态缓存、后台账号、后台目录、安装锁均已保留。';
    }
}

list($cacheCount, $cacheSize) = initial_setup_dirs_stat(initial_setup_runtime_cache_dirs());
list($contentCount, $contentSize) = initial_setup_dirs_stat(array('data/content_center'));
list($uploadCount, $uploadSize) = initial_setup_dirs_stat(array('assets/uploads/content_center'));

admin_header('初始设置');
?>
<?php if($msg): ?><div class="notice"><?php echo admin_h($msg); ?></div><?php endif; ?>
<?php if($error): ?><div class="warn"><?php echo admin_h($error); ?></div><?php endif; ?>
<?php if($report): ?><div class="notice"><?php foreach($report as $line): ?><div><?php echo admin_h($line); ?></div><?php endforeach; ?></div><?php endif; ?>

<div class="grid">
    <div class="stat"><strong><?php echo intval($cacheCount); ?></strong><span>缓存/日志文件</span></div>
    <div class="stat"><strong><?php echo round($cacheSize/1024, 2); ?>KB</strong><span>缓存/日志大小</span></div>
    <div class="stat"><strong><?php echo intval($contentCount); ?></strong><span>内容中心文件</span></div>
    <div class="stat"><strong><?php echo intval($uploadCount); ?></strong><span>内容上传图片</span></div>
</div>

<div class="card">
    <h2>初始设置说明</h2>
    <p class="help">本功能用于交付前或重新初始化时清理客户端运行数据。执行前系统会自动备份被处理的配置和目录到 <code>cache/backup/initial_setup/</code>。</p>
    <p class="help">默认保留：<code>config/license.php</code>、<code>config/license_server.php</code>、<code>cache/license/</code>、<code>config/admin.php</code>、<code>yanscms/config.php</code>、<code>install/install.lock</code>。</p>
</div>

<div class="card">
    <h2>选择初始化模式</h2>
    <div class="initial-setup-options">
        <?php foreach($modes as $key=>$mode): ?>
        <form method="post" class="initial-setup-card initial-setup-<?php echo admin_h($mode['level']); ?>" data-confirm="确定执行<?php echo admin_h($mode['title']); ?>吗？系统会先备份再清理，此操作不可逆。">
            <input type="hidden" name="mode" value="<?php echo admin_h($key); ?>">
            <h3><?php echo admin_h($mode['title']); ?></h3>
            <p><?php echo admin_h($mode['desc']); ?></p>
            <button class="<?php echo $mode['level']==='danger' ? 'btn danger' : 'btn'; ?>">执行<?php echo admin_h($mode['title']); ?></button>
        </form>
        <?php endforeach; ?>
    </div>
</div>

<div class="card">
    <h2>清理范围</h2>
    <table>
        <tr><th>模式</th><th>会处理的内容</th><th>保留内容</th></tr>
        <tr><td>清理缓存和日志</td><td><code>cache/static</code>、<code>cache/oplog</code>、<code>cache/push</code>、<code>cache/spider</code>、<code>cache/security</code></td><td>业务配置、内容、授权码、授权状态缓存、后台账号</td></tr>
        <tr><td>清空业务配置</td><td>缓存日志、站群域名、自动分配记录、友链、推送、强引、内容中心、站点目录</td><td>授权、公钥、API 密钥、授权状态缓存、后台账号、安装锁、主题基础数据</td></tr>
        <tr><td>恢复出厂初始状态</td><td>清空业务配置，并清空 <code>assets/uploads/content_center</code></td><td>授权、公钥、API 密钥、授权状态缓存、后台账号、安装锁、主题固定图片</td></tr>
    </table>
</div>

<style>
.initial-setup-options{display:grid;grid-template-columns:repeat(auto-fit,minmax(260px,1fr));gap:16px;}
.initial-setup-card{border:1px solid #e5e7eb;border-radius:8px;padding:18px;background:#fff;display:flex;flex-direction:column;gap:12px;min-height:210px;}
.initial-setup-card h3{margin:0;font-size:18px;}
.initial-setup-card p{margin:0;color:#5b6472;line-height:1.7;flex:1;}
.initial-setup-warn{border-color:#f59e0b;background:#fffbeb;}
.initial-setup-danger{border-color:#ef4444;background:#fff5f5;}
</style>
<?php admin_footer(); ?>