<?php

if (basename(__FILE__) == basename($_SERVER['SCRIPT_FILENAME'])) {
    die('No direct script access allowed');
}

global $update, $platform, $user_id, $user;


if (!isset($update) || empty($update)) {
    $update = json_decode(file_get_contents('php://input'), true) ?? [];
}


$platform = defined('PLATFORM') ? PLATFORM : 'telegram';

$platform_id = 0;
$chat_id_from_update = 0;
$user_info_source = null;
$message_text_raw = null; 

if (isset($update['message'])) {
    $platform_id = $update['message']['from']['id'] ?? 0;
    $chat_id_from_update = $update['message']['chat']['id'] ?? 0;
    $user_info_source = $update['message']['from'] ?? null;
    $message_text_raw = $update['message']['text'] ?? null; 
} elseif (isset($update['callback_query'])) {
    $platform_id = $update['callback_query']['from']['id'] ?? 0;
    $chat_id_from_update = $update['callback_query']['message']['chat']['id'] ?? 0;
    $user_info_source = $update['callback_query']['from'] ?? null;
} else {
    http_response_code(200);
    
    if (!defined('IS_BRIDGE_CALL') || IS_BRIDGE_CALL !== true) { exit(); } else { return; }
    
}

if ($platform_id === 0 || $chat_id_from_update === 0) {
    file_put_contents(ERROR_LOG_PATH, date('Y-m-d H:i:s') . " - Error: Could not determine platform ID ({$platform_id}) or chat ID ({$chat_id_from_update}) in Kernel.\nUpdate Data: " . json_encode($update) . "\n", FILE_APPEND);
    http_response_code(200);
    
    if (!defined('IS_BRIDGE_CALL') || IS_BRIDGE_CALL !== true) { exit(); } else { return; }
    
}

$user = getUser($platform_id, $platform);

if (!$user) {
    
    $first_name = $user_info_source['first_name'] ?? 'کاربر';
    
    $referred_by_user_id = null;
    if ($message_text_raw && strpos($message_text_raw, '/start ') === 0) {
        $ref_code = substr($message_text_raw, 7);
        if (!empty($ref_code)) {
            $partner = getUserByReferralCode($ref_code);
            if ($partner) {
                $referred_by_user_id = $partner['id'];
            }
        }
    }
    
    $user_id = createUser($platform_id, $chat_id_from_update, $first_name, $platform, $referred_by_user_id);
    if ($user_id === 0) {
    
        file_put_contents(ERROR_LOG_PATH, date('Y-m-d H:i:s') . " - CRITICAL Error: Failed to create user for platform ID {$platform_id} on {$platform}.\n", FILE_APPEND);
        http_response_code(200);
        
        if (!defined('IS_BRIDGE_CALL') || IS_BRIDGE_CALL !== true) { exit(); } else { return; }
        
    }
    $user = getUserById($user_id);
    if (!$user) {
        file_put_contents(ERROR_LOG_PATH, date('Y-m-d H:i:s') . " - CRITICAL Error: Failed to retrieve user {$user_id} immediately after creation.\n", FILE_APPEND);
        http_response_code(200);
        
        if (!defined('IS_BRIDGE_CALL') || IS_BRIDGE_CALL !== true) { exit(); } else { return; }
        
    }
} else {
    $chat_id_column = ($platform === 'bale') ? 'bale_chat_id' : 'telegram_chat_id';
    if (($user[$chat_id_column] ?? null) != $chat_id_from_update) {
        updateUserField($user['id'], $chat_id_column, $chat_id_from_update);
        $user[$chat_id_column] = $chat_id_from_update;
    }
}

$user_id = $user['id'];

if (($user['is_active'] ?? false) == false) {
    sendMessage(
        $chat_id_from_update,
        "❌ دسترسی شما به ربات مسدود شده است.",
        ['remove_keyboard' => true],
        $platform
    );
    
    if (!defined('IS_BRIDGE_CALL') || IS_BRIDGE_CALL !== true) { exit(); } else { return; }
    
}

$session_data = $user['session'] ? json_decode($user['session'], true) : [];
if (!is_array($session_data)) { $session_data = ['state' => 'idle']; }
$state = $session_data['state'] ?? 'idle';
$last_activity = strtotime($user['session_last_activity'] ?? '1970-01-01');

if ($state !== 'idle' && (time() - $last_activity) > SESSION_TIMEOUT_SECONDS) {
    $session_data = ['state' => 'idle', 'checkout' => [], 'selected_card_id' => null, ];
    updateUserField($user_id, 'session', json_encode($session_data));

    $user['session'] = json_encode($session_data);
    $user['session_last_activity'] = date('Y-m-d H:i:s');
    $state = 'idle';

    $admin_keyboard_markup = getAdminMainMenuKeyboard();
    $customer_keyboard_markup = getCustomerMainMenuKeyboard($user);
    $keyboard_to_show = ($user['is_admin'] ?? false) ? $admin_keyboard_markup : $customer_keyboard_markup;

    sendMessage(
        $chat_id_from_update,
        "⏳ عملیات قبلی شما به دلیل عدم فعالیت لغو شد. به منوی اصلی بازگشتید.",
        $keyboard_to_show,
        $platform
    );
    
    if (!defined('IS_BRIDGE_CALL') || IS_BRIDGE_CALL !== true) { exit(); } else { return; }
    
}

$verification_statuses = [
    'awaiting_phone', 'awaiting_otp', 'awaiting_full_name',
    'awaiting_national_id_photo', 'awaiting_national_id_code',
    'awaiting_verification_payment',
    'awaiting_birth_year', 'awaiting_birth_month',
    'awaiting_birth_day', 'awaiting_selfie', 'awaiting_admin_selfie_approval',
    'awaiting_physical_code', 'identity_rejected'
];

if ($user['is_admin'] ?? false) {
    require_once __DIR__ . '/../Handlers/AdminHandler.php';
} elseif (in_array($user['status'], $verification_statuses)) {
    require_once __DIR__ . '/../Handlers/VerificationHandler.php';
} else {
    require_once __DIR__ . '/../Handlers/CustomerHandler.php';
}

?>