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

// 自動建立設定表
$pdo->exec("CREATE TABLE IF NOT EXISTS app_settings (
    id INT AUTO_INCREMENT PRIMARY KEY,
    setting_key VARCHAR(100) NOT NULL UNIQUE,
    setting_value TEXT,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)");

$success = '';
$error = '';

// 從資料庫載入設定
function getSetting($pdo, $key, $default = '') {
    $stmt = $pdo->prepare("SELECT setting_value FROM app_settings WHERE setting_key = ?");
    $stmt->execute([$key]);
    $row = $stmt->fetch();
    return $row ? $row['setting_value'] : $default;
}

function saveSetting($pdo, $key, $value) {
    $stmt = $pdo->prepare("INSERT INTO app_settings (setting_key, setting_value) VALUES (?, ?) ON DUPLICATE KEY UPDATE setting_value = ?");
    $stmt->execute([$key, $value, $value]);
}

// 處理儲存
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    if ($_POST['action'] === 'save_deepseek') {
        $key = trim($_POST['deepseek_api_key'] ?? '');
        saveSetting($pdo, 'deepseek_api_key', $key);
        define('DEEPSEEK_API_KEY', $key);
        $success = 'DeepSeek API Key 已更新';
    } elseif ($_POST['action'] === 'save_google_drive') {
        $client_id = trim($_POST['google_drive_client_id'] ?? '');
        $client_secret = trim($_POST['google_drive_client_secret'] ?? '');
        saveSetting($pdo, 'google_drive_client_id', $client_id);
        saveSetting($pdo, 'google_drive_client_secret', $client_secret);
        $success = 'Google Drive 憑證已更新';
    } elseif ($_POST['action'] === 'revoke_google_drive') {
        $pdo->exec("DELETE FROM google_drive_tokens");
        $success = '已中斷 Google Drive 連線';
    }
}

// 讀取目前設定
$saved_deepseek_key = getSetting($pdo, 'deepseek_api_key', DEEPSEEK_API_KEY);
$saved_gd_client_id = getSetting($pdo, 'google_drive_client_id', GOOGLE_DRIVE_CLIENT_ID);
$saved_gd_client_secret = getSetting($pdo, 'google_drive_client_secret', GOOGLE_DRIVE_CLIENT_SECRET);

// 檢查 Google Drive 連線狀態
$gd_connected = false;
try {
    $stmt = $pdo->query("SELECT * FROM google_drive_tokens ORDER BY id DESC LIMIT 1");
    $token = $stmt->fetch();
    $gd_connected = !empty($token);
} catch (Exception $e) {}

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

<div class="mb-8">
    <h1 class="text-2xl font-bold text-slate-800">系統設定</h1>
    <p class="text-slate-500">管理 API 金鑰及外部服務連線</p>
</div>

