<?php
// ============================================================
//  MadelineProto Session Setup (Birinchi marta interaktiv login)
//  Ishlatilishi: php setup_session.php  (terminalda bir marta)
// ============================================================

set_time_limit(0);

if (PHP_SAPI !== 'cli') {
    exit("Faqat CLI dan ishlatiladi!\nphp setup_session.php");
}

// .htaccess session papkasini himoya qiladi
$sessionDir = __DIR__ . '/madeline_session';
if (!is_dir($sessionDir)) {
    mkdir($sessionDir, 0755, true);
    file_put_contents($sessionDir . '/.htaccess', "Deny from all\n");
}

require_once __DIR__ . '/config.php';
require_once __DIR__ . '/vendor/autoload.php';

use danog\MadelineProto\API;
use danog\MadelineProto\Settings;
use danog\MadelineProto\Settings\AppInfo;

$sessionFile = $sessionDir . '/' . MADELINE_SESSION_NAME . '.madeline';

echo "==============================================\n";
echo "  MadelineProto UserBot Session Setup\n";
echo "==============================================\n\n";

if (file_exists($sessionFile)) {
    echo "⚠️  Mavjud session topildi: {$sessionFile}\n";
    echo "Qayta login qilmoqchimisiz? (yes/no): ";
    $answer = trim(fgets(STDIN));
    if (strtolower($answer) !== 'yes') {
        echo "Bekor qilindi.\n";
        exit(0);
    }
}

$settings = (new Settings)
    ->setAppInfo(
        (new AppInfo)
            ->setApiId(MADELINE_API_ID)
            ->setApiHash(MADELINE_API_HASH)
    );

echo "\n📱 Telegram hisobingizga kirish uchun telefon raqamingizni kiriting.\n";
echo "Format: +998901234567\n\n";

$MadelineProto = new API($sessionFile, $settings);

// Interaktiv login  
// MadelineProto o'zi stdout/stdin orqali so'raydi:
// 1. Telefon raqam
// 2. SMS kodi
// 3. (agar 2FA bo'lsa) parol
$MadelineProto->start();

$self = $MadelineProto->getSelf();

echo "\n✅ Muvaffaqiyatli kirildi!\n";
echo "👤 Ism: " . ($self['first_name'] ?? '') . " " . ($self['last_name'] ?? '') . "\n";
echo "📛 Username: @" . ($self['username'] ?? 'yo\'q') . "\n";
echo "🆔 User ID: " . $self['id'] . "\n\n";
echo "Session fayl: {$sessionFile}\n\n";
echo "✅ Endi bot katta fayllarni siz orqali yuborishga tayyor!\n";
