<?php
// =============================================================================
// login.php — admin login page (split layout, Vanta NET on the left)
// =============================================================================

require_once __DIR__ . '/includes/bootstrap.php';

// ----- TEMP DEBUG LOGGER --------------------------------------------------
// Writes every login hit to /debug_trace.log at the panel root. .log is denied
// by the .htaccess so it's not web-readable — pull it via FTP. Remove this
// block once the 500 is diagnosed.
(function () {
    $log_path = __DIR__ . '/debug_trace.log';
    $line = [
        'ts'      => date('c'),
        'page'    => 'login.php',
        'method'  => $_SERVER['REQUEST_METHOD'] ?? '?',
        'ip'      => function_exists('client_ip') ? client_ip() : ($_SERVER['REMOTE_ADDR'] ?? '?'),
        'has_csrf_in_post' => isset($_POST['_csrf']),
        'username'         => isset($_POST['username']) ? substr((string)$_POST['username'], 0, 30) : null,
        'pw_len'           => isset($_POST['password']) ? strlen((string)$_POST['password']) : 0,
        'session_id'       => session_id() ? substr(session_id(), 0, 8) . '…' : null,
        'sess_csrf_set'    => !empty($_SESSION['csrf']),
        'sess_admin_id'    => $_SESSION['admin_id'] ?? null,
        'sess_pending_2fa' => $_SESSION['pending_totp_admin_id'] ?? null,
        'cookie_mpanel'    => isset($_COOKIE['MPANEL']) ? substr($_COOKIE['MPANEL'], 0, 8) . '…' : null,
        'cf_ray'           => $_SERVER['HTTP_CF_RAY'] ?? null,
    ];
    @file_put_contents($log_path,
        json_encode($line, JSON_UNESCAPED_SLASHES) . "\n",
        FILE_APPEND | LOCK_EX);
    register_shutdown_function(function () use ($log_path) {
        $e = error_get_last();
        $headers = function_exists('headers_list') ? headers_list() : [];
        $status_header = '';
        foreach ($headers as $h) {
            if (stripos($h, 'Location:') === 0) { $status_header = $h; break; }
        }
        $tail = [
            'ts'       => date('c'),
            'page'     => 'login.php-end',
            'php_err'  => $e,
            'http_code'=> http_response_code(),
            'redirect' => $status_header ?: null,
        ];
        @file_put_contents($log_path,
            json_encode($tail, JSON_UNESCAPED_SLASHES) . "\n",
            FILE_APPEND | LOCK_EX);
    });
})();
// ----- END TEMP DEBUG LOGGER ----------------------------------------------

if (auth_user()) {
    header('Location: dashboard.php');
    exit;
}

require_once __DIR__ . '/includes/totp.php';

