<?php
/**
 * Local-data frontend for PPQCMS.
 * Collection is performed by PPQSQL/collect.php or the scheduled updater;
 * page requests only read PPQSQL/Home/<category>.txt.
 */

$ppqTranslateHelper = dirname(__DIR__, 2) . '/Php/Home/Translate.php';
if (is_file($ppqTranslateHelper)) require_once $ppqTranslateHelper;

if (!function_exists('ppq_h')) {
    function ppq_h($value) {
        return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
    }
}

if (!function_exists('ppq_read_json')) {
    function ppq_read_json($path, $fallback = array()) {
        if (!is_file($path)) return $fallback;
        $raw = @file_get_contents($path);
        $data = json_decode($raw, true);
        return is_array($data) ? $data : $fallback;
    }
}

if (!function_exists('ppq_safe_url')) {
    function ppq_safe_url($url) {
        $url = trim((string)$url);
        if ($url === '') return '';
        if (strpos($url, '//') === 0) return 'https:' . $url;
        return preg_match('#^https?://#i', $url) ? $url : '';
    }
}

if (!function_exists('ppq_types')) {
    function ppq_types() {
        $data = ppq_read_json(__DIR__ . '/../type.php');
        $types = array();
        foreach ($data as $item) {
            $id = isset($item['id']) ? (int)$item['id'] : (isset($item['type_id']) ? (int)$item['type_id'] : 0);
            $name = isset($item['name']) ? $item['name'] : (isset($item['type_name']) ? $item['type_name'] : '');
            if ($id > 0 && $name !== '') $types[$id] = $name;
        }
        return $types;
    }
}

if (!function_exists('ppq_records')) {
    function ppq_records($tid) {
        $tid = (int)$tid;
        if ($tid < 1) return array();
        $data = ppq_read_json(__DIR__ . '/' . $tid . '.txt');
        $records = array();
        foreach ($data as $item) {
            $id = isset($item['d_id']) ? trim((string)$item['d_id']) : '';
            if ($id === '') continue;
            $item['d_id'] = $id;
            $item['d_pic'] = ppq_safe_url(isset($item['d_pic']) ? $item['d_pic'] : '');
            $item['d_playurl'] = ppq_safe_url(isset($item['d_playurl']) ? $item['d_playurl'] : '');
            $records[] = $item;
        }
        return $records;
    }
}

if (!function_exists('ppq_find_video')) {
    function ppq_find_video($id, $tid, $types) {
        $id = trim((string)$id);
        $tid = (int)$tid;
        $order = array();
        if ($tid > 0 && isset($types[$tid])) $order[] = $tid;
        foreach ($types as $typeId => $unused) {
            if (!in_array($typeId, $order, true)) $order[] = $typeId;
        }
        foreach ($order as $typeId) {
            foreach (ppq_records($typeId) as $item) {
                if ((string)$item['d_id'] === $id) return array($item, $typeId);
            }
        }
        return array(null, 0);
    }
}

if (!function_exists('ppq_detail_url')) {
    function ppq_detail_url($id, $tid) {
        return '/video_detail/' . rawurlencode((string)$id) . '/' . (int)$tid . '/index.html';
    }
}

if (!function_exists('ppq_play_url')) {
    function ppq_play_url($id, $tid) {
        return '/video_conter/' . rawurlencode((string)$id) . '/' . (int)$tid . '/index.html';
    }
}

$types = ppq_types();
$page = isset($_GET['page']) ? strtolower(trim($_GET['page'])) : '';
$id = isset($_GET['id']) ? trim((string)$_GET['id']) : '';
$tid = isset($_GET['tid']) ? (int)$_GET['tid'] : 0;
$pageNo = isset($_GET['p']) ? max(1, (int)$_GET['p']) : 1;

// Direct category links such as /PPQSQL/Home/index.php?tid=20 remain usable.
if ($page === '' && $tid > 0) $page = 'category';

// Keep old links working while the site transitions from the legacy router.
if ($page === '' && !empty($_GET['m'])) {
    $legacy = explode('*', (string)$_GET['m']);
    $legacyPage = isset($legacy[0]) ? $legacy[0] : '';
    $id = isset($legacy[1]) ? trim($legacy[1]) : $id;
    $tid = isset($legacy[2]) ? (int)$legacy[2] : $tid;
    if ($legacyPage === 'video_detail') $page = 'detail';
    if ($legacyPage === 'video_conter') $page = 'play';
    if ($legacyPage === 'video_list') $page = 'category';
}

