<?php
session_start();

// ম্যাডেলিনপ্রো লোকেশন
$madelineProtoPath = __DIR__ . '/vendor/autoload.php';
if (file_exists($madelineProtoPath)) {
    require_once $madelineProtoPath;
} else {
    require_once __DIR__ . '/../vendor/autoload.php';
}

use danog\MadelineProto\API;

$targetBotUsername = "@ResetDrip_bot";
$sessionFile = 'session.madeline';
$message = "";
$msgType = "";

if ($_SERVER["REQUEST_METHOD"] == "POST" && !empty($_POST['voucher_code'])) {
    $voucher = trim($_POST['voucher_code']);
    
    if (strlen($voucher) !== 10) {
        $message = "O código deve ter exatamente 10 caracteres.";
        $msgType = "error";
    } else {
        try {
            $settings = (new \danog\MadelineProto\Settings\AppInfo)
                ->setApiId(27109040)
                ->setApiHash('92ed09c7586eedc48395d3cd59960fe1');
            
            $mp = new API($sessionFile, $settings);
            $mp->start();

            // বটে মেসেজ পাঠানো
            $mp->messages->sendMessage(['peer' => $targetBotUsername, 'message' => $voucher]);

            // প্রথমে কিছুক্ষণ অপেক্ষা করা (বটের প্রসেসিং মেসেজ আসার জন্য)
            sleep(3);
            
            $finalReply = "";
            $lastMessage = "";
            $attempts = 0;
            $maxAttempts = 12; // 12 সেকেন্ড পর্যন্ত অপেক্ষা করবে
            
            // বটের ফাইনাল রেসপন্স পাওয়া পর্যন্ত অপেক্ষা করা
            while ($attempts < $maxAttempts) {
                sleep(1);
                $attempts++;
                
                $messages = $mp->messages->getHistory([
                    'peer' => $targetBotUsername, 
                    'limit' => 3 // শেষের ৩টি মেসেজ চেক করা
                ]);
                
                if (isset($messages['messages'])) {
                    // আউটগোয়িং নয় এমন মেসেজ খুঁজে বের করা (বটের মেসেজ)
                    foreach ($messages['messages'] as $msg) {
                        if (!$msg['out'] && isset($msg['message']) && !empty($msg['message'])) {
                            $currentMessage = $msg['message'];
                            
                            // শুধু প্রসেসিং মেসেজ স্কিপ করা (এগুলো টেম্পরারি)
                            if (strpos($currentMessage, 'PROCESSING KEY') === false && 
                                strpos($currentMessage, 'Authenticating') === false &&
                                $currentMessage !== $lastMessage) {
                                
                                $lastMessage = $currentMessage;
                                
                                // যদি সত্যিকারের রেসপন্স পাই (সাক্সেস/ফেইল্ড)
                                if (strpos($currentMessage, 'RESET SUCCESSFUL') !== false || 
                                    strpos($currentMessage, 'RESET FAILED') !== false ||
                                    strpos($currentMessage, '✅') !== false || 
                                    strpos($currentMessage, '❌') !== false) {
                                    
                                    $finalReply = $currentMessage;
                                    break 2; // উভয় লুপ থেকে বের হওয়া
                                }
                            }
                        }
                    }
                }
                
                // শেষ চেষ্টায় যদি এখনও কিছু না পাই, তাহলে শেষ পাওয়া মেসেজটি নেয়া
                if ($attempts == $maxAttempts && !empty($lastMessage)) {
                    $finalReply = $lastMessage;
                }
            }

            if (!empty($finalReply)) {
                // ডিবাগিং জন্য লগ করা
                // file_put_contents('bot_response.txt', $finalReply . "\n---\n", FILE_APPEND);
                
                // বটের রেসপন্স প্যাটার্ন অনুযায়ী পার্স করি
                if (strpos($finalReply, '✅ RESET SUCCESSFUL') !== false || strpos($finalReply, '✅') !== false) {
                    $message = "✅ RESET SUCCESSFULLY COMPLETED";
                    $msgType = "success";
                } 
                elseif (strpos($finalReply, '❌ RESET FAILED') !== false || strpos($finalReply, '❌') !== false) {
                    // লিমিট চেক
                    if (strpos($finalReply, 'Daily reset limit reached') !== false || 
                        strpos($finalReply, 'limit reached') !== false) {
                        
                        // টাইম এক্সট্র্যাক্ট করার চেষ্টা করি
                        preg_match('/Try again after (\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})/', $finalReply, $matches);
                        if (isset($matches[1])) {
                            $message = "❌ DAILY LIMIT REACHED! Try again after " . $matches[1];
                        } else {
                            $message = "❌ DAILY LIMIT REACHED! Try again later.";
                        }
                        $msgType = "error";
                    }
                    // টোকেন নট ফাউন্ড চেক
                    elseif (strpos($finalReply, 'Token not found') !== false || 
                            strpos($finalReply, 'not found') !== false) {
                        $message = "❌ KEY NOT FOUND! Please check your key.";
                        $msgType = "error";
                    }
                    // ইনভ্যালিড কিচেক
                    elseif (strpos($finalReply, 'Invalid') !== false || 
                            strpos($finalReply, 'invalid') !== false) {
                        $message = "❌ INVALID KEY! Please check your key.";
                        $msgType = "error";
                    }
                    // অন্যান্য এরর
                    else {
                        $message = "❌ RESET FAILED! Please try again.";
                        $msgType = "error";
                    }
                }
                // অলরেডি রিসেট চেক
                elseif (strpos($finalReply, 'already reset') !== false || 
                        strpos($finalReply, 'already') !== false) {
                    $message = "⚠️ THIS TOKEN IS ALREADY RESET!";
                    $msgType = "info";
                }
                else {
                    $message = "SYSTEM RESPONSE: Processing completed.";
                    $msgType = "info";
                }
            } else {
                $message = "Connection failed! No response from system.";
                $msgType = "error";
            }
        } catch (\Exception $e) {
            // ইরর মেসেজ লগ করুন (ডিবাগিং এর জন্য)
            // file_put_contents('error_log.txt', $e->getMessage() . "\n", FILE_APPEND);
            $message = "SYSTEM ERROR! Please try again.";
            $msgType = "error";
        }
    }
}
?>

