<?php
@header("Cache-Control: no-cache, must-revalidate");  // 強烈清除緩存
@header("Content-Type: text/html; charset=utf-8");
@header('Content-Type: application/json; charset=UTF-8');
ob_start();
session_start();

include_once  'azure_db.php';
date_default_timezone_set('Asia/Taipei');

header('Content-Type: text/html; charset=utf-8');
  


// 從環境變量獲取資料庫連接資訊, 在hanyu_e 平台會發生錯誤
/*
$dbHost = ""; //getenv('DB_HOST');
$dbName = ""; //getenv('DB_NAME');
$dbUser = ""; // getenv('DB_USER');
$dbPassword = ""; //getenv('DB_PASSWORD');
*/
/* $dbhost =  getenv('dbhost');
$dbname =  getenv('dbname'); //$_ENV['dbname'];
$dbusername =  getenv('dbusername');
$dbpassword = getenv('dbpassword'); */

try {
    // 建立 PDO 連接
    $conn = new PDO("mysql:host=$dbhost;dbname=$dbname;charset=utf8", $dbusername, $dbpassword);
    // 設定 PDO 錯誤模式為異常
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

} catch (PDOException $e) {
    echo "連接失敗: " . $e->getMessage();
}

$today = date("Y-m-d"); // 獲取今天的日期
$now = date("Y-m-d H:i:s"); // 獲取當前時間
$oneHourLater = date("Y-m-d H:i:s", strtotime($now . " +1 hour")); // 当前时间加一个小时
$oneHourBefore = date("Y-m-d H:i:s", strtotime($now . " -1 hour")); // 当前时间加一个小时
$nextYear = date("Y-m-d", strtotime($today . " +1 year")); // 當前日期加上一年
$lastWeek = date("Y-m-d", strtotime($today . " -7 days")); // 當前日期的前一週
$yesterday = date("Y-m-d", strtotime($today . " -1 days")); // 當前日期的前一天
$mSysAdmin = $_SESSION['Nchc_role'] ?? "user";
// 生成 CSRF token
if (empty($_SESSION['csrfToken'])) {
    $_SESSION['csrfToken'] = bin2hex(random_bytes(32));
}

if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
    $client_ip = $_SERVER['HTTP_CLIENT_IP'];
} else if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
    $client_ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
    $client_ip = $_SERVER['REMOTE_ADDR'];
}

function base64url_encode($data)
{
    return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
}

function base64url_decode($data)
{
    return base64_decode(str_pad(strtr($data, '-_', '+/'), strlen($data) % 4, '=', STR_PAD_RIGHT));
}
