<?php

declare(strict_types=1);

require_once __DIR__ . DIRECTORY_SEPARATOR . 'auth.php';
require_once __DIR__ . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'layout.php';
require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_adsense.php';
require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_member_email.php';

fate_admin_require_login();

$error = null;
$notice = null;
$saved = isset($_GET['saved']) && $_GET['saved'] === '1';
$uploaded = isset($_GET['uploaded']) && $_GET['uploaded'] === '1';
$deleted = isset($_GET['deleted']) && $_GET['deleted'] === '1';

$stored = fate_adsense_normalize(fate_adsense_read());
$resolved = fate_adsense_resolved();
$envPub = fate_adsense_env_publisher_id();
$envEnabled = fate_adsense_env_enabled_locked();
$locked = $envPub !== '' || $envEnabled !== null;

$siteOrigin = fate_public_site_absolute_base()['origin'] ?? '';
if ($siteOrigin === '' && isset($_SERVER['HTTP_HOST'])) {
    $scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
    $siteOrigin = $scheme . '://' . trim((string) $_SERVER['HTTP_HOST']);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $csrf = isset($_POST['csrf']) && is_string($_POST['csrf']) ? $_POST['csrf'] : '';
    if (!fate_admin_csrf_check($csrf)) {
        $error = '工作階段逾期或驗證失敗，請重新整理後再試。';
    } else {
        $action = isset($_POST['action']) && is_string($_POST['action']) ? $_POST['action'] : 'save';

        if ($action === 'delete_verify') {
            $name = isset($_POST['verify_name']) && is_string($_POST['verify_name']) ? $_POST['verify_name'] : '';
            $del = fate_adsense_verify_delete($name);
            if (!$del['ok']) {
                $error = $del['error'] ?? '刪除失敗';
            } else {
                header('Location: adsense.php?deleted=1', true, 302);
                exit;
            }
        } elseif ($action === 'upload_verify') {
            if (!isset($_FILES['verify_file']) || !is_array($_FILES['verify_file'])) {
                $error = '請選擇要上傳的驗證檔。';
            } else {
                $f = $_FILES['verify_file'];
                $errCode = (int) ($f['error'] ?? UPLOAD_ERR_NO_FILE);
                if ($errCode !== UPLOAD_ERR_OK) {
                    $error = $errCode === UPLOAD_ERR_NO_FILE ? '未選擇檔案' : '上傳失敗（錯誤碼 ' . $errCode . '）';
                } else {
                    $tmp = (string) ($f['tmp_name'] ?? '');
                    $orig = (string) ($f['name'] ?? '');
                    $content = is_file($tmp) ? (string) file_get_contents($tmp) : '';
                    $up = fate_adsense_verify_upload($orig, $content);
                    if (!$up['ok']) {
                        $error = $up['error'] ?? '上傳失敗';
                    } else {
                        header('Location: adsense.php?uploaded=1', true, 302);
                        exit;
                    }
                }
            }
        } else {
            $result = fate_adsense_save_admin_post($_POST);
            if (!$result['ok']) {
                $error = $result['error'] ?? '儲存失敗';
                $stored = fate_adsense_normalize(array_merge($stored, [
                    'enabled' => !empty($_POST['adsense_enabled']),
                    'skip_admin' => !isset($_POST['adsense_skip_admin']) || !empty($_POST['adsense_skip_admin']),
                    'publisher_id' => isset($_POST['publisher_id']) && is_string($_POST['publisher_id'])
                        ? $_POST['publisher_id'] : $stored['publisher_id'],
                ]));
            } else {
                header('Location: adsense.php?saved=1', true, 302);
                exit;
            }
        }
    }
}

$verifyFiles = fate_adsense_verify_list();
$csrf = fate_admin_csrf_token();
$displayPub = $resolved['publisher_id'] !== '' ? $resolved['publisher_id'] : $stored['publisher_id'];
$renderOn = fate_adsense_should_render();

