<?php
/**
 * 微信JSSDK签名接口
 * 用于前端 wx.config() 配置，支持 wx-open-launch-weapp 跳转小程序
 */
require_once __DIR__ . '/../config.php';

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

// 获取公众号配置（优先从数据库settings表，其次从config.php常量）
$db = getDB();

$appid = '';
$secret = '';

// 从数据库读取
$stmt = $db->query("SELECT key_name, value FROM settings WHERE group_name = 'wechat'");
foreach ($stmt->fetchAll() as $row) {
    if ($row['key_name'] === 'wechat_appid') $appid = $row['value'];
    if ($row['key_name'] === 'wechat_secret') $secret = $row['value'];
}

// 兜底从config.php常量
if (empty($appid)) $appid = defined('WECHAT_APPID') ? WECHAT_APPID : '';
if (empty($secret)) $secret = defined('WECHAT_SECRET') ? WECHAT_SECRET : '';

if (empty($appid) || empty($secret)) {
    echo json_encode(['code' => 0, 'msg' => '公众号AppID或Secret未配置，请在后台设置或config.php中填写']);
    exit;
}

// 获取当前页面URL（前端传入）
$url = trim($_GET['url'] ?? '');
if (empty($url)) {
    echo json_encode(['code' => 0, 'msg' => '缺少url参数']);
    exit;
}

// 获取access_token（带缓存，2小时有效期）
$tokenCacheFile = __DIR__ . '/../data/access_token.json';
$ticketCacheFile = __DIR__ . '/../data/jsapi_ticket.json';

function getAccessToken($appid, $secret, $cacheFile) {
    // 检查缓存
    if (file_exists($cacheFile)) {
        $cache = json_decode(file_get_contents($cacheFile), true);
        if ($cache && $cache['expire_time'] > time()) {
            return $cache['access_token'];
        }
    }

    // 请求微信API
    $apiUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$secret}";
    $res = file_get_contents($apiUrl);
    $data = json_decode($res, true);

    if (!$data || isset($data['errcode'])) {
        return false;
    }

    // 缓存（提前5分钟过期）
    $cacheData = [
        'access_token' => $data['access_token'],
        'expire_time' => time() + $data['expires_in'] - 300,
    ];
    @file_put_contents($cacheFile, json_encode($cacheData));

    return $data['access_token'];
}

function getJsapiTicket($accessToken, $cacheFile) {
    // 检查缓存
    if (file_exists($cacheFile)) {
        $cache = json_decode(file_get_contents($cacheFile), true);
        if ($cache && $cache['expire_time'] > time()) {
            return $cache['jsapi_ticket'];
        }
    }

    // 请求微信API
    $apiUrl = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={$accessToken}&type=jsapi";
    $res = file_get_contents($apiUrl);
    $data = json_decode($res, true);

    if (!$data || $data['errcode'] !== 0) {
        return false;
    }

    // 缓存
    $cacheData = [
        'jsapi_ticket' => $data['ticket'],
        'expire_time' => time() + $data['expires_in'] - 300,
    ];
    @file_put_contents($cacheFile, json_encode($cacheData));

    return $data['ticket'];
}

$accessToken = getAccessToken($appid, $secret, $tokenCacheFile);
if (!$accessToken) {
    echo json_encode(['code' => 0, 'msg' => '获取access_token失败，请检查AppID和Secret是否正确']);
    exit;
}

$jsapiTicket = getJsapiTicket($accessToken, $ticketCacheFile);
if (!$jsapiTicket) {
    echo json_encode(['code' => 0, 'msg' => '获取jsapi_ticket失败']);
    exit;
}

// 生成签名
$nonceStr = md5(uniqid(mt_rand(), true));
$timestamp = time();
$signStr = "jsapi_ticket={$jsapiTicket}&noncestr={$nonceStr}&timestamp={$timestamp}&url={$url}";
$signature = sha1($signStr);

echo json_encode([
    'code' => 1,
    'data' => [
        'appId'     => $appid,
        'timestamp' => $timestamp,
        'nonceStr'  => $nonceStr,
        'signature' => $signature,
    ]
], JSON_UNESCAPED_SLASHES);