if ($page === 'detail' || $page === 'play') {
    list($video, $foundTid) = ppq_find_video($id, $tid, $types);
    if (!$video) {
        http_response_code(404);
        echo '<!doctype html><meta charset="utf-8"><title>视频不存在</title><p style="font-family:sans-serif;padding:40px">视频数据不存在或已被资源点移除。</p>';
        exit;
    }
    $tid = $foundTid;
    $name = isset($video['d_name']) ? $video['d_name'] : '视频详情';
    $pic = isset($video['d_pic']) ? $video['d_pic'] : '';
    $play = isset($video['d_playurl']) ? $video['d_playurl'] : '';
    $typeName = isset($types[$tid]) ? $types[$tid] : '视频';
    if ($page === 'play') {
        ?><!doctype html>
        <html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title><?php echo ppq_h($name); ?> - 播放</title>
        <style>body{margin:0;background:#111;color:#fff;font-family:Arial,'Microsoft YaHei',sans-serif}.wrap{max-width:1100px;margin:auto;padding:24px}.back{color:#9fd8ff;text-decoration:none}.player{margin-top:20px;background:#000;min-height:300px;display:flex;align-items:center;justify-content:center}video{width:100%;max-height:75vh}.empty{padding:70px 20px;text-align:center;color:#bbb}.meta{color:#aaa;margin:16px 0}</style></head>
        <body><div class="wrap"><a class="back" href="<?php echo ppq_h(ppq_detail_url($id, $tid)); ?>">← 返回详情</a><h1><?php echo ppq_h($name); ?></h1>
        <div class="player"><?php if ($play): ?><video id="player" controls playsinline preload="metadata" poster="<?php echo ppq_h($pic); ?>"><source src="<?php echo ppq_h($play); ?>"></video><?php else: ?><div class="empty">当前视频没有可用播放地址。</div><?php endif; ?></div>
        <div class="meta">分类：<?php echo ppq_h($typeName); ?></div></div>
        <?php if ($play && preg_match('/\.m3u8(?:\?|$)/i', $play)): ?><script src="https://cdn.jsdelivr.net/npm/hls.js@1.5.17"></script><script>(function(){var v=document.getElementById('player');if(v&&window.Hls&&Hls.isSupported()){var h=new Hls();h.loadSource(<?php echo json_encode($play); ?>);h.attachMedia(v);}})();</script><?php endif; ?><?php echo function_exists('ppq_translate_assets') ? ppq_translate_assets() : ''; ?></body></html><?php
        exit;
    }
    ?><!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title><?php echo ppq_h($name); ?> - PPQCMS</title>
    <style>body{margin:0;background:#f6f7fb;color:#222;font-family:Arial,'Microsoft YaHei',sans-serif}.wrap{max-width:1100px;margin:auto;padding:24px}.top a,.back{color:#2f3b52;text-decoration:none}.card{margin-top:20px;background:#fff;border-radius:14px;padding:24px;box-shadow:0 8px 28px #18233b12}.cover{max-width:420px;width:100%;max-height:520px;object-fit:cover;border-radius:10px}.btn{display:inline-block;margin-top:20px;padding:12px 28px;background:#2f3b52;color:#fff;border-radius:8px;text-decoration:none}.muted{color:#888}</style></head><body><div class="wrap"><div class="top"><a href="/">首页</a> / <a href="<?php echo ppq_h('/?page=category&tid=' . $tid); ?>"><?php echo ppq_h($typeName); ?></a></div><div class="card"><h1><?php echo ppq_h($name); ?></h1><?php if ($pic): ?><img class="cover" src="<?php echo ppq_h($pic); ?>" alt="<?php echo ppq_h($name); ?>"><?php endif; ?><p class="muted">分类：<?php echo ppq_h($typeName); ?></p><a class="btn" href="<?php echo ppq_h(ppq_play_url($id, $tid)); ?>">立即播放</a></div></div><?php echo function_exists('ppq_translate_assets') ? ppq_translate_assets() : ''; ?></body></html><?php
    exit;
}

if ($page === 'category') {
    $tid = isset($types[$tid]) ? $tid : 0;
    $records = $tid > 0 ? ppq_records($tid) : array();
    $perPage = 24;
    $totalPages = max(1, (int)ceil(count($records) / $perPage));
    $pageNo = min($pageNo, $totalPages);
    $records = array_slice($records, ($pageNo - 1) * $perPage, $perPage);
    $title = $tid > 0 ? $types[$tid] : '全部视频';
} else {
    $title = '首页';
    $sections = array();
    foreach ($types as $typeId => $typeName) {
        $records = ppq_records($typeId);
        if (!empty($records)) $sections[] = array('id' => $typeId, 'name' => $typeName, 'records' => array_slice($records, 0, 12));
        if (count($sections) >= 6) break;
    }
}
?><!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title><?php echo ppq_h($title); ?> - PPQCMS</title>
<style>*{box-sizing:border-box}body{margin:0;background:linear-gradient(135deg,#eef4ff,#fff);color:#252b36;font-family:Arial,'Microsoft YaHei',sans-serif}.wrap{max-width:1240px;margin:auto;padding:24px}.header{display:flex;justify-content:space-between;align-items:center;margin-bottom:20px}.logo{font-size:26px;font-weight:800;color:#2f3b52}.home{color:#2f3b52;text-decoration:none}.cats{display:flex;flex-wrap:wrap;gap:10px;padding:16px;background:#fff;border-radius:14px;box-shadow:0 6px 20px #18233b12}.cats a{padding:9px 15px;border-radius:9px;background:#f0f3f8;color:#2f3b52;text-decoration:none}.cats a.active,.cats a:hover{background:#2f3b52;color:#fff}.section{margin-top:28px}.section-head{display:flex;justify-content:space-between;align-items:center;margin-bottom:12px}.section-head h2{margin:0}.more{color:#68758a;text-decoration:none;font-size:14px}.grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(210px,1fr));gap:18px}.card{display:block;background:#fff;border-radius:14px;overflow:hidden;color:inherit;text-decoration:none;box-shadow:0 6px 20px #18233b12;transition:transform .2s}.card:hover{transform:translateY(-3px)}.thumb{aspect-ratio:16/10;background:#e9edf4;overflow:hidden}.thumb img{width:100%;height:100%;object-fit:cover}.info{padding:12px}.name{font-weight:600;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.meta{margin-top:7px;font-size:12px;color:#8893a3}.empty{padding:70px;text-align:center;color:#8893a3;background:#fff;border-radius:14px}.pager{display:flex;gap:10px;margin-top:24px}.pager a{padding:8px 13px;background:#fff;border-radius:8px;color:#2f3b52;text-decoration:none}.footer{text-align:center;color:#99a2b0;padding:32px 0;font-size:12px}</style></head><body><div class="wrap"><div class="header"><div class="logo">PPQCMS</div><a class="home" href="/">首页</a></div><nav class="cats"><a href="/" class="<?php echo $page === '' ? 'active' : ''; ?>">首页推荐</a><?php foreach ($types as $typeId => $typeName): ?><a href="<?php echo ppq_h('/?page=category&tid=' . $typeId); ?>" class="<?php echo ($page === 'category' && $tid === $typeId) ? 'active' : ''; ?>"><?php echo ppq_h($typeName); ?></a><?php endforeach; ?></nav>
<?php if ($page === 'category'): ?><section class="section"><div class="section-head"><h2><?php echo ppq_h($title); ?></h2><span class="meta">第 <?php echo $pageNo; ?> / <?php echo $totalPages; ?> 页</span></div><?php if ($records): ?><div class="grid"><?php foreach ($records as $v): ?><a class="card" href="<?php echo ppq_h(ppq_detail_url($v['d_id'], $tid)); ?>"><div class="thumb"><?php if (!empty($v['d_pic'])): ?><img loading="lazy" src="<?php echo ppq_h($v['d_pic']); ?>" alt="<?php echo ppq_h($v['d_name']); ?>"><?php endif; ?></div><div class="info"><div class="name"><?php echo ppq_h($v['d_name']); ?></div><div class="meta"><?php echo !empty($v['d_playurl']) ? '可播放' : '暂无播放地址'; ?></div></div></a><?php endforeach; ?></div><?php else: ?><div class="empty">该分类暂无已采集的视频数据。</div><?php endif; ?><div class="pager"><?php if ($pageNo > 1): ?><a href="<?php echo ppq_h('/?page=category&tid=' . $tid . '&p=' . ($pageNo - 1)); ?>">上一页</a><?php endif; ?><?php if ($pageNo < $totalPages): ?><a href="<?php echo ppq_h('/?page=category&tid=' . $tid . '&p=' . ($pageNo + 1)); ?>">下一页</a><?php endif; ?></div></section>
<?php else: ?><?php if ($sections): foreach ($sections as $section): ?><section class="section"><div class="section-head"><h2><?php echo ppq_h($section['name']); ?></h2><a class="more" href="<?php echo ppq_h('/?page=category&tid=' . $section['id']); ?>">查看全部 →</a></div><div class="grid"><?php foreach ($section['records'] as $v): ?><a class="card" href="<?php echo ppq_h(ppq_detail_url($v['d_id'], $section['id'])); ?>"><div class="thumb"><?php if (!empty($v['d_pic'])): ?><img loading="lazy" src="<?php echo ppq_h($v['d_pic']); ?>" alt="<?php echo ppq_h($v['d_name']); ?>"><?php endif; ?></div><div class="info"><div class="name"><?php echo ppq_h($v['d_name']); ?></div><div class="meta"><?php echo !empty($v['d_playurl']) ? '可播放' : '暂无播放地址'; ?></div></div></a><?php endforeach; ?></div></section><?php endforeach; else: ?><div class="empty">暂无已采集的视频数据，请在后台或定时任务中运行采集。</div><?php endif; ?><?php endif; ?><div class="footer">PPQCMS © <?php echo date('Y'); ?></div></div><?php echo function_exists('ppq_translate_assets') ? ppq_translate_assets() : ''; ?></body></html>