$error = '';
$username = '';
$needs_totp = !empty($_SESSION['pending_totp_admin_id']);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $ip    = client_ip();
    $token = isset($_POST['_csrf']) ? $_POST['_csrf'] : '';
    if (!csrf_check($token)) {
        $error = 'Invalid session token. Please reload and try again.';
    } elseif ($needs_totp) {
        $code = isset($_POST['totp_code']) ? trim($_POST['totp_code']) : '';
        $pending_id = (int)$_SESSION['pending_totp_admin_id'];
        $row = db_one('SELECT id, username, totp_secret FROM admin_users WHERE id = ?', [$pending_id]);
        $step = login_throttle_step($ip, function () use ($row, $code) {
            return $row && totp_verify($row['totp_secret'], $code);
        });
        if ($step['locked']) {
            $error = $step['locked_msg'];
        } elseif ($step['auth_result']) {
            unset($_SESSION['pending_totp_admin_id']);
            auth_login($row);
            header('Location: dashboard.php');
            exit;
        } else {
            $error = 'Invalid 6-digit code. Please try again.';
        }
    } else {
        $username = isset($_POST['username']) ? trim($_POST['username']) : '';
        $password = isset($_POST['password']) ? $_POST['password'] : '';
        if ($username === '' || $password === '') {
            $error = 'Username and password are required.';
        } else {
            $row = null;
            $step = login_throttle_step($ip, function () use (&$row, $username, $password) {
                $row = auth_check_password($username, $password);
                return (bool)$row;
            });
            if ($step['locked']) {
                $error = $step['locked_msg'];
            } elseif ($step['auth_result']) {
                if ((int)($row['totp_enabled'] ?? 0) === 1) {
                    $_SESSION['pending_totp_admin_id'] = (int)$row['id'];
                    $needs_totp = true;
                } else {
                    auth_login($row);
                    header('Location: dashboard.php');
                    exit;
                }
            } else {
                $error = 'Invalid username or password.';
            }
        }
    }
}
$csrf = csrf_token();
?><!doctype html>
<html lang="en" style="background:#0a0a0a;color-scheme:dark">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="color-scheme" content="dark">
<meta name="theme-color" content="#0a0a0a">
<style>html,body{background:#0a0a0a;color:#e2e8f0;}</style>
<title>Master Panel — Login</title>
<link rel="icon" href="assets/images/favicon.ico" type="image/x-icon">
<script src="https://cdn.tailwindcss.com"></script>
<link rel="stylesheet" href="assets/css/phosphor.css">
<link rel="stylesheet" href="assets/css/panel.css">
<script>
tailwind.config = {
    darkMode: 'class',
    theme: { extend: { colors: {
        primary: {50:'#fff8eb',100:'#ffefc6',200:'#ffdb88',300:'#ffc44a',400:'#f9a825',500:'#f39c12',600:'#d68910',700:'#b8760e',800:'#955f0b',900:'#7a4d0c'},
        dark:    {50:'#e2e8f0',100:'#ccc',200:'#aaa',300:'#999',400:'#777',500:'#666',600:'#2a2a2a',700:'#1e1e1e',800:'#161616',900:'#0a0a0a',950:'#111'}
    } } }
}
</script>
<script src="https://cdn.jsdelivr.net/npm/three@0.121.1/build/three.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vanta@latest/dist/vanta.net.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js" defer></script>
<style>
body { background:#0a0a0a; color:#e2e8f0; }
#vanta-bg { position:absolute; inset:0; }
.gradient-text { background: linear-gradient(135deg, #f39c12, #ffc44a); -webkit-background-clip: text; background-clip: text; color: transparent; }
</style>
</head>
<body class="min-h-screen">
<div class="min-h-screen flex">
    <!-- LEFT: Vanta.NET background -->
    <div class="hidden lg:flex lg:w-1/2 relative items-center justify-center overflow-hidden">
        <div id="vanta-bg"></div>
        <div class="relative z-10 text-center px-8">
            <div class="inline-flex items-center justify-center h-20 w-20 bg-primary-500 rounded-2xl mb-6 shadow-2xl">
                <span class="text-white font-bold text-4xl">T</span>
            </div>
            <h1 class="text-5xl font-bold mb-2 gradient-text">Master Panel</h1>
            <p class="text-dark-300">Sign in to your account</p>
        </div>
    </div>

    <!-- RIGHT: Login form -->
    <div class="flex-1 flex items-center justify-center px-6 py-12" style="background:#161616;">
        <div class="w-full max-w-md slide-up">
            <div class="lg:hidden text-center mb-8">
                <div class="inline-flex items-center justify-center h-14 w-14 bg-primary-500 rounded-xl mb-3">
                    <span class="text-white font-bold text-2xl">T</span>
                </div>
                <h1 class="text-2xl font-bold text-white">Master Panel</h1>
            </div>

            <div class="mb-6">
                <h2 class="text-2xl font-bold text-white mb-1"><?php echo $needs_totp ? 'Two-factor verification' : 'Welcome back'; ?></h2>
                <p class="text-sm text-dark-400"><?php echo $needs_totp ? 'Enter the 6-digit code from your authenticator app.' : 'Enter your credentials to continue'; ?></p>
            </div>

            <?php if ($error !== ''): ?>
                <div class="mb-4 p-3 rounded-lg bg-red-500/10 border border-red-500/30 text-red-300 text-sm flex items-center gap-2">
                    <i class="ph ph-warning-circle text-lg"></i>
                    <span><?php echo h($error); ?></span>
                </div>
            <?php endif; ?>

            <?php if ($needs_totp): ?>
            <form method="POST" class="space-y-5">
                <input type="hidden" name="_csrf" value="<?php echo h($csrf); ?>">
                <div>
                    <label class="form-label text-xs uppercase tracking-wider">Authentication code</label>
                    <div class="relative">
                        <i class="ph ph-shield-check absolute left-3 top-1/2 -translate-y-1/2 text-dark-400 text-lg"></i>
                        <input type="text" name="totp_code" inputmode="numeric" pattern="[0-9]{6}" maxlength="6"
                               autocomplete="one-time-code" autofocus required
                               class="login-input pl-11 mono tracking-[0.4em] text-center"
                               placeholder="123456">
                    </div>
                </div>
                <button type="submit"
                        class="w-full flex items-center justify-center gap-2 px-4 py-3 bg-primary-600 hover:bg-primary-700 text-white font-semibold rounded-lg transition-colors">
                    <i class="ph ph-check-circle"></i> Verify
                </button>
                <p class="text-center text-xs text-dark-500">
                    <a href="logout.php" class="hover:text-primary-400">Cancel and sign in as a different user</a>
                </p>
            </form>
            <?php else: ?>
            <form method="POST" x-data="{ showPw: false }" class="space-y-5">
                <input type="hidden" name="_csrf" value="<?php echo h($csrf); ?>">
                <div>
                    <label class="form-label text-xs uppercase tracking-wider">Username</label>
                    <div class="relative">
                        <i class="ph ph-user absolute left-3 top-1/2 -translate-y-1/2 text-dark-400 text-lg"></i>
                        <input type="text" name="username" autocomplete="username" autofocus
                               value="<?php echo h($username); ?>"
                               class="login-input pl-11"
                               placeholder="admin">
                    </div>
                </div>
                <div>
                    <label class="form-label text-xs uppercase tracking-wider">Password</label>
                    <div class="relative">
                        <i class="ph ph-lock absolute left-3 top-1/2 -translate-y-1/2 text-dark-400 text-lg"></i>
                        <input :type="showPw ? 'text' : 'password'" name="password" autocomplete="current-password"
                               class="login-input pl-11 pr-11" placeholder="••••••••">
                        <button type="button" @click="showPw=!showPw"
                                class="absolute right-3 top-1/2 -translate-y-1/2 text-dark-400 hover:text-primary-400">
                            <i class="ph" :class="showPw ? 'ph-eye-slash' : 'ph-eye'"></i>
                        </button>
                    </div>
                </div>
                <div class="flex items-center justify-between text-xs">
                    <label class="flex items-center gap-2 text-dark-300 cursor-pointer">
                        <input type="checkbox" name="remember" class="rounded border-dark-500 text-primary-500 focus:ring-primary-500 bg-dark-700">
                        Remember me
                    </label>
                    <span class="text-dark-500">v1.0</span>
                </div>
                <button type="submit"
                        class="w-full flex items-center justify-center gap-2 px-4 py-3 bg-primary-600 hover:bg-primary-700 text-white font-semibold rounded-lg transition-colors">
                    <i class="ph ph-sign-in"></i> Sign in
                </button>
            </form>
            <?php endif; ?>

        </div>
    </div>
</div>
<script>
window.addEventListener('load', function () {
    if (window.VANTA && document.getElementById('vanta-bg')) {
        VANTA.NET({
            el: '#vanta-bg',
            mouseControls: true, touchControls: true, gyroControls: false,
            minHeight: 200.00, minWidth: 200.00,
            scale: 1.00, scaleMobile: 1.00,
            color: 0xf39c12, backgroundColor: 0x0a0a0a,
            points: 8.00, maxDistance: 20.00, spacing: 18.00
        });
    }
});
</script>
</body>
</html>
