<?php
class TelegramAuth {
    private $botToken;
    private $chatId;
    private $apiUrl = 'https://api.telegram.org/bot';

    public function __construct($botToken, $chatId) {
        $this->botToken = $botToken;
        $this->chatId = $chatId;
    }

    public function generateOTP($length = 6) {
        return str_pad(random_int(0, pow(10, $length) - 1), $length, '0', STR_PAD_LEFT);
    }

    public function sendOTP($otp) {
        $message = "🔐 *SSA Dashboard*\n\n";
        $message .= "Your verification code is: `$otp`\n\n";
        $message .= "⚠️ This code will expire in 5 minutes.\n";
        $message .= "🌐 IP: " . $_SERVER['REMOTE_ADDR'] . "\n";
        $message .= "⏰ Time: " . date('Y-m-d H:i:s') . "\n";

        $params = [
            'chat_id' => $this->chatId,
            'text' => $message,
            'parse_mode' => 'Markdown'
        ];

        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_URL => $this->apiUrl . $this->botToken . '/sendMessage',
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => $params,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_SSL_VERIFYPEER => true
        ]);
        
        $response = curl_exec($ch);
        $error = curl_error($ch);
        curl_close($ch);

        if ($error) {
            error_log("Telegram Error: $error");
            return false;
        }

        $result = json_decode($response, true);
        return isset($result['ok']) && $result['ok'] === true;
    }

    public function verifyOTP($inputOTP, $storedOTP, $timestamp) {
        if (time() - $timestamp > 300) {
            return ['success' => false, 'message' => 'Verification code has expired'];
        }

        if ($inputOTP === $storedOTP) {
            return ['success' => true, 'message' => 'Verification successful'];
        }

        return ['success' => false, 'message' => 'Invalid verification code'];
    }
}
?>