<?php
require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../config/google_drive_helper.php';
requireLogin();

$message = '';
$error = '';

// 處理 OAuth callback
if (isset($_GET['code'])) {
    $code = $_GET['code'];

    $ch = curl_init('https://oauth2.googleapis.com/token');
    curl_setopt_array($ch, [
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => http_build_query([
            'code' => $code,
            'client_id' => GOOGLE_DRIVE_CLIENT_ID_DB,
            'client_secret' => GOOGLE_DRIVE_CLIENT_SECRET_DB,
            'redirect_uri' => GOOGLE_DRIVE_REDIRECT_URI,
            'grant_type' => 'authorization_code'
        ]),
        CURLOPT_RETURNTRANSFER => true
    ]);
    $response = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($http_code === 200) {
        $data = json_decode($response, true);
        $helper = new GoogleDriveHelper($pdo);
        $helper->saveTokens($data['access_token'], $data['refresh_token'], $data['expires_in']);

        // 建立應用程式資料夾
        $folderId = $helper->getOrCreateAppFolder();
        if ($folderId) {
            $message = 'Google Drive 授權成功！<a href="google_drive_docs.php" class="text-green-700 font-bold underline">前往雲端檔案總管</a>';
        } else {
            $message = 'Google Drive 授權成功！<a href="google_drive_docs.php" class="text-green-700 font-bold underline">前往雲端檔案總管</a>';
        }
    } else {
        $error = '授權失敗，請重試。';
    }
}

// 處理登出
if (isset($_GET['revoke'])) {
    $pdo->exec("DELETE FROM google_drive_tokens");
    $message = '已中斷 Google Drive 連線。';
}

// 檢查目前狀態
$pdo->exec("CREATE TABLE IF NOT EXISTS google_drive_tokens (
    id INT AUTO_INCREMENT PRIMARY KEY,
    access_token TEXT,
    refresh_token TEXT,
    expires_at DATETIME,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)");
$stmt = $pdo->query("SELECT * FROM google_drive_tokens ORDER BY id DESC LIMIT 1");
$token = $stmt->fetch();
$is_connected = !empty($token);

include __DIR__ . '/../includes/header.php';
?>

<div class="mb-8">
    <h1 class="text-2xl font-bold text-slate-800">Google Drive 設定</h1>
    <p class="text-slate-500">連接 Google Drive 作為地盤文件的雲端儲存空間</p>
</div>

<?php if ($message): ?>
    <div class="bg-green-50 text-green-600 p-4 rounded-lg mb-6 flex items-center">
        <i class="fas fa-check-circle mr-2"></i> <?php echo $message; ?>
    </div>
<?php endif; ?>

<?php if ($error): ?>
    <div class="bg-red-50 text-red-600 p-4 rounded-lg mb-6 flex items-center">
        <i class="fas fa-exclamation-circle mr-2"></i> <?php echo $error; ?>
    </div>
<?php endif; ?>

