<?php

include_once 'config.php';
include_once 'telegram.php';
include_once 'class.php';

$telegram = new telegram(TOKEN,HOST,USERNAME,PASSWORD,DBNAME);

$apiKey = "3eafdbb2f29c2c92719653a710828f00";

if(!isset($_GET['token'])){
    die("token not found");
}

$token = base64_decode($_GET['token']);

$explode = explode('.', $token);

$userid = $explode[0];
$fileid = $explode[1];

$file = $telegram->db->query("SELECT * FROM fl_file WHERE id='$fileid'")->fetch(2);

if(!$file){
    die("پلن یافت نشد");
}

$amount = intval($file['price']) * 10; // تومان به ریال

$hashId = "vpn_" . time() . "_" . $userid;

$callback = baseURI . "/tetra_verify.php";

$data = [
    "ApiKey" => $apiKey,
    "Hash_id" => $hashId,
    "Amount" => $amount,
    "Description" => "خرید سرویس VPN",
    "Email" => "user@example.com",
    "Mobile" => "09120000000",
    "CallbackURL" => $callback
];

$ch = curl_init("https://tetra98.com/api/create_order");

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "Content-Type: application/json"
]);

curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));

$response = curl_exec($ch);

curl_close($ch);

$result = json_decode($response, true);

if(isset($result['status']) && $result['status'] == "100"){

    $authority = $result['Authority'];

    // ذخیره سفارش
    $telegram->db->query("
        INSERT INTO tetra_payments 
        (userid,fileid,authority,hash_id,status,create_time)
        VALUES
        ('$userid','$fileid','$authority','$hashId','0',NOW())
    ");

    header("Location: ".$result['payment_url_web']);
    exit;

}else{

    echo "خطا در ایجاد پرداخت";
    echo "<pre>";
    print_r($result);

}