<?php
// 1. 設定 LINE Login API 的相關資訊
// v6.x.5 fallback:v6.4.0 helper /etc/evmorning-secrets.env 還沒 deploy 完
// 先回到 v6.3.20 的 inline creds,確保登入流程不中斷
// 等下次 v6.4.0 完整 deploy 再切回去(補 helper + env file + RUNBOOK §11.66)
$client_id     = '2004849982';
$client_secret = 'b2d118fbe274b95e9b3860f1cef16f26';
if (isset($_GET['return_url'])) {
    $redirect_uri = 'https://evmorning.com/Login.php?return_url=' . urlencode($_GET['return_url']);
} else {
    $redirect_uri = 'https://evmorning.com/Login.php';
}



// 2. 檢查是否有授權碼，如果有則處理登入流程
if (isset($_GET['code'])) {
    // 取得授權碼
    $code = $_GET['code'];

    // 使用授權碼換取存取權杖
    $token_url = 'https://api.line.me/oauth2/v2.1/token';
    $data = array(
        'grant_type' => 'authorization_code',
        'code' => $code,
        'client_id' => $client_id,
        'client_secret' => $client_secret,
        'redirect_uri' => $redirect_uri
    );

    $options = array(
        'http' => array(
            'method' => 'POST',
            'content' => http_build_query($data),
            'header' => "Content-Type: application/x-www-form-urlencoded\r\n"
        )
    );

    $context = stream_context_create($options);
    $response = file_get_contents($token_url, false, $context);
    $params = json_decode($response, true);

    // 取得存取權杖後，可以根據需要進一步處理，例如獲取使用者資訊等
    if (isset($params['access_token'])) {
        $access_token = $params['access_token'];

        //echo "Work.<br>";
        // 使用存取權杖向 LINE 平台發送請求，獲取使用者資訊
        $user_profile_url = 'https://api.line.me/v2/profile';
        $access_token = $params['access_token']; // 假設$params為之前獲取的存取權杖

        $options = array(
            'http' => array(
                'header' => "Authorization: Bearer $access_token"
            )
        );

        $context = stream_context_create($options);
        $response = file_get_contents($user_profile_url, false, $context);
        $user_profile = json_decode($response, true);

        /* Setting sha256 convert Cookie. */
        include "./api/cookie_care.php";
        setSecureCookie('userName', $user_profile['displayName'],   time() + (7 * 24 * 60 * 60));
        setSecureCookie('userId',   $user_profile['userId'],        time() + (7 * 24 * 60 * 60));
        setSecureCookie('photoUrl', $user_profile['pictureUrl'],    time() + (7 * 24 * 60 * 60));
        /* Set Done. */

        /* Sql Check */
        include "./api/connDB.php";
        $Check_User_Data = "SELECT * FROM user_account WHERE `line_userId` = '" . $user_profile['userId'] . "'";
        $Check_User_Data_result = mysqli_query($link, $Check_User_Data);
        if (mysqli_num_rows(mysqli_query($link, $Check_User_Data)) == 0) {
            $Create_Account_sql = "INSERT INTO `evmorning`.`user_account`(`line_name`, `line_userId`, `update_time`) 
            VALUE('" . $user_profile['displayName'] . "','" . $user_profile['userId'] . "','" . date('Y-m-d H:i:s') . "')";
            if (mysqli_query($link, $Create_Account_sql)) {
                $Check_User_Data_assoc = mysqli_fetch_assoc($Check_User_Data_result);
                setSecureCookie('uid', $Check_User_Data_assoc['uid'],    time() + (7 * 24 * 60 * 60));

                header("Location:https://liff.line.me/2004849982-ykl96Mpn");
            } else {
                echo "資料建立失敗";
            }
        } else {
            $Check_User_Data_assoc = mysqli_fetch_assoc($Check_User_Data_result);
            setSecureCookie('uid', $Check_User_Data_assoc['uid'],    time() + (7 * 24 * 60 * 60));
            if (isset($_GET['return_url'])) {
                switch ($_GET['return_url']) {
                    case 'ChargeMap.php':
                        header("Location:https://liff.line.me/2004849982-1KKX6wPz");
                        break;
                    case 'ChargeQRCode.php':
                        header("Location:https://liff.line.me/2004849982-5ZrBRJX1");
                        break;
                    case 'UserChargeControl.php':
                        header("Location:https://liff.line.me/2004849982-k8D6KyR2");
                        break;
                    case 'InstallAndFixreport.php':
                        header("Location:https://liff.line.me/2004849982-5K8B2eWm");
                        break;
                    case 'UserIndex.php':
                        header("Location:https://liff.line.me/2004849982-jZpExXly");
                        break;
                    case 'ChargeLog.php':
                        header("Location:./ChargeLog.php");
                        break;
                    default:
                        header("Location:https://liff.line.me/2004849982-jZpExXly");
                        break;
                }
            } else {
                header("Location:https://liff.line.me/2004849982-jZpExXly");
            }
        }
    } else {
        // 登入失敗，處理錯誤情況
        echo "登入失敗";
    }
} else {
    // 3. 如果沒有授權碼，則導向到 LINE 登入頁面
    $login_url = 'https://access.line.me/oauth2/v2.1/authorize?' . http_build_query(array(
        'response_type' => 'code',
        'client_id' => $client_id,
        'redirect_uri' => $redirect_uri,
        'state' => 'random_state',
        'scope' => 'openid profile'
    ));
    header('Location: ' . $login_url);
    exit();
}