fate_admin_layout_start(['page' => 'Google AdSense', 'active' => 'adsense', 'body_class' => 'admin-body--adsense']);
?>
        <header class="page-head">
            <h1 class="page-title">Google AdSense</h1>
            <p class="sub">
                設定<strong>自動廣告</strong>程式碼（全站一組 <code>ca-pub-</code>），並上傳 Google 提供的<strong>網站驗證檔</strong>至站台根目錄。
                設定檔：<code>fate/data/fate_adsense.json</code>；驗證檔備份：<code>fate/data/adsense_verify/</code>。
                環境變數 <code>FATE_ADSENSE_PUBLISHER_ID</code>、<code>FATE_ADSENSE_ENABLED</code> 優先於檔案。
            </p>
        </header>

        <?php if ($saved): ?>
            <div class="msg ok">AdSense 設定已儲存。</div>
        <?php endif; ?>
        <?php if ($uploaded): ?>
            <div class="msg ok">驗證檔已上傳並發布至站台根目錄。</div>
        <?php endif; ?>
        <?php if ($deleted): ?>
            <div class="msg ok">已刪除驗證檔。</div>
        <?php endif; ?>
        <?php if ($error !== null): ?>
            <div class="msg bad"><?= htmlspecialchars($error, ENT_QUOTES, 'UTF-8') ?></div>
        <?php endif; ?>

        <div class="card">
            <h2 class="card-title">申請與操作說明（官方連結）</h2>
            <ul class="api-key-links">
                <?php foreach (fate_adsense_admin_links() as $link): ?>
                    <li>
                        <a href="<?= htmlspecialchars($link['url'], ENT_QUOTES, 'UTF-8') ?>" target="_blank" rel="noopener noreferrer"><?= htmlspecialchars($link['label'], ENT_QUOTES, 'UTF-8') ?></a>
                        <?php if (!empty($link['hint'])): ?>
                            <span class="sub"> — <?= htmlspecialchars($link['hint'], ENT_QUOTES, 'UTF-8') ?></span>
                        <?php endif; ?>
                    </li>
                <?php endforeach; ?>
            </ul>
            <?php if ($siteOrigin !== ''): ?>
                <p class="sub" style="margin-bottom:0;margin-top:0.75rem;">
                    本站對外網址（申請 AdSense 時請填此網域）：<code><?= htmlspecialchars($siteOrigin, ENT_QUOTES, 'UTF-8') ?>/</code>
                    <?php if (getenv('FATE_PUBLIC_SITE_ORIGIN')): ?>
                        <span>（來自 <code>FATE_PUBLIC_SITE_ORIGIN</code>）</span>
                    <?php endif; ?>
                </p>
            <?php endif; ?>
        </div>

        <div class="card">
            <h2 class="card-title">目前狀態</h2>
            <dl class="row">
                <div class="stat">
                    <dt>自動廣告</dt>
                    <dd><?= $renderOn ? '已啟用（前台會載入 script）' : '未啟用或未設定發布商 ID' ?></dd>
                </div>
                <div class="stat">
                    <dt>發布商 ID</dt>
                    <dd><code><?= $displayPub !== '' ? htmlspecialchars($displayPub, ENT_QUOTES, 'UTF-8') : '（未設定）' ?></code></dd>
                </div>
                <div class="stat">
                    <dt>設定來源</dt>
                    <dd><?= htmlspecialchars($resolved['source'] === 'env' ? '環境變數' : 'fate_adsense.json', ENT_QUOTES, 'UTF-8') ?></dd>
                </div>
                <div class="stat">
                    <dt>驗證檔</dt>
                    <dd><?= count($verifyFiles) ?> 個</dd>
                </div>
            </dl>
        </div>

        <form method="post" action="adsense.php" class="stack-form">
            <input type="hidden" name="csrf" value="<?= htmlspecialchars($csrf, ENT_QUOTES, 'UTF-8') ?>">
            <input type="hidden" name="action" value="save">

            <div class="card">
                <h2 class="card-title">自動廣告程式碼</h2>
                <p class="sub" style="margin-top:0;">
                    通過 AdSense 審核後，於主控台取得<strong>發布商 ID</strong>（<code>ca-pub-xxxxxxxxxxxxxxxx</code>），或複製「自動廣告」提供的整段 <code>&lt;script&gt;</code> 貼入下方，系統會自動擷取 <code>client=</code> 參數。
                    啟用後會插入於前台模版 <code>&lt;head&gt;</code>（預設不含 <code>/admin</code> 後台）。
                </p>
                <?php if ($locked): ?>
                    <div class="msg warn">部分設定由環境變數鎖定，此頁表單無法覆寫。</div>
                <?php endif; ?>
                <div class="field-grid">
                    <div class="field field--full">
                        <label class="checkbox-label">
                            <input type="checkbox" name="adsense_enabled" value="1"
                                <?= !empty($resolved['enabled']) ? 'checked' : '' ?>
                                <?= $locked ? 'disabled' : '' ?>>
                            啟用 Google AdSense 自動廣告
                        </label>
                    </div>
                    <div class="field field--full">
                        <label class="checkbox-label">
                            <input type="checkbox" name="adsense_skip_admin" value="1"
                                <?= !empty($resolved['skip_admin']) ? 'checked' : '' ?>
                                <?= $locked ? 'disabled' : '' ?>>
                            不在後台路徑（<code>/admin</code>）載入廣告
                        </label>
                    </div>
                    <div class="field field--full">
                        <label for="publisher_id">發布商 ID 或官方 script 片段</label>
                        <textarea name="publisher_id" id="publisher_id" rows="4" class="mono-input"
                                  placeholder="ca-pub-1234567890123456 或貼上 adsbygoogle.js 的 &lt;script&gt;…"
                                  <?= $locked ? 'readonly' : '' ?>><?= htmlspecialchars($displayPub, ENT_QUOTES, 'UTF-8') ?></textarea>
                        <p class="sub">留空且未勾選啟用時，保留檔案內既有 ID 不變；若要清除 ID 請先取消啟用並改貼新值覆寫。</p>
                    </div>
                </div>
                <?php if (!$locked): ?>
                    <p><button type="submit" class="btn">儲存 AdSense 設定</button></p>
                <?php endif; ?>
            </div>
        </form>

        <form method="post" action="adsense.php" enctype="multipart/form-data" class="stack-form">
            <input type="hidden" name="csrf" value="<?= htmlspecialchars($csrf, ENT_QUOTES, 'UTF-8') ?>">
            <input type="hidden" name="action" value="upload_verify">

            <div class="card">
                <h2 class="card-title">網站驗證檔上傳</h2>
                <p class="sub" style="margin-top:0;">
                    在 AdSense「新增網站」時若選擇<strong>HTML 檔案</strong>驗證，請下載 Google 提供的檔案（檔名通常為 <code>google….html</code>），在此上傳。
                    系統會寫入站台根目錄，使網址形如
                    <?php if ($siteOrigin !== ''): ?>
                        <code><?= htmlspecialchars($siteOrigin, ENT_QUOTES, 'UTF-8') ?>/google….html</code>
                    <?php else: ?>
                        <code>https://您的網域/google….html</code>
                    <?php endif; ?>
                    可被 Google 存取。完成驗證後可保留或刪除檔案。
                    若要求 <code>ads.txt</code> 亦可上傳。
                </p>
                <div class="field field--full">
                    <label for="verify_file">選擇驗證檔</label>
                    <input type="file" name="verify_file" id="verify_file" accept=".html,.txt,text/html,text/plain" required>
                </div>
                <p><button type="submit" class="btn btn--secondary">上傳並發布至網站根目錄</button></p>
            </div>
        </form>

        <div class="card">
            <h2 class="card-title">已上傳的驗證檔</h2>
            <?php if ($verifyFiles === []): ?>
                <p class="sub">尚無驗證檔。請依 AdSense 主控台指示上傳。</p>
            <?php else: ?>
                <div class="table-wrap">
                    <table class="adsense-verify-table">
                        <thead>
                            <tr>
                                <th>檔名</th>
                                <th>公開網址</th>
                                <th>根目錄</th>
                                <th>上傳時間</th>
                                <th></th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($verifyFiles as $vf): ?>
                                <tr>
                                    <td><code><?= htmlspecialchars($vf['name'], ENT_QUOTES, 'UTF-8') ?></code></td>
                                    <td>
                                        <a href="<?= htmlspecialchars($vf['public_url'], ENT_QUOTES, 'UTF-8') ?>" target="_blank" rel="noopener noreferrer">開啟</a>
                                    </td>
                                    <td><?= !empty($vf['web_ok']) ? '✓ 可存取' : '<span class="text-warn">缺少</span>' ?></td>
                                    <td><?= htmlspecialchars($vf['uploaded_at'], ENT_QUOTES, 'UTF-8') ?></td>
                                    <td>
                                        <form method="post" action="adsense.php" class="inline-form" onsubmit="return confirm('確定刪除此驗證檔？');">
                                            <input type="hidden" name="csrf" value="<?= htmlspecialchars($csrf, ENT_QUOTES, 'UTF-8') ?>">
                                            <input type="hidden" name="action" value="delete_verify">
                                            <input type="hidden" name="verify_name" value="<?= htmlspecialchars($vf['name'], ENT_QUOTES, 'UTF-8') ?>">
                                            <button type="submit" class="btn btn-sm btn--danger">刪除</button>
                                        </form>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </div>

        <div class="card">
            <h2 class="card-title">操作步驟（建議順序）</h2>
            <ol class="sub ordered-steps">
                <li>至 <a href="https://www.google.com/adsense/start/" target="_blank" rel="noopener noreferrer">Google AdSense</a> 申請並登入帳號。</li>
                <li>在「網站」新增本站網址（例：<code><?= htmlspecialchars($siteOrigin !== '' ? $siteOrigin : 'https://fate.novice.tw', ENT_QUOTES, 'UTF-8') ?>/</code>）。</li>
                <li>選擇 <strong>HTML 檔案</strong> 驗證方式 → 下載檔案 → 於本頁<strong>上傳驗證檔</strong> → 在 AdSense 按「驗證」。</li>
                <li>審核通過後，於 AdSense 開啟<strong>自動廣告</strong>，複製含 <code>ca-pub-</code> 的程式碼或 ID → 貼至上方並<strong>啟用</strong> → 儲存。</li>
                <li>重新整理前台首頁，以瀏覽器開發者工具確認已載入 <code>pagead2.googlesyndication.com</code> 的 script（政策允許後才會顯示廣告）。</li>
            </ol>
        </div>
<?php
fate_admin_layout_end();