<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>DRIP CLIENT - Reset HWID</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <style>
        * { box-sizing: border-box; }
        body { 
            background: radial-gradient(circle at top, #1e293b, #0f172a);
            color: #e2e8f0; 
            font-family: 'Inter', sans-serif; 
            display: flex; 
            flex-direction: column;
            justify-content: center; 
            align-items: center; 
            min-height: 100vh; 
            margin: 0;
            user-select: none;
        }

        .header-logo {
            font-size: 38px;
            font-weight: 800;
            text-transform: uppercase;
            letter-spacing: 2px;
            margin-bottom: 5px;
        }
        .header-logo .drip { color: #818cf8; }
        .header-logo .client { color: #f8fafc; }
        
        .sub-title {
            color: #94a3b8;
            font-size: 14px;
            margin-bottom: 35px;
            font-weight: 500;
        }

        .card { 
            background: rgba(30, 41, 59, 0.7);
            backdrop-filter: blur(10px);
            border-radius: 20px; 
            padding: 35px; 
            width: 92%;
            max-width: 400px; 
            border: 1px solid rgba(255, 255, 255, 0.1); 
            box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.5);
        }

        .card-header-title { font-size: 22px; font-weight: 700; margin-bottom: 8px; color: #f1f5f9; }
        .card-description { font-size: 13px; color: #94a3b8; margin-bottom: 25px; }

        .info-box {
            background: rgba(15, 23, 42, 0.5);
            border-radius: 12px;
            padding: 18px;
            margin-bottom: 25px;
            border: 1px solid rgba(255, 255, 255, 0.05);
        }

        .info-row { display: flex; justify-content: space-between; font-size: 14px; margin-bottom: 10px; }
        .info-row:last-child { margin-bottom: 0; }
        .info-label { color: #64748b; }
        .info-value { font-weight: 600; color: #cbd5e1; }

        .input-group { text-align: left; margin-bottom: 20px; }
        .input-label { font-size: 13px; font-weight: 500; display: block; margin-bottom: 10px; color: #94a3b8; }
        
        .input-field { 
            width: 100%; 
            background: rgba(15, 23, 42, 0.6); 
            border: 1px solid #334155; 
            border-radius: 12px; 
            padding: 16px; 
            color: #fff; 
            outline: none; 
            font-size: 15px;
            transition: 0.3s;
        }
        .input-field:focus { border-color: #6366f1; background: rgba(15, 23, 42, 0.8); }

        .reset-btn { 
            width: 100%; 
            background: linear-gradient(135deg, #6366f1, #4f46e5);
            color: white; 
            border: none; 
            border-radius: 12px; 
            padding: 16px; 
            font-weight: 700; 
            cursor: pointer; 
            display: flex; 
            align-items: center; 
            justify-content: center; 
            gap: 10px;
            font-size: 16px;
            box-shadow: 0 10px 15px -3px rgba(79, 70, 229, 0.3);
            transition: 0.3s;
        }
        .reset-btn:hover { transform: translateY(-2px); opacity: 0.95; }
        .reset-btn:disabled { opacity: 0.5; cursor: not-allowed; transform: none; }

        .footer-text { margin-top: 40px; font-size: 12px; color: #475569; letter-spacing: 0.5px; }
        
        /* লোডিং এনিমেশন */
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        .fa-spinner { animation: spin 1s linear infinite; }
        
        /* কাস্টম এলার্ট স্টাইল */
        .swal2-title {
            font-family: 'Inter', sans-serif;
        }
        .swal2-html-container {
            font-family: 'Inter', sans-serif;
        }
    </style>
</head>
<body>

    <div class="header-logo">
        <span class="drip">DRIP</span><span class="client">CLIENT</span>
    </div>
    <div class="sub-title">Sistema de Reset de HWID</div>

    <div class="card">
        <div class="card-header-title">Reset de HWID</div>
        <div class="card-description">Digite o nome de usuário (10 dígitos)</div>

        <div class="info-box">
            <div class="info-row">
                <span class="info-label">Vendedor:</span>
                <span class="info-value">G TOOLS</span>
            </div>
            <div class="info-row">
                <span class="info-label">Status:</span>
                <span class="info-value">Online</span>
            </div>
            <div class="info-row">
                <span class="info-label">Expira em:</span>
                <span class="info-value">Nunca</span>
            </div>
        </div>

        <form method="POST" id="resetForm">
            <div class="input-group">
                <label class="input-label">Nome de Usuário</label>
                <input type="text" name="voucher_code" id="voucherInput" class="input-field" placeholder="Inter your key" required autocomplete="off" maxlength="10">
            </div>
            
            <button type="submit" class="reset-btn" id="subBtn">
                <i class="fas fa-sync-alt"></i> Resetar HWID
            </button>
        </form>
    </div>

    <div class="footer-text">
        © 2026 DRIP CLIENT - SECURITY SYSTEM
    </div>

<script>
    if ( window.history.replaceState ) {
        window.history.replaceState( null, null, window.location.href );
    }

    window.onload = function() {
        var msg = "<?php echo addslashes($message); ?>";
        var type = "<?php echo $msgType; ?>";

        if (msg !== "") {
            var title, icon;
            
            // মেসেজের প্রথম ক্যারেক্টার দেখে আইকন সেট করা
            if (msg.includes('✅')) {
                title = "Success!";
                icon = "success";
                // ✅ ইমোজি রিমুভ করা (যদি থাকে)
                msg = msg.replace('✅', '').trim();
            } else if (msg.includes('❌')) {
                title = "Error!";
                icon = "error";
                msg = msg.replace('❌', '').trim();
            } else if (msg.includes('⚠️')) {
                title = "Warning!";
                icon = "warning";
                msg = msg.replace('⚠️', '').trim();
            } else {
                if (type === "success") {
                    title = "Success!";
                    icon = "success";
                } else if (type === "error") {
                    title = "Error!";
                    icon = "error";
                } else if (type === "info") {
                    title = "Information";
                    icon = "info";
                } else {
                    title = "System Response";
                    icon = "info";
                }
            }
            
            // HTML লাইন ব্রেক সাপোর্ট সহ এলার্ট
            Swal.fire({
                title: title,
                html: msg.replace(/\n/g, '<br>'),
                icon: icon,
                background: '#1e293b',
                color: '#f1f5f9',
                confirmButtonColor: '#6366f1',
                confirmButtonText: 'OK',
                customClass: {
                    title: 'swal2-title',
                    htmlContainer: 'swal2-html-container'
                }
            });
        }
    };

    document.getElementById('resetForm').onsubmit = function(e) {
        var input = document.getElementById('voucherInput').value;
        var btn = document.getElementById('subBtn');

        if (input.length !== 10) {
            e.preventDefault();
            Swal.fire({
                title: 'Invalid Digits',
                text: 'Please enter exactly 10 characters.',
                icon: 'warning',
                background: '#1e293b',
                color: '#f1f5f9',
                confirmButtonColor: '#6366f1'
            });
            return false;
        }

        // শুধু সংখ্যা চেক
        if (!/^\d+$/.test(input)) {
            e.preventDefault();
            Swal.fire({
                title: 'Invalid Format',
                text: 'Please enter only numbers.',
                icon: 'warning',
                background: '#1e293b',
                color: '#f1f5f9',
                confirmButtonColor: '#6366f1'
            });
            return false;
        }

        btn.disabled = true;
        btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Processing...';
        
        // প্রসেসিং এলার্ট শো করা
        Swal.fire({
            title: 'Processing',
            html: 'Connecting to system...<br><small>Please wait</small>',
            icon: 'info',
            background: '#1e293b',
            color: '#f1f5f9',
            showConfirmButton: false,
            allowOutsideClick: false,
            allowEscapeKey: false,
            didOpen: () => {
                Swal.showLoading();
            }
        });
        
        return true;
    };

    // ইনপুট ফিল্ডে শুধু সংখ্যা প্রবেশের অনুমতি দিন
    document.getElementById('voucherInput').addEventListener('input', function(e) {
        this.value = this.value.replace(/[^0-9]/g, '');
        
        // অটো হাইলাইট যখন 10 ডিজিট পূর্ণ হয়
        if (this.value.length === 10) {
            this.select();
        }
    });
    
    // পেজ লোড হলে ইনপুট ফিল্ডে ফোকাস করা
    document.getElementById('voucherInput').focus();
</script>
</body>
</html>