<?php
include __DIR__ . '/auth.php';
admin_check();
include __DIR__ . '/layout.php';
include_once __DIR__ . '/../inc/static_cache.php';

$site = preg_replace('/[^a-zA-Z0-9\.\-_]/','', $_GET['site'] ?? '');
$channel = preg_replace('/[^a-zA-Z0-9\-_]/','', $_GET['channel'] ?? 'news');
$file = preg_replace('/[^a-zA-Z0-9\.\-_]/','', $_GET['file'] ?? '');
$dir = realpath(__DIR__ . '/../data/sites/' . $site . '/' . $channel);
$root = realpath(__DIR__ . '/../data/sites');

$domains = is_file(__DIR__ . '/../config/domain.php') ? include __DIR__ . '/../config/domain.php' : array();
$theme = $domains[$site]['theme'] ?? 'industrial';
$assetFile = __DIR__ . '/../data/theme_assets.php';
$assetMap = is_file($assetFile) ? include $assetFile : array();
$assetPool = $assetMap[$theme][$channel] ?? ($assetMap[$theme]['news'] ?? array());

admin_header('编辑TXT');

if(!$dir || !$root || strpos($dir,$root)!==0){
    echo '<div class="card">目录不存在</div>';
    admin_footer();
    exit;
}
if(!$file){
    $file = date('YmdHis') . '.txt';
}
$path = $dir . '/' . $file;
$saved = false;
if($_SERVER['REQUEST_METHOD'] === 'POST'){
    $content = $_POST['content'] ?? '';
    if(isset($_POST['quick_image']) && trim($_POST['quick_image']) !== ''){
        $img = trim($_POST['quick_image']);
        if(preg_match('/^图片：.*$/mu', $content)){
            $content = preg_replace('/^图片：.*$/mu', '图片：' . $img, $content, 1);
        }else{
            $content = preg_replace('/(摘要：.*\n)/u', '$1图片：' . $img . "\n", $content, 1);
        }
    }
    file_put_contents($path, $content, LOCK_EX);
    if(function_exists('static_cache_clear')) static_cache_clear();
    $saved = true;
}
$defaultImage = $assetPool ? $assetPool[abs(crc32($file . $channel)) % count($assetPool)] : '';
$content = is_file($path) ? file_get_contents($path) : "标题：新文章标题\n日期：".date('Y-m-d')."\n分类：企业新闻\n关键词：关键词1,关键词2\n摘要：这里写摘要\n图片：".$defaultImage."\n\n正文：\n这里写正文内容。\n";
?>
<?php if($saved): ?><div class="notice">保存成功</div><?php endif; ?>
<div class="card">
<h2>编辑：<?php echo admin_h($file); ?></h2>
<p class="help">当前域名主题：<code><?php echo admin_h(function_exists('admin_site_theme_label') ? admin_site_theme_label($theme) : $theme); ?></code>。新建文章会自动带入当前主题素材库中的 1 张图片，也可以在下方手动选择替换。</p>
<form method="post">
<?php if($assetPool): ?>
<div class="asset-picker">
    <?php foreach($assetPool as $img): ?>
    <label>
        <input type="radio" name="quick_image" value="<?php echo admin_h($img); ?>">
        <img src="<?php echo admin_h($img); ?>" alt="">
        <span><?php echo admin_h(basename($img)); ?></span>
    </label>
    <?php endforeach; ?>
</div>
<?php endif; ?>
<textarea name="content"><?php echo admin_h($content); ?></textarea>
<p>
<button>保存</button>
<a class="btn ghost" href="files.php?site=<?php echo urlencode($site); ?>&channel=<?php echo urlencode($channel); ?>">返回列表</a>
</p>
</form>
</div>
<?php admin_footer(); ?>