<?php if ($success): ?>
    <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 $success; ?>
    </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">
    <!-- DeepSeek AI 設定 -->
    <div class="bg-white rounded-2xl shadow-sm border border-slate-100 p-8">
        <div class="flex items-center gap-3 mb-6">
            <div class="w-10 h-10 rounded-xl bg-purple-100 flex items-center justify-center">
                <i class="fas fa-robot text-purple-600"></i>
            </div>
            <div>
                <h2 class="text-lg font-bold text-slate-800">DeepSeek AI</h2>
                <p class="text-xs text-slate-500">用於報價單生成、開工登記、工程總結等 AI 功能</p>
            </div>
        </div>
        <form action="settings.php" method="POST" class="space-y-4">
            <input type="hidden" name="action" value="save_deepseek">
            <div>
                <label class="block text-sm font-medium text-slate-700 mb-1">API Key</label>
                <div class="relative">
                    <input type="password" name="deepseek_api_key" id="deepseek-key" value="<?php echo htmlspecialchars($saved_deepseek_key); ?>" placeholder="sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" class="w-full px-4 py-2.5 pr-10 border border-slate-200 rounded-lg outline-none focus:ring-2 focus:ring-purple-500 font-mono text-sm">
                    <button type="button" onclick="togglePassword('deepseek-key')" class="absolute right-3 top-2.5 text-slate-400 hover:text-slate-600">
                        <i class="fas fa-eye"></i>
                    </button>
                </div>
                <p class="text-xs text-slate-400 mt-1">到 <a href="https://platform.deepseek.com" target="_blank" class="text-purple-500 hover:underline">platform.deepseek.com</a> 取得</p>
            </div>
            <button type="submit" class="bg-purple-600 text-white px-6 py-2.5 rounded-lg font-bold hover:bg-purple-700 transition shadow-lg">儲存設定</button>
        </form>
    </div>

    <!-- Google Drive 設定 -->
    <div class="bg-white rounded-2xl shadow-sm border border-slate-100 p-8">
        <div class="flex items-center gap-3 mb-6">
            <div class="w-10 h-10 rounded-xl bg-blue-100 flex items-center justify-center">
                <i class="fab fa-google-drive text-blue-600"></i>
            </div>
            <div>
                <h2 class="text-lg font-bold text-slate-800">Google Drive</h2>
                <p class="text-xs text-slate-500">用於雲端檔案管理，檔案與你的 Google Drive 即時同步</p>
            </div>
        </div>

        <!-- 連線狀態 -->
        <div class="mb-6 p-4 rounded-xl <?php echo $gd_connected ? 'bg-green-50 border border-green-100' : 'bg-slate-50 border border-slate-100'; ?>">
            <div class="flex items-center justify-between">
                <div class="flex items-center gap-3">
                    <div class="w-8 h-8 rounded-full <?php echo $gd_connected ? 'bg-green-100' : 'bg-slate-200'; ?> flex items-center justify-center">
                        <i class="fas <?php echo $gd_connected ? 'fa-check-circle text-green-500' : 'fa-cloud text-slate-400'; ?>"></i>
                    </div>
                    <div>
                        <p class="text-sm font-bold <?php echo $gd_connected ? 'text-green-700' : 'text-slate-600'; ?>">
                            <?php echo $gd_connected ? '已連線 Google Drive' : '未連線'; ?>
                        </p>
                    </div>
                </div>
                <?php if ($gd_connected): ?>
                    <form action="settings.php" method="POST" onsubmit="return confirm('確定要中斷 Google Drive 連線？')">
                        <input type="hidden" name="action" value="revoke_google_drive">
                        <button type="submit" class="text-xs text-red-500 hover:text-red-700 font-medium">中斷連線</button>
                    </form>
                <?php endif; ?>
            </div>
        </div>

        <form action="settings.php" method="POST" class="space-y-4">
            <input type="hidden" name="action" value="save_google_drive">
            <div>
                <label class="block text-sm font-medium text-slate-700 mb-1">用戶端 ID (Client ID)</label>
                <input type="text" name="google_drive_client_id" value="<?php echo htmlspecialchars($saved_gd_client_id); ?>" placeholder="123456789-xxxxx.apps.googleusercontent.com" class="w-full px-4 py-2.5 border border-slate-200 rounded-lg outline-none focus:ring-2 focus:ring-blue-500 font-mono text-sm">
            </div>
            <div>
                <label class="block text-sm font-medium text-slate-700 mb-1">用戶端密碼 (Client Secret)</label>
                <div class="relative">
                    <input type="password" name="google_drive_client_secret" id="gd-secret" value="<?php echo htmlspecialchars($saved_gd_client_secret); ?>" placeholder="GOCSPX-xxxxxxxxxxxxxxxx" class="w-full px-4 py-2.5 pr-10 border border-slate-200 rounded-lg outline-none focus:ring-2 focus:ring-blue-500 font-mono text-sm">
                    <button type="button" onclick="togglePassword('gd-secret')" class="absolute right-3 top-2.5 text-slate-400 hover:text-slate-600">
                        <i class="fas fa-eye"></i>
                    </button>
                </div>
            </div>
            <div class="flex items-center gap-3">
                <button type="submit" class="bg-blue-600 text-white px-6 py-2.5 rounded-lg font-bold hover:bg-blue-700 transition shadow-lg">儲存憑證</button>
                <?php if (!empty($saved_gd_client_id) && !empty($saved_gd_client_secret)): ?>
                    <a href="google_drive_auth.php" class="text-blue-600 hover:text-blue-800 text-sm font-medium">
                        <i class="fas fa-external-link-alt mr-1"></i> 前往授權
                    </a>
                <?php endif; ?>
            </div>
        </form>
    </div>
</div>

<!-- Google Drive 操作說明 -->
<?php if ($gd_connected): ?>
<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"><i class="fab fa-google-drive text-blue-500 mr-2"></i>Google Drive 雲端檔案</h2>
    <p class="text-sm text-slate-600 mb-4">已連線 Google Drive，你可以：</p>
    <div class="grid grid-cols-1 md:grid-cols-3 gap-4 text-sm">
        <div class="bg-blue-50 rounded-xl p-4">
            <i class="fas fa-folder-open text-blue-500 text-xl mb-2 block"></i>
            <p class="font-bold text-slate-700 mb-1">瀏覽雲端檔案</p>
            <p class="text-slate-500 text-xs">查看 Google Drive 上的所有資料夾和檔案</p>
        </div>
        <div class="bg-green-50 rounded-xl p-4">
            <i class="fas fa-upload text-green-500 text-xl mb-2 block"></i>
            <p class="font-bold text-slate-700 mb-1">上傳 / 新增</p>
            <p class="text-slate-500 text-xs">上傳檔案或新增資料夾，即時同步到 Google Drive</p>
        </div>
        <div class="bg-red-50 rounded-xl p-4">
            <i class="fas fa-trash-alt text-red-500 text-xl mb-2 block"></i>
            <p class="font-bold text-slate-700 mb-1">刪除同步</p>
            <p class="text-slate-500 text-xs">刪除操作會同步到 Google Drive</p>
        </div>
    </div>
    <a href="google_drive_docs.php" class="inline-flex items-center gap-2 mt-4 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-drive"></i> 開啟雲端檔案總管
    </a>
</div>
<?php endif; ?>

<script>
function togglePassword(id) {
    const input = document.getElementById(id);
    input.type = input.type === 'password' ? 'text' : 'password';
}
</script>

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