<?php
// /app/public/definir_senha.php — visual igual ao login.php (white label)
session_start();

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';

// DEBUG TEMPORÁRIO (remova depois)
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Carrega config white label (mesma usada no login)
$wl = wl_login();

$pdo   = db();
$error = null;
$ok    = null;

// Lê token via GET
$token = isset($_GET['token']) ? trim($_GET['token']) : '';

// Busca usuário pelo token válido (não expirado)
$user = null;
if ($token !== '') {
    $stmt = $pdo->prepare('
        SELECT id, email, name, reset_expires
        FROM public.auth_users
        WHERE reset_token = :t
        LIMIT 1
    ');
    $stmt->execute([':t' => $token]);
    $user = $stmt->fetch();
    if (!$user) {
        $error = 'Senha já definida, realize o login clicando abaixo.';
    } else {
        $exp = new DateTimeImmutable($user['reset_expires'] ?? '1970-01-01 00:00:00');
        $now = new DateTimeImmutable('now');
        if ($now > $exp) {
            $error = 'Senha já definida, realize o login clicando abaixo.';
            $user  = null;
        }
    }
} else {
    $error = 'Token ausente. Use o link recebido.';
}

// POST: definir senha
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $user) {
    $csrf = $_POST['csrf'] ?? '';
    $p1   = trim($_POST['password'] ?? '');
    $p2   = trim($_POST['password2'] ?? '');

    if (!csrf_verify($csrf)) {
        $error = 'Sessão expirada. Recarregue a página.';
    } elseif ($p1 === '' || $p2 === '') {
        $error = 'Informe e confirme a nova senha.';
    } elseif ($p1 !== $p2) {
        $error = 'As senhas não coincidem.';
    } elseif (strlen($p1) < 8) {
        $error = 'A senha deve ter pelo menos 8 caracteres.';
    } else {
        $hash = password_hash($p1, PASSWORD_BCRYPT, ['cost' => 10]);

        $up = $pdo->prepare('
            UPDATE public.auth_users
            SET password_hash = :h,
                reset_token   = NULL,
                reset_expires = NULL
            WHERE id = :id
        ');

        $okUpdate = $up->execute([':h' => $hash, ':id' => $user['id']]);

        if ($okUpdate) {
            $ok   = 'Senha definida com sucesso! Já pode fazer login.';
            $user = null; // força esconder o form
        } else {
            $error = 'Não foi possível definir a senha. Tente novamente.';
        }
    }
}
?>
<!doctype html>
<html lang="pt-br">
<head>
    <meta charset="utf-8">
    <title>Definir senha</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;
            --ok: #10b981;
        }

        * { 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 {
            position: relative;
            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: 800 }
        .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; }

        .hint { font-size: .85rem; color: var(--muted); text-align: center; margin-top: 10px; }

        .msg {
            display: flex; gap: 10px; align-items: flex-start;
            padding: 10px 12px; border-radius: 12px; margin: 0 0 12px;
            font-size: .93rem; border: 1px solid;
        }
        .msg.error { background: rgba(239, 68, 68, .1); color: #fecaca; border-color: rgba(239, 68, 68, .35); }
        .msg.success { background: rgba(16, 185, 129, .08); color: #a7f3d0; border-color: rgba(16, 185, 129, .35); }

        .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="login.php" 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">Definir nova senha</div>
            <div class="subtitle">Crie sua senha para acessar o sistema</div>

            <?php if ($ok): ?>
                <div class="msg success" 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="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
                    </svg>
                    <div><?= htmlspecialchars($ok) ?></div>
                </div>
                <div class="muted"><a href="login.php">Ir para a página de login</a></div>

            <?php elseif ($error): ?>
                <div class="msg 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><?= htmlspecialchars($error) ?></div>
                </div>
                <?php if (!$user): ?>
                    <div class="muted"><a href="login.php">Fazer login</a></div>
                <?php endif; ?>
            <?php endif; ?>

            <?php if ($user): ?>
                <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">
                            <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" type="password" name="password" placeholder="Nova senha (mínimo 8 caracteres)" required autocomplete="new-password">
                        <span class="right" id="togglePass">mostrar</span>
                    </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="password2" type="password" name="password2" placeholder="Confirme a nova senha" required autocomplete="new-password">
                        <span class="right" id="togglePass2">mostrar</span>
                    </div>

                    <button class="btn" type="submit">Salvar senha</button>

                    <p class="hint">
                        Válido para: <strong><?= htmlspecialchars($user['email']) ?></strong><br>
                        Expira em <?= (new DateTimeImmutable($user['reset_expires']))->format('d/m/Y H:i') ?>
                    </p>
                </form>
            <?php endif; ?>
        </div>
    </div>

    <script>
        function bindToggle(toggleId, inputId) {
            const t = document.getElementById(toggleId);
            const i = document.getElementById(inputId);
            if (!t || !i) return;
            t.addEventListener('click', () => {
                const is = i.type === 'password';
                i.type = is ? 'text' : 'password';
                t.textContent = is ? 'ocultar' : 'mostrar';
            });
        }
        bindToggle('togglePass',  'password');
        bindToggle('togglePass2', 'password2');
    </script>
</body>
</html>