<?php
require_once '../../includes/functions.php';
require_once '../../includes/email_service.php';
setCORSHeaders();

// Verify API Hash
verifyAPIHash();

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    sendError('Method not allowed', 405);
}

$input = json_decode(file_get_contents('php://input'), true);

if (!$input) {
    sendError('Invalid JSON data');
}

$username = trim($input['username'] ?? '');
$email = trim($input['email'] ?? '');
$password = $input['password'] ?? '';
$fullName = trim($input['full_name'] ?? '');
$phone = trim($input['phone'] ?? '');

// Validation
if (empty($username) || empty($email) || empty($password) || empty($fullName)) {
    sendError('All required fields must be filled');
}

if (strlen($username) < 3) {
    sendError('Username must be at least 3 characters');
}

if (!validateEmail($email)) {
    sendError('Invalid email format');
}

if (strlen($password) < 6) {
    sendError('Password must be at least 6 characters');
}

if (!empty($phone) && !validatePhone($phone)) {
    sendError('Invalid phone number format');
}

// Check if user already exists
$existingUser = getUserByEmail($email);
if ($existingUser) {
    sendError('Email already registered');
}

$stmt = $pdo->prepare("SELECT id FROM users WHERE username = ?");
$stmt->execute([$username]);
if ($stmt->fetch()) {
    sendError('Username already taken');
}

// Create new user
$hashedPassword = password_hash($password, PASSWORD_DEFAULT);

// Get default coins from app_settings
$stmt = $pdo->prepare("SELECT setting_value FROM app_settings WHERE setting_key = 'default_coins'");
$stmt->execute();
$defaultCoins = (int)($stmt->fetchColumn() ?? 0);

$stmt = $pdo->prepare("SELECT setting_value FROM app_settings WHERE setting_key = 'default_free_coins'");
$stmt->execute();
$defaultFreeCoins = (int)($stmt->fetchColumn() ?? 0);

$stmt = $pdo->prepare("SELECT setting_value FROM app_settings WHERE setting_key = 'telegram_user_bot_enabled'");
$stmt->execute();
$telegramUserBotEnabled = (int)($stmt->fetchColumn() ?? 0) === 1;

if ($telegramUserBotEnabled) {
    // Initial bonus will be granted only after Telegram verification.
    $defaultCoins = 0;
    $defaultFreeCoins = 0;
}

$stmt = $pdo->prepare("INSERT INTO users (username, email, password, full_name, phone, coins, free_coins) VALUES (?, ?, ?, ?, ?, ?, ?)");
if ($stmt->execute([$username, $email, $hashedPassword, $fullName, $phone, $defaultCoins, $defaultFreeCoins])) {
    $userId = $pdo->lastInsertId();
    $syncCode = (int)$userId * 74596;
    $stmt = $pdo->prepare("UPDATE users SET telegram_sync_code = ? WHERE id = ?");
    $stmt->execute([$syncCode, $userId]);
    
    // Generate JWT token
    $token = generateJWT([
        'user_id' => $userId,
        'username' => $username,
        'email' => $email,
        'exp' => time() + (60 * 60 * 24 * 7) // 7 days
    ]);
    
    // Get user data
    $user = getUserById($userId);
    
    // Send Telegram notification to admin
    try {
        $stmt = $pdo->query("SELECT setting_key, setting_value FROM app_settings WHERE setting_key IN ('telegram_bot_token', 'telegram_admin_id')");
        $settings = [];
        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            $settings[$row['setting_key']] = $row['setting_value'];
        }
        
        $botToken = $settings['telegram_bot_token'] ?? '';
        $adminId = $settings['telegram_admin_id'] ?? '';
        
        if (!empty($botToken) && !empty($adminId)) {
            $text = "🆕 <b>کاربر جدید ثبت‌نام کرد!</b>\n\n";
            $text .= "🆔 <b>شناسه کاربر:</b> #{$userId}\n";
            $text .= "👤 <b>نام:</b> {$fullName}\n";
            $text .= "📧 <b>ایمیل:</b> {$email}\n";
            $text .= "🔖 <b>نام کاربری:</b> @{$username}\n";
            if (!empty($phone)) {
                $text .= "📱 <b>تلفن:</b> {$phone}\n";
            }
            $text .= "💰 <b>سکه اولیه:</b> {$defaultCoins}\n";
            if ($defaultFreeCoins > 0) {
                $text .= "⭐ <b>سکه رایگان اولیه:</b> {$defaultFreeCoins}\n";
            }
            $text .= "📅 <b>تاریخ ثبت‌نام:</b> " . date('Y/m/d H:i') . "\n";
            
            $url = "https://api.telegram.org/bot{$botToken}/sendMessage";
            $data = [
                'chat_id' => $adminId,
                'text' => $text,
                'parse_mode' => 'HTML'
            ];
            
            $ch = curl_init($url);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_TIMEOUT, 5);
            curl_exec($ch);
            curl_close($ch);
        }
    } catch (Exception $e) {
        // Don't fail the registration if Telegram notification fails
        error_log("Telegram notification error: " . $e->getMessage());
    }

    try {
        sendSystemEmail(
            $pdo,
            'user_welcome',
            $email,
            [
                'full_name' => $fullName,
                'username' => $username
            ],
            [
                'triggered_by' => 'api_register',
                'context' => ['user_id' => $userId]
            ]
        );
    } catch (Exception $e) {
        error_log("Welcome email error: " . $e->getMessage());
    }
    
    sendResponse([
        'success' => true,
        'message' => 'User registered successfully',
        'data' => [
            'token' => $token,
            'user' => $user
        ]
    ], 201);
} else {
    sendError('Registration failed');
}
?>