<?php

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

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

$apiKey = "3eafdbb2f29c2c92719653a710828f00";

$authority = $_POST['authority'];

if(!$authority){
    die("authority not found");
}

$data = [
    "authority" => $authority,
    "ApiKey" => $apiKey
];

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

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){

    $payment = $telegram->db->query("
        SELECT * FROM tetra_payments
        WHERE authority='$authority'
    ")->fetch(2);

    if(!$payment){
        die("payment not found");
    }

    if($payment['status'] == 1){
        die("قبلا تایید شده");
    }

    $telegram->db->query("
        UPDATE tetra_payments
        SET status='1'
        WHERE authority='$authority'
    ");

    $userid = $payment['userid'];
    $fileid = $payment['fileid'];

    // اینجا اکانت بساز
    // مثلا:
    // create_account($userid, $fileid);

    $telegram->sendMessage(
        $userid,
        "✅ پرداخت شما با موفقیت تایید شد"
    );

    echo "OK";

}else{

    echo "پرداخت ناموفق";

}