<?php
/**
 * strongswan_app_version.php
 *
 * update_channel 값:
 *   auto      — 설치 출처 자동 감지 (Play Store 설치 → Play Store, 직접 설치 → APK 다운로드)
 *   apk       — 항상 직접 APK 다운로드
 *   playstore — 항상 Google Play 스토어로 연결
 */
header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-cache, no-store, must-revalidate');
header('X-Robots-Tag: noindex');

include_once(__DIR__ . '/_common.php');

define('APK_BASE_URL', 'https://app.vpnlink.kr/mylib/apk_download/');
define('APK_TABLE',    'app_apk_release');

// pending → live 자동 전환
sql_query("UPDATE " . APK_TABLE . "
           SET status='live', activated_at=NOW()
           WHERE status='pending' AND scheduled_at <= NOW()", false);

$row = sql_fetch("SELECT * FROM " . APK_TABLE . "
                  WHERE status='live'
                  ORDER BY version_code DESC, id DESC
                  LIMIT 1", false);

if (!$row || empty($row['id'])) {
    echo json_encode(array('result' => 'no_update'), JSON_UNESCAPED_UNICODE);
    exit;
}

$apk_url = ($row['apk_filename'] !== '')
    ? APK_BASE_URL . rawurlencode($row['apk_filename'])
    : '';

$channel = in_array($row['update_channel'], array('auto','apk','playstore'), true)
    ? $row['update_channel']
    : 'auto';

echo json_encode(array(
    'result'         => 'success',
    'version_code'   => (int)$row['version_code'],
    'version_name'   => (string)$row['version_name'],
    'apk_url'        => $apk_url,
    'update_channel' => $channel,
    'release_notes'  => (string)$row['release_notes'],
    'force_update'   => (bool)(int)$row['force_update'],
), JSON_UNESCAPED_UNICODE);
