<?php
/**
 * PPQCMS SEO helper (shared by frontend + admin)
 * - ppq_seo_head($type, $vars): returns <head> SEO block (canonical + OG + JSON-LD)
 * - ppq_build_sitemap(): writes /sitemap.xml
 * - ppq_baidu_push($urls, $token): push URLs to Baidu
 * Direct web access is blocked.
 */
if (basename(__FILE__) === basename(isset($_SERVER['SCRIPT_FILENAME']) ? $_SERVER['SCRIPT_FILENAME'] : '')) {
    http_response_code(404);
    exit;
}

if (!function_exists('ppq_root')) {
    function ppq_root() {
        if (!empty($_SERVER['DOCUMENT_ROOT'])) return rtrim($_SERVER['DOCUMENT_ROOT'], '/');
        return dirname(__DIR__, 2);
    }
}

if (!function_exists('ppq_site_url')) {
    function ppq_site_url() {
        $proto = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
        $host = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : 'localhost';
        return $proto . '://' . $host;
    }
}

if (!function_exists('ppq_seo_cfg')) {
    function ppq_seo_cfg() {
        static $cfg = null;
        if ($cfg !== null) return $cfg;
        $file = ppq_root() . '/PPQSQL/Admin/Basic/AdminBasic.php';
        $arr = array();
        if (is_file($file)) {
            $dec = @json_decode(@file_get_contents($file), true);
            if (is_array($dec)) $arr = $dec;
        }
        return $arr;
    }
}

if (!function_exists('ppq_seo_esc')) {
    function ppq_seo_esc($s) {
        return htmlspecialchars((string) ($s ?? ''), ENT_QUOTES, 'UTF-8');
    }
}

if (!function_exists('ppq_canonical_url')) {
    function ppq_canonical_url($type, $id = '', $page = '') {
        $base = rtrim(ppq_site_url(), '/');
        if ($type === 'index') return $base . '/';
        if ($type === 'video_detail') return $base . '/video_detail/' . rawurlencode($id) . '/' . rawurlencode($page) . '/index.html';
        if ($type === 'video_list') return $base . '/video_list/' . rawurlencode($id) . '/' . rawurlencode($page) . '/index.html';
        if ($type === 'video_conter') return $base . '/video_conter/' . rawurlencode($id) . '/' . rawurlencode($page) . '/index.html';
        if ($type === 'video_search') return $base . '/?m=video_search*' . rawurlencode($id) . '*1';
        return $base . '/';
    }
}

if (!function_exists('ppq_seo_head')) {
    function ppq_seo_head($type = 'home', $vars = array()) {
        $cfg = ppq_seo_cfg();
        $site = isset($cfg['WebTitle']) ? $cfg['WebTitle'] : 'PPQCMS';
        $desc = isset($cfg['WebDescription']) ? $cfg['WebDescription'] : '';
        $ogImage = isset($cfg['SeoOgImage']) && $cfg['SeoOgImage'] ? $cfg['SeoOgImage'] : (isset($cfg['WebLogo']) ? $cfg['WebLogo'] : '');
        $canonicalOn = !isset($cfg['SeoCanonical']) || $cfg['SeoCanonical'] === '1' || $cfg['SeoCanonical'] === 1;
        $ogOn = !isset($cfg['SeoOg']) || $cfg['SeoOg'] === '1' || $cfg['SeoOg'] === 1;
        $jsonldOn = !isset($cfg['SeoJsonLd']) || $cfg['SeoJsonLd'] === '1' || $cfg['SeoJsonLd'] === 1;

        $title = isset($vars['title']) ? $vars['title'] : $site;
        $pageDesc = isset($vars['description']) ? $vars['description'] : $desc;
        $image = isset($vars['image']) ? $vars['image'] : $ogImage;
        $url = isset($vars['url']) ? $vars['url'] : ppq_site_url() . '/';

        $out = '';
        if ($canonicalOn) {
            $out .= '<link rel="canonical" href="' . ppq_seo_esc($url) . '">' . "\n";
        }
        if ($ogOn) {
            $ogType = ($type === 'detail') ? 'video.other' : 'website';
            $out .= '<meta property="og:type" content="' . $ogType . '">' . "\n";
            $out .= '<meta property="og:site_name" content="' . ppq_seo_esc($site) . '">' . "\n";
            $out .= '<meta property="og:title" content="' . ppq_seo_esc($title) . '">' . "\n";
            $out .= '<meta property="og:description" content="' . ppq_seo_esc($pageDesc) . '">' . "\n";
            $out .= '<meta property="og:url" content="' . ppq_seo_esc($url) . '">' . "\n";
            if ($image) {
                $out .= '<meta property="og:image" content="' . ppq_seo_esc($image) . '">' . "\n";
            }
        }
        if ($jsonldOn) {
            if ($type === 'detail' && !empty($vars['video'])) {
                $v = $vars['video'];
                $ld = array(
                    '@context' => 'https://schema.org',
                    '@type' => 'VideoObject',
                    'name' => $title,
                    'description' => $pageDesc,
                    'thumbnailUrl' => $image,
                    'uploadDate' => isset($v['date']) ? $v['date'] : date('c'),
                    'contentUrl' => isset($v['playurl']) ? $v['playurl'] : $url,
                    'url' => $url,
                );
                $out .= '<script type="application/ld+json">' . json_encode($ld, JSON_UNESCAPED_UNICODE) . '</script>' . "\n";
            } else {
                $ld = array(
                    '@context' => 'https://schema.org',
                    '@type' => 'WebSite',
                    'name' => $site,
                    'url' => ppq_site_url() . '/',
                );
                $out .= '<script type="application/ld+json">' . json_encode($ld, JSON_UNESCAPED_UNICODE) . '</script>' . "\n";
            }
        }
        return $out;
    }
}

