<?php
// 資料庫配置
define('DB_HOST', 'localhost');
define('DB_USER', 'root');
define('DB_PASS', '');
define('DB_NAME', 'renovation_mgmt');

// 系統配置
define('APP_NAME', '香港裝修工程管理系統');

// 自動偵測 BASE_URL
$protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http";
$host = $_SERVER['HTTP_HOST'];
$script_name = $_SERVER['SCRIPT_NAME'];
$base_dir = str_replace('\\', '/', dirname(dirname($script_name)));
$base_url = $protocol . "://" . $host . ($base_dir == '/' ? '' : $base_dir) . '/public';
define('BASE_URL', $base_url);

define('UPLOAD_DIR', __DIR__ . '/../uploads/');

// AI 配置 (DeepSeek API)
define('DEEPSEEK_API_KEY', 'sk-89bc548359db48a88de19f6c8f986fca');
define('DEEPSEEK_API_URL', 'https://api.deepseek.com/v1/chat/completions');

// Google Drive 配置
define('GOOGLE_DRIVE_CLIENT_ID', '488447071746-ar4q1ecmid14dk3hr2tof00odsm29og2.apps.googleusercontent.com');
define('GOOGLE_DRIVE_CLIENT_SECRET', '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');
define('GOOGLE_DRIVE_REDIRECT_URI', BASE_URL . '/google_drive_auth.php');
define('GOOGLE_DRIVE_FOLDER_NAME', '裝修管理系統文件');

// 建立資料庫連接
try {
    $pdo = new PDO("mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . ";charset=utf8mb4", DB_USER, DB_PASS);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    die("資料庫連接失敗: " . $e->getMessage());
}

// 啟動 Session
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

// 從資料庫載入設定（覆蓋 config.php 中的靜態設定）
try {
    if (isset($pdo)) {
        $stmt = $pdo->query("SELECT setting_key, setting_value FROM app_settings");
        $dbSettings = $stmt->fetchAll();
        $settingMap = [];
        foreach ($dbSettings as $s) {
            $settingMap[$s['setting_key']] = $s['setting_value'];
        }
        if (!empty($settingMap['deepseek_api_key'])) {
            define('DEEPSEEK_API_KEY_DB', $settingMap['deepseek_api_key']);
        } else {
            define('DEEPSEEK_API_KEY_DB', DEEPSEEK_API_KEY);
        }
        if (!empty($settingMap['google_drive_client_id'])) {
            define('GOOGLE_DRIVE_CLIENT_ID_DB', $settingMap['google_drive_client_id']);
        } else {
            define('GOOGLE_DRIVE_CLIENT_ID_DB', GOOGLE_DRIVE_CLIENT_ID);
        }
        if (!empty($settingMap['google_drive_client_secret'])) {
            define('GOOGLE_DRIVE_CLIENT_SECRET_DB', $settingMap['google_drive_client_secret']);
        } else {
            define('GOOGLE_DRIVE_CLIENT_SECRET_DB', GOOGLE_DRIVE_CLIENT_SECRET);
        }
    } else {
        define('DEEPSEEK_API_KEY_DB', DEEPSEEK_API_KEY);
        define('GOOGLE_DRIVE_CLIENT_ID_DB', GOOGLE_DRIVE_CLIENT_ID);
        define('GOOGLE_DRIVE_CLIENT_SECRET_DB', GOOGLE_DRIVE_CLIENT_SECRET);
    }
} catch (Exception $e) {
    define('DEEPSEEK_API_KEY_DB', DEEPSEEK_API_KEY);
    define('GOOGLE_DRIVE_CLIENT_ID_DB', GOOGLE_DRIVE_CLIENT_ID);
    define('GOOGLE_DRIVE_CLIENT_SECRET_DB', GOOGLE_DRIVE_CLIENT_SECRET);
}

// 常用函數
function redirect($path) {
    header("Location: " . BASE_URL . $path);
    exit();
}

function isLoggedIn() {
    return isset($_SESSION['admin_id']);
}

function requireLogin() {
    if (!isLoggedIn()) {
        redirect('/login.php');
    }
}

function format_amount($amount) {
    if ($amount == floor($amount)) {
        return number_format($amount, 0);
    }
    $formatted = number_format($amount, 2, '.', '');
    return rtrim(rtrim($formatted, '0'), '.');
}
?>
