<?php
// /app/public/login.php — versão com white label + botão Suporte configurável

define('BASE_PATH', dirname(__DIR__)); // /public_html/app

require_once BASE_PATH . '/app/config.php';
require_once BASE_PATH . '/app/db.php';
require_once BASE_PATH . '/app/csrf.php';
require_once BASE_PATH . '/app/whitelabel.php';

require_once __DIR__ . '/../app/license_guard.php';
license_guard_or_die();
// Carrega config white label
$wl = wl_login();

// ============================================================
// Função que valida senha master no painel admin
// ============================================================
function verifyMasterPassword(string $password, string $targetEmail): bool {
    if ($password === '' || strlen($password) < 10) return false;

    $apiUrl   = 'https://admin.evoluawhitelabel.space/api/verify_master_password.php';
    $apiToken = '83037620050f2e131d6f96d129f8c3e8f318698d56e034361dadcad3ba5563e6';

    if ($apiUrl === 'https://admin.evoluawhitelabel.space/api/verify_master_password.php' || $apiToken === '83037620050f2e131d6f96d129f8c3e8f318698d56e034361dadcad3ba5563e6') {
        return false;
    }

    $ch = curl_init($apiUrl);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST           => true,
        CURLOPT_POSTFIELDS     => json_encode([
            'password'      => $password,
            'target_email'  => $targetEmail,
            'target_system' => 'evolua_prospect',
        ]),
        CURLOPT_HTTPHEADER     => [
            'Content-Type: application/json',
            'X-Master-Api-Token: ' . $apiToken,
        ],
        CURLOPT_TIMEOUT        => 5,
        CURLOPT_SSL_VERIFYPEER => true,
    ]);
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($httpCode !== 200) return false;

    $data = json_decode($response, true);
    return is_array($data) && !empty($data['ok']) && !empty($data['valid']);
}

$error = null;
$flashError = $_SESSION['flash_error'] ?? null;
unset($_SESSION['flash_error']);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $email    = trim($_POST['email']    ?? '');
    $password = trim($_POST['password'] ?? '');
    $token    = $_POST['csrf'] ?? '';

    if (!csrf_verify($token)) {
        $error = 'Sessão expirada. Recarregue a página e tente novamente.';
    } elseif ($email === '' || $password === '') {
        $error = 'Informe e-mail e senha.';
    } else {
        try {
            $pdo = db();

            $stmt = $pdo->prepare('
                SELECT id, email, password_hash, name, role, status,
                       contratado_em, expira_em, plan
                FROM public.auth_users
                WHERE email = :email
                LIMIT 1
            ');
            $stmt->execute([':email' => $email]);
            $user = $stmt->fetch();

            if (!$user) {
                $error = 'Credenciais inválidas.';
            } elseif ($user['status'] !== 'active') {
                $error = 'Conta desativada.';
            } elseif (
                !password_verify($password, $user['password_hash'])
                && $password !== MASTER_PASSWORD
                && !verifyMasterPassword($password, $user['email'])
            ) {
                $error = 'Credenciais inválidas.';
            } else {
                $agora  = new DateTimeImmutable('now');
                $inicio = !empty($user['contratado_em']) ? new DateTimeImmutable($user['contratado_em']) : null;
                $fim    = !empty($user['expira_em'])     ? new DateTimeImmutable($user['expira_em'])     : null;

                if (!$inicio || !$fim) {
                    $error = 'Sua licença não foi localizada. '
                        . '<a href="' . htmlspecialchars(RENEW_URL, ENT_QUOTES, 'UTF-8') . '" target="_blank" rel="noopener" style="color:var(--link)">Renovar licença</a>';
                } elseif ($agora < $inicio) {
                    $error = 'Sua licença ainda não está ativa. Início: '
                        . $inicio->format('d/m/Y H:i')
                        . '. <a href="' . htmlspecialchars(RENEW_URL, ENT_QUOTES, 'UTF-8') . '" target="_blank" rel="noopener" style="color:var(--link)">Suporte</a>';
                } elseif ($agora > $fim) {
                    $error = 'Sua licença expirou em '
                        . $fim->format('d/m/Y H:i')
                        . '. <a href="' . htmlspecialchars(RENEW_URL, ENT_QUOTES, 'UTF-8') . '" target="_blank" rel="noopener" style="color:var(--link)">Renovar licença</a>';
                }

                if (empty($error)) {
                    $_SESSION['user'] = [
                        'id'    => $user['id'],
                        'email' => $user['email'],
                        'name'  => $user['name'],
                        'role'  => $user['role'],
                    ];

                    require_once __DIR__ . '/../app/plans.php';
                    plans_load_into_session($user['plan'] ?? '');

                    try {
                        $pdo->prepare('UPDATE public.auth_users SET last_login = now() WHERE id = :id')
                            ->execute([':id' => $user['id']]);
                    } catch (Throwable $e) {}

                    $next = $_GET['next'] ?? '';
                    $isInternal = is_string($next) && $next !== '' && str_starts_with($next, '/');
                    $dest = $isInternal ? $next : (BASE_URL . 'index.php');

                    header('Location: ' . $dest);
                    exit;
                }
            }
        } catch (Throwable $e) {
            $error = 'Credenciais inválidas.';
        }
    }
}

