<?php
session_start();
include_once "./bkashconfig.php";

// Clear existing token
$_SESSION['id_token'] = null;

$post_token = array(
    'app_key' => APPKEY,
    'app_secret' => APPSECRET
);

$url = curl_init(BASEURL."/tokenized/checkout/token/grant");

$post_token_json = json_encode($post_token);

$header = array(
    'Content-Type: application/json',
    "username:".USERNAME,
    "password:".PASSWORD
);

curl_setopt($url, CURLOPT_HTTPHEADER, $header);
curl_setopt($url, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($url, CURLOPT_RETURNTRANSFER, true);
curl_setopt($url, CURLOPT_POSTFIELDS, $post_token_json);
curl_setopt($url, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($url, CURLOPT_TIMEOUT, 30);

$result_data = curl_exec($url);
$http_code = curl_getinfo($url, CURLINFO_HTTP_CODE);
curl_close($url);

$response = json_decode($result_data, true);

if ($http_code == 200 && isset($response['id_token'])) {
    $_SESSION['id_token'] = $response['id_token'];
    $_SESSION['token_type'] = $response['token_type'] ?? '';
    $_SESSION['expires_in'] = $response['expires_in'] ?? 3600;
    
    // Return success response
    echo "success";
} else {
    // Return error message
    if (isset($response['msg'])) {
        echo "Error: " . $response['msg'];
    } else if (isset($response['errorMessage'])) {
        echo "Error: " . $response['errorMessage'];
    } else {
        echo "Token generation failed. HTTP Code: " . $http_code;
    }
}
?>