if (!function_exists('ppq_build_sitemap')) {
    function ppq_build_sitemap() {
        $root = ppq_root();
        $home = $root . '/PPQSQL/Home/';
        $site = rtrim(ppq_site_url(), '/');
        $urls = array();
        $urls[] = array('loc' => $site . '/', 'priority' => '1.0', 'changefreq' => 'daily');
        $files = glob($home . '*.txt');
        $videoCount = 0;
        foreach ($files as $f) {
            $cat = basename($f, '.txt');
            if (!is_numeric($cat)) continue;
            $arr = @json_decode(@file_get_contents($f), true);
            if (!is_array($arr)) continue;
            $urls[] = array('loc' => $site . '/video_list/' . $cat . '/1/index.html', 'priority' => '0.6', 'changefreq' => 'daily');
            foreach ($arr as $v) {
                if (!isset($v['d_id'])) continue;
                $urls[] = array('loc' => $site . '/video_detail/' . $v['d_id'] . '/' . $cat . '/index.html', 'priority' => '0.8', 'changefreq' => 'weekly');
                $videoCount++;
            }
        }
        $xml = '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
        $xml .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:video="http://www.google.com/schemas/sitemap-video/1.1">' . "\n";
        foreach ($urls as $u) {
            $xml .= '  <url><loc>' . htmlspecialchars($u['loc'], ENT_XML1, 'UTF-8') . '</loc>';
            if (isset($u['priority'])) $xml .= '<priority>' . $u['priority'] . '</priority>';
            if (isset($u['changefreq'])) $xml .= '<changefreq>' . $u['changefreq'] . '</changefreq>';
            $xml .= '<lastmod>' . date('c') . '</lastmod></url>' . "\n";
        }
        $xml .= '</urlset>' . "\n";
        @file_put_contents($root . '/sitemap.xml', $xml);
        return array('total' => count($urls), 'videos' => $videoCount);
    }
}

if (!function_exists('ppq_baidu_push')) {
    function ppq_baidu_push($urls, $token, $site = null) {
        if ($site === null) $site = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : 'localhost';
        if (!$token || !is_array($urls) || count($urls) === 0) return array('ok' => false, 'msg' => 'missing token or urls');
        $api = 'http://data.zz.baidu.com/urls?site=' . urlencode($site) . '&token=' . urlencode($token);
        $data = implode("\n", $urls);
        if (!function_exists('curl_init')) return array('ok' => false, 'msg' => 'curl not available');
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $api);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/plain'));
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        $res = curl_exec($ch);
        $err = curl_error($ch);
        curl_close($ch);
        return array('ok' => true, 'response' => $res, 'error' => $err);
    }
}