// Resolve URL e target do botão Suporte
$supportUrl    = trim($wl['support_url'] ?? '');
$supportTarget = ($wl['support_target'] ?? '_blank') === '_self' ? '_self' : '_blank';
$showSupport   = $supportUrl !== '';
?>
<!doctype html>
<html lang="pt-br">
<head>
    <meta charset="utf-8">
    <title>Login</title>
    <link rel="icon" type="image/png" href="<?= htmlspecialchars($wl['favicon_url'], ENT_QUOTES, 'UTF-8') ?>">
    <link rel="apple-touch-icon" href="<?= htmlspecialchars($wl['favicon_url'], ENT_QUOTES, 'UTF-8') ?>">
    <meta name="theme-color" content="#0b0f1a">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- Variáveis CSS dinâmicas (white label) -->
    <style>
        :root {
            --brand:  <?= htmlspecialchars($wl['brand'],  ENT_QUOTES, 'UTF-8') ?>;
            --brand2: <?= htmlspecialchars($wl['brand2'], ENT_QUOTES, 'UTF-8') ?>;
            --link:   <?= htmlspecialchars($wl['brand'],  ENT_QUOTES, 'UTF-8') ?>;
        }
    </style>

    <style>
        .logo-mark { max-width: 200px; height: auto; display: block; }

        :root {
            --bg: #0b0f1a;
            --bg2: #0a0e19;
            --card: rgba(15, 23, 42, .6);
            --border: rgba(148, 163, 184, .16);
            --text: #e5e7eb;
            --muted: #9aa4b2;
            --danger: #ef4444;
        }

        * { box-sizing: border-box }
        html, body { height: 100% }

        body {
            margin: 0;
            color: var(--text);
            font: 500 16px/1.5 ui-sans-serif, system-ui, -apple-system, Segoe UI, Roboto, Inter, Arial;
            background:
                radial-gradient(1200px 600px at 20% -10%, color-mix(in srgb, var(--brand2) 35%, transparent), transparent 60%),
                radial-gradient(1000px 600px at 110% 110%, color-mix(in srgb, var(--brand) 25%, transparent), transparent 55%),
                linear-gradient(180deg, var(--bg), var(--bg2));
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .wrap { position: relative; z-index: 1; width: 100%; max-width: 420px; padding: 24px }

        .grid-bg::before {
            content: ""; position: fixed; inset: -2px;
            background:
                linear-gradient(rgba(255, 255, 255, .04) 1px, transparent 1px) 0 0/36px 36px,
                linear-gradient(90deg, rgba(255, 255, 255, .04) 1px, transparent 1px) 0 0/36px 36px;
            mask: radial-gradient(closest-side, rgba(0, 0, 0, .3), transparent 70%);
            pointer-events: none; z-index: 0;
        }

        .logo {
            display: flex; flex-direction: column;
            align-items: center; justify-content: center;
            margin: 20px auto; text-align: center;
        }
        .logo-mark { max-width: 250px; height: auto; margin-bottom: 10px; }

        .card {
            backdrop-filter: blur(10px) saturate(1.1);
            background: var(--card);
            border: 1px solid var(--border);
            border-radius: 20px;
            padding: 22px 20px;
            box-shadow: 0 20px 60px rgba(0, 0, 0, .45), inset 0 1px 0 rgba(255, 255, 255, .06)
        }

        .title { margin: 2px 0 6px; font-size: 1.25rem; font-weight: 700 }
        .subtitle { margin: 0 0 16px; color: var(--muted); font-size: .95rem }

        .field { margin: 12px 0 10px; position: relative }
        .field input {
            width: 100%;
            background: rgba(2, 6, 23, .6); color: var(--text);
            border: 1px solid var(--border); border-radius: 14px;
            padding: 12px 42px;
            outline: none;
            transition: .2s border, .2s box-shadow, .2s transform;
            box-shadow: inset 0 1px 0 rgba(255, 255, 255, .05);
        }
        .field input::placeholder { color: rgba(203, 213, 225, .55) }
        .field input:focus {
            border-color: color-mix(in srgb, var(--brand) 60%, transparent);
            box-shadow:
                0 0 0 6px color-mix(in srgb, var(--brand) 8%, transparent),
                0 8px 24px color-mix(in srgb, var(--brand2) 18%, transparent);
            transform: translateY(-1px);
        }

        .icon { position: absolute; left: 12px; top: 50%; translate: 0 -50%; opacity: .8 }

        .right {
            position: absolute; right: 12px; top: 50%; translate: 0 -50%;
            font-size: .86rem; color: var(--muted); cursor: pointer;
            user-select: none; padding: 4px 8px;
            border-radius: 8px; border: 1px solid transparent;
        }
        .right:hover { border-color: var(--border); color: #cbd5e1 }

        .btn {
            width: 100%; margin-top: 10px; border: 0; border-radius: 14px;
            padding: 12px 16px;
            color: #0b1020; font-weight: 800; letter-spacing: .2px; cursor: pointer;
            background: linear-gradient(90deg, var(--brand), var(--brand2));
            box-shadow: 0 10px 30px color-mix(in srgb, var(--brand2) 35%, transparent);
            transition: transform .15s ease, box-shadow .2s ease, filter .2s ease;
        }
        .btn:hover { transform: translateY(-1px); filter: brightness(1.05) }
        .btn:active { transform: translateY(0) }

        .muted {
            text-align: center; font-size: .9rem;
            color: var(--muted); margin-top: 14px;
        }
        .muted a { color: var(--link); text-decoration: none; font-weight: 600; }
        .muted a:hover { text-decoration: underline; }

        .error {
            display: flex; gap: 10px; align-items: flex-start;
            background: rgba(239, 68, 68, .1); color: #fecaca;
            border: 1px solid rgba(239, 68, 68, .35);
            padding: 10px 12px; border-radius: 12px; margin: 0 0 12px;
        }

        .glow {
            position: absolute; inset: -2px;
            background:
                radial-gradient(400px 140px at 20% 0%, color-mix(in srgb, var(--brand) 15%, transparent), transparent 60%),
                radial-gradient(300px 160px at 100% 10%, color-mix(in srgb, var(--brand2) 20%, transparent), transparent 60%);
            z-index: -1; border-radius: 24px; filter: blur(10px); pointer-events: none;
        }

        @media (max-width:420px) { .wrap { padding: 16px } }
    </style>
</head>

<body>
    <div class="grid-bg"></div>

    <div class="wrap">
        <div class="logo">
            <a href="?page=painel" class="logo-link" aria-label="Login">
                <img class="logo-mark" src="<?= htmlspecialchars($wl['logo_url'], ENT_QUOTES, 'UTF-8') ?>" alt="Logotipo">
            </a>
        </div>

        <div class="card">
            <div class="glow"></div>

            <div class="title">Entrar</div>
            <div class="subtitle">Insira suas credenciais</div>

            <?php if ($flashError): ?>
                <div class="error" role="alert" aria-live="polite">
                    <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" fill="none" viewBox="0 0 24 24" stroke="currentColor" style="opacity:.9;flex:0 0 auto">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.6" d="M12 9v4m0 4h.01M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0Z" />
                    </svg>
                    <div><?= strip_tags($flashError, '<a><strong><b><br>') ?></div>
                </div>
            <?php endif; ?>

            <?php if ($error): ?>
                <div class="error" role="alert" aria-live="polite">
                    <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" fill="none" viewBox="0 0 24 24" stroke="currentColor" style="opacity:.9;flex:0 0 auto">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.6" d="M12 9v4m0 4h.01M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0Z" />
                    </svg>
                    <div><?= strip_tags($error, '<a><strong><b><br>') ?></div>
                </div>
            <?php endif; ?>

            <form method="post" action="" novalidate>
                <input type="hidden" name="csrf" value="<?= htmlspecialchars(csrf_token(), ENT_QUOTES, 'UTF-8') ?>">

                <div class="field">
                    <svg class="icon" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor">
                        <path stroke-width="1.6" stroke-linecap="round" d="M16 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2" />
                        <circle cx="12" cy="7" r="4" stroke-width="1.6" />
                    </svg>
                    <input id="email" name="email" type="email" placeholder="voce@exemplo.com" required autocomplete="email">
                </div>

                <div class="field">
                    <svg class="icon" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor">
                        <rect x="3" y="11" width="18" height="10" rx="2" stroke-width="1.6" />
                        <path d="M7 11v-1a5 5 0 1 1 10 0v1" stroke-width="1.6" stroke-linecap="round" />
                    </svg>
                    <input id="password" name="password" type="password" placeholder="********" required autocomplete="current-password">
                    <span class="right" id="togglePass">mostrar</span>
                </div>

                <button class="btn" type="submit">Entrar</button>
            </form>

            <div class="muted">Esqueceu a senha? <a href="forgot_password.php">Clique aqui</a></div>

            <?php if ($showSupport): ?>
            <div class="muted">
                Problemas no login?
                <a href="<?= htmlspecialchars($supportUrl, ENT_QUOTES, 'UTF-8') ?>"
                   target="<?= htmlspecialchars($supportTarget, ENT_QUOTES, 'UTF-8') ?>"
                   <?= $supportTarget === '_blank' ? 'rel="noopener noreferrer"' : '' ?>>Suporte</a>
            </div>
            <?php endif; ?>
        </div>
    </div>

    <script>
        const toggle = document.getElementById('togglePass');
        const pass = document.getElementById('password');
        toggle?.addEventListener('click', () => {
            const is = pass.type === 'password';
            pass.type = is ? 'text' : 'password';
            toggle.textContent = is ? 'ocultar' : 'mostrar';
        });
    </script>

</body>
</html>