<div class="grid grid-cols-1 lg:grid-cols-2 gap-8">
    <!-- 連線狀態 -->
    <div class="bg-white rounded-2xl shadow-sm border border-slate-100 p-8">
        <h2 class="text-lg font-bold text-slate-800 mb-4">連線狀態</h2>
        <?php if ($is_connected): ?>
            <div class="flex items-center gap-3 mb-6">
                <div class="w-12 h-12 rounded-full bg-green-100 flex items-center justify-center">
                    <i class="fas fa-check-circle text-green-500 text-2xl"></i>
                </div>
                <div>
                    <p class="text-green-700 font-bold">已連線 Google Drive</p>
                    <p class="text-xs text-slate-500 mt-1">Token 有效至：<?php echo htmlspecialchars($token['expires_at']); ?></p>
                </div>
            </div>
            <?php if (!empty(GOOGLE_DRIVE_CLIENT_ID_DB)): ?>
                <div class="mb-4 p-3 bg-blue-50 border border-blue-100 rounded-lg text-xs text-blue-700 flex items-start gap-2">
                    <i class="fas fa-info-circle mt-0.5"></i>
                    <div>
                        <p class="font-medium">已啟用雲端檔案瀏覽功能</p>
                        <p class="mt-0.5">現在切換到地盤文件的「雲端」模式，即可直接瀏覽您的 Google Drive 資料夾結構。</p>
                    </div>
                </div>
            <?php endif; ?>
            <a href="?revoke=1" onclick="return confirm('確定要中斷 Google Drive 連線？')" class="inline-flex items-center gap-2 text-red-500 hover:text-red-700 text-sm font-medium">
                <i class="fas fa-unlink"></i> 中斷連線
            </a>
        <?php else: ?>
            <div class="flex items-center gap-3 mb-6">
                <div class="w-12 h-12 rounded-full bg-slate-100 flex items-center justify-center">
                    <i class="fas fa-cloud text-slate-400 text-2xl"></i>
                </div>
                <div>
                    <p class="text-slate-700 font-medium">未連線</p>
                    <p class="text-xs text-slate-500">尚未連接 Google Drive 帳戶</p>
                </div>
            </div>
            <?php if (!empty(GOOGLE_DRIVE_CLIENT_ID_DB)): ?>
                <a href="<?php echo GoogleDriveHelper::getAuthUrl(); ?>" class="inline-flex items-center gap-2 bg-blue-600 text-white px-6 py-3 rounded-xl font-bold hover:bg-blue-700 transition shadow-lg">
                    <i class="fab fa-google"></i> 連線 Google Drive
                </a>
            <?php else: ?>
                <div class="bg-amber-50 border border-amber-200 rounded-xl p-4 text-sm text-amber-700">
                    <p class="font-bold mb-2"><i class="fas fa-exclamation-triangle mr-1"></i> 尚未設定 API 憑證</p>
                    <p>請先到「系統設定」頁面填入 Google Drive 用戶端 ID 及用戶端密碼。</p>
                    <a href="settings.php" class="text-amber-800 font-bold underline mt-2 inline-block">前往系統設定</a>
                </div>
            <?php endif; ?>
        <?php endif; ?>
    </div>

    <!-- 設定說明 -->
    <div class="bg-white rounded-2xl shadow-sm border border-slate-100 p-8">
        <h2 class="text-lg font-bold text-slate-800 mb-4">設定步驟</h2>
        <ol class="space-y-4 text-sm text-slate-600">
            <li class="flex items-start gap-3">
                <span class="w-6 h-6 rounded-full bg-blue-100 text-blue-600 flex items-center justify-center text-xs font-bold flex-shrink-0">1</span>
                <div>
                    <p class="font-bold text-slate-700">前往 Google Cloud Console</p>
                    <p>到 <a href="https://console.cloud.google.com" target="_blank" class="text-blue-500 hover:underline">console.cloud.google.com</a> 建立新專案</p>
                </div>
            </li>
            <li class="flex items-start gap-3">
                <span class="w-6 h-6 rounded-full bg-blue-100 text-blue-600 flex items-center justify-center text-xs font-bold flex-shrink-0">2</span>
                <div>
                    <p class="font-bold text-slate-700">啟用 Google Drive API</p>
                    <p>在「API 和服務」→「圖書庫」搜尋「Google Drive API」並啟用</p>
                </div>
            </li>
            <li class="flex items-start gap-3">
                <span class="w-6 h-6 rounded-full bg-blue-100 text-blue-600 flex items-center justify-center text-xs font-bold flex-shrink-0">3</span>
                <div>
                    <p class="font-bold text-slate-700">建立 OAuth 2.0 憑證</p>
                    <p>「API 和服務」→「憑證」→「建立憑證」→「OAuth 用戶端 ID」<br>
                    應用類型選「網頁應用」，授權重新導向 URI 填入：</p>
                    <code class="block bg-slate-100 text-xs p-2 rounded mt-1 break-all"><?php echo GOOGLE_DRIVE_REDIRECT_URI; ?></code>
                </div>
            </li>
            <li class="flex items-start gap-3">
                <span class="w-6 h-6 rounded-full bg-blue-100 text-blue-600 flex items-center justify-center text-xs font-bold flex-shrink-0">4</span>
                <div>
                    <p class="font-bold text-slate-700">填入 config.php</p>
                    <p>複製「用戶端 ID」及「用戶端密碼」，填入 config.php 中的</p>
                    <code class="block bg-slate-100 text-xs p-2 rounded mt-1">GOOGLE_DRIVE_CLIENT_ID</code>
                    <code class="block bg-slate-100 text-xs p-2 rounded mt-1">GOOGLE_DRIVE_CLIENT_SECRET</code>
                </div>
            </li>
        </ol>
    </div>
</div>

<!-- 使用說明 -->
<div class="bg-white rounded-2xl shadow-sm border border-slate-100 p-8 mt-6">
    <h2 class="text-lg font-bold text-slate-800 mb-4">如何使用</h2>
    <div class="grid grid-cols-1 md:grid-cols-3 gap-6 text-sm">
        <div class="bg-slate-50 rounded-xl p-4">
            <i class="fas fa-cloud-upload-alt text-blue-500 text-xl mb-2 block"></i>
            <p class="font-bold text-slate-700 mb-1">上傳到雲端</p>
            <p class="text-slate-500">在地盤文件頁面切換到 Google Drive 模式，上傳的檔案會直接存入您的 Google Drive</p>
        </div>
        <div class="bg-slate-50 rounded-xl p-4">
            <i class="fas fa-folder-open text-green-500 text-xl mb-2 block"></i>
            <p class="font-bold text-slate-700 mb-1">瀏覽雲端檔案</p>
            <p class="text-slate-500">切換至雲端模式後，可直接瀏覽您 Google Drive 上的所有檔案和資料夾</p>
        </div>
        <div class="bg-slate-50 rounded-xl p-4">
            <i class="fas fa-sync-alt text-purple-500 text-xl mb-2 block"></i>
            <p class="font-bold text-slate-700 mb-1">隨處存取</p>
            <p class="text-slate-500">檔案存在您的 Google Drive，可直接在 Google Drive 網頁或手機 App 中查看</p>
        </div>
    </div>
</div>

<?php include __DIR__ . '/../includes/footer.php'; ?>
