<?php
/**
 * 字体下载和安装 API
 * 支持从远程服务器下载字体文件到项目目录
 */

require __DIR__ . '/../../app/bootstrap.php';
require_login();

header('Content-Type: application/json; charset=utf-8');

$action = isset($_GET['action']) ? trim((string)$_GET['action']) : '';
$fontName = isset($_GET['font']) ? trim((string)$_GET['font']) : '';

// 字体映射表
$fontMap = array(
    'noto-cjk' => array(
        'url' => 'http://154.12.28.99/font/NotoSans-cjk.otf',
        'filename' => 'NotoSansCJK-Regular.ttc',
        'name' => 'Noto Sans CJK'
    ),
    'msyh' => array(
        'url' => 'http://154.12.28.99/font/msyh.ttc',
        'filename' => 'msyh.ttc',
        'name' => 'Microsoft YaHei'
    ),
    'simhei' => array(
        'url' => 'http://154.12.28.99/font/SimHei.ttf',
        'filename' => 'simhei.ttf',
        'name' => 'SimHei'
    ),
    'simsun' => array(
        'url' => 'http://154.12.28.99/font/SimSun.ttf',
        'filename' => 'simsun.ttf',
        'name' => 'SimSun'
    ),
);

if ($action === 'download' && isset($fontMap[$fontName])) {
    $fontInfo = $fontMap[$fontName];
    $fontDir = __DIR__ . '/../../assets/fonts';
    $targetPath = $fontDir . '/' . $fontInfo['filename'];
    
    // 确保目录存在
    if (!is_dir($fontDir)) {
        if (!mkdir($fontDir, 0755, true)) {
            echo json_encode(array(
                'ok' => false,
                'error' => '无法创建字体目录'
            ), JSON_UNESCAPED_UNICODE);
            exit;
        }
    }
    
    // 检查是否已存在
    if (is_file($targetPath)) {
        echo json_encode(array(
            'ok' => true,
            'message' => '字体已存在，无需重复下载',
            'filename' => $fontInfo['filename']
        ), JSON_UNESCAPED_UNICODE);
        exit;
    }
    
    // 1) 本地直读：若字体仓库与本站部署在同一台服务器，尝试按 URL 路径映射到本地文件系统
    $downloadErrors = array();
    $fontContent = false;
    $parsed = parse_url($fontInfo['url']);
    if ($parsed && isset($parsed['path'])) {
        // 例如 URL: http(s)://<host>/font/SimHei.ttf => 本地猜测路径: 项目根/font/SimHei.ttf
        $localGuess = realpath(__DIR__ . '/../../' . ltrim($parsed['path'], '/'));
        if ($localGuess && is_file($localGuess)) {
            $content = @file_get_contents($localGuess);
            if ($content !== false && strlen($content) > 0) {
                $fontContent = $content;
            } else {
                $downloadErrors[] = 'local read failed: ' . $localGuess;
            }
        } else {
            $downloadErrors[] = 'local miss: ' . (__DIR__ . '/../../' . ltrim($parsed['path'], '/'));
            // 进一步尝试使用 DOCUMENT_ROOT 进行映射（同机不同项目根的情况）
            $docRoot = isset($_SERVER['DOCUMENT_ROOT']) ? rtrim((string)$_SERVER['DOCUMENT_ROOT'], '/\\') : '';
            if ($docRoot !== '') {
                $guess2 = realpath($docRoot . DIRECTORY_SEPARATOR . ltrim($parsed['path'], '/'));
                if ($guess2 && is_file($guess2)) {
                    $content = @file_get_contents($guess2);
                    if ($content !== false && strlen($content) > 0) {
                        $fontContent = $content;
                    } else {
                        $downloadErrors[] = 'local(docroot) read failed: ' . $guess2;
                    }
                } else {
                    $downloadErrors[] = 'local(docroot) miss: ' . ($docRoot . DIRECTORY_SEPARATOR . ltrim($parsed['path'], '/'));
                }
            }
        }
    }

    // 2) 网络下载（稳健：fgc/cURL；http->https；追加 127.0.0.1 回环尝试以规避公网回环限制）
    $tryUrls = array();
    $tryUrls[] = $fontInfo['url'];
    if ($parsed && isset($parsed['path'])) {
        $tryUrls[] = 'http://127.0.0.1' . $parsed['path'];
        $tryUrls[] = 'https://127.0.0.1' . $parsed['path'];
    }
    if (stripos($fontInfo['url'], 'http://') === 0) {
        $tryUrls[] = 'https://' . substr($fontInfo['url'], 7);
    }

    if ($fontContent === false) {
        // 仅当本地直读失败时，进行网络尝试
        
        foreach ($tryUrls as $u) {
            // 方式一：file_get_contents
            $context = stream_context_create(array(
                'http' => array(
                    'timeout' => 45,
                    'follow_location' => 1,
                    'user_agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
                ),
                'ssl' => array(
                    'verify_peer' => false,
                    'verify_peer_name' => false
                )
            ));
            $content = @file_get_contents($u, false, $context);
            if ($content !== false && strlen($content) > 0) {
                $fontContent = $content;
                break;
            } else {
                $downloadErrors[] = 'fgc failed: ' . $u;
            }

            // 方式二：cURL（如果可用）
            if (function_exists('curl_init')) {
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, $u);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
                curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 15);
                curl_setopt($ch, CURLOPT_TIMEOUT, 60);
                curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36');
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
                $data = curl_exec($ch);
                if ($data !== false && curl_getinfo($ch, CURLINFO_HTTP_CODE) === 200 && strlen($data) > 0) {
                    $fontContent = $data;
                    curl_close($ch);
                    break;
                } else {
                    $downloadErrors[] = 'curl failed: ' . $u . ' err=' . curl_error($ch) . ' code=' . curl_getinfo($ch, CURLINFO_HTTP_CODE);
                }
                curl_close($ch);
            }
        }
    }
    foreach ($tryUrls as $u) {
        // 方式一：file_get_contents
        $context = stream_context_create(array(
            'http' => array(
                'timeout' => 45,
                'follow_location' => 1,
                'user_agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
            ),
            'ssl' => array(
                'verify_peer' => false,
                'verify_peer_name' => false
            )
        ));
        $content = @file_get_contents($u, false, $context);
        if ($content !== false && strlen($content) > 0) {
            $fontContent = $content;
            break;
        } else {
            $downloadErrors[] = 'fgc failed: ' . $u;
        }

        // 方式二：cURL（如果可用）
        if (function_exists('curl_init')) {
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $u);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 15);
            curl_setopt($ch, CURLOPT_TIMEOUT, 60);
            curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36');
            // 允许 https 在某些环境下绕过校验（仅用于下载公共字体文件）
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
            $data = curl_exec($ch);
            if ($data !== false && curl_getinfo($ch, CURLINFO_HTTP_CODE) === 200 && strlen($data) > 0) {
                $fontContent = $data;
                curl_close($ch);
                break;
            } else {
                $downloadErrors[] = 'curl failed: ' . $u . ' err=' . curl_error($ch) . ' code=' . curl_getinfo($ch, CURLINFO_HTTP_CODE);
            }
            curl_close($ch);
        }
    }

    if ($fontContent === false) {
        echo json_encode(array(
            'ok' => false,
            'error' => '下载字体文件失败，请检查服务器出网能力或防火墙。' ,
            'detail' => implode(' | ', $downloadErrors)
        ), JSON_UNESCAPED_UNICODE);
        exit;
    }
    
    // 保存字体文件
    if (file_put_contents($targetPath, $fontContent) === false) {
        echo json_encode(array(
            'ok' => false,
            'error' => '保存字体文件失败，请检查目录权限'
        ), JSON_UNESCAPED_UNICODE);
        exit;
    }
    
    echo json_encode(array(
        'ok' => true,
        'message' => '字体下载成功',
        'filename' => $fontInfo['filename'],
        'size' => filesize($targetPath)
    ), JSON_UNESCAPED_UNICODE);
    exit;
}

if ($action === 'list') {
    $fontDir = __DIR__ . '/../../assets/fonts';
    $fonts = array();
    
    foreach ($fontMap as $key => $info) {
        $targetPath = $fontDir . '/' . $info['filename'];
        $fonts[] = array(
            'key' => $key,
            'name' => $info['name'],
            'filename' => $info['filename'],
            'exists' => is_file($targetPath),
            'size' => is_file($targetPath) ? filesize($targetPath) : 0
        );
    }
    
    echo json_encode(array(
        'ok' => true,
        'fonts' => $fonts
    ), JSON_UNESCAPED_UNICODE);
    exit;
}

echo json_encode(array(
    'ok' => false,
    'error' => '无效的请求'
), JSON_UNESCAPED_UNICODE);
