<?php
// public/forgot_password.php — visual igual ao login.php (white label)

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/mailer.php';
require_once BASE_PATH . '/app/whitelabel.php';

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

$success = null;
$error = null;

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

    if (!csrf_verify($token)) {
        $error = "Sessão expirada. Recarregue a página.";
    } elseif ($email === '') {
        $error = "Informe o e-mail.";
    } else {
        try {
            $pdo = db();
            $stmt = $pdo->prepare("SELECT id, name FROM public.auth_users WHERE email = :email LIMIT 1");
            $stmt->execute([':email' => $email]);
            $user = $stmt->fetch();

            if ($user) {
                $resetToken = bin2hex(random_bytes(32));
                $expires    = date('Y-m-d H:i:s', strtotime('+7 days'));

                $pdo->prepare("
                    UPDATE public.auth_users
                    SET reset_token = :token, reset_expires = :exp
                    WHERE id = :id
                ")->execute([
                    ':token' => $resetToken,
                    ':exp'   => $expires,
                    ':id'    => $user['id'],
                ]);

                $base = defined('APP_BASE_URL')
                    ? rtrim(APP_BASE_URL, '/') . '/'
                    : (defined('BASE_URL') ? rtrim(BASE_URL, '/') . '/' : 'https://app.backendevoluaspy.space/app/public/');
                $link = $base . 'definir_senha.php?token=' . urlencode($resetToken);

                $nome    = $user['name'] ?: 'Usuário';
                $subject = smtp_get_subject_reset();  // ← vem do banco (configurado pelo admin)

                $html = '
                    <p>Olá <strong>' . htmlspecialchars($nome) . '</strong>,</p>
                    <p>Recebemos uma solicitação para definir/redefinir sua senha.</p>
                    <p><a href="' . htmlspecialchars($link) . '" target="_blank" style="display:inline-block;padding:12px 18px;background:' . htmlspecialchars($wl['brand2']) . ';color:#fff;border-radius:10px;text-decoration:none">
                    Definir minha senha</a></p>
                    <p>Ou copie e cole no navegador:<br>' . htmlspecialchars($link) . '</p>
                    <p>Este link expira em <strong>7 dias</strong>.</p>
                    <hr>
                    <p style="color:#6b7280;font-size:12px">Se você não solicitou, ignore este e-mail.</p>
                ';

                send_system_email($email, $subject, $html);
            }

            $success = "Se o e-mail existir, enviaremos instruções para definir a senha.";

        } catch (Throwable $e) {
            $error = "Não foi possível processar sua solicitação agora.";
        }
    }
}
?>
<!doctype html>
<html lang="pt-br">
<head>
    <meta charset="utf-8">
    <title>Esqueci minha 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;
        }

        .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; }

        .msg {
            display: flex; gap: 10px; align-items: flex-start;
            padding: 10px 12px; border-radius: 12px; margin: 12px 0 0;
            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="Voltar ao 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">Esqueci minha senha</div>
            <div class="subtitle">Informe seu e-mail e enviaremos instruções</div>

            <form method="post" 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="M4 7a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V7Z" />
                        <path stroke-width="1.6" d="m22 7-10 6L2 7" />
                    </svg>
                    <input type="email" name="email" placeholder="voce@exemplo.com" required autocomplete="email">
                </div>

                <button class="btn" type="submit">Enviar instruções</button>
            </form>

            <?php if ($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><?= $error ?></div>
                </div>
            <?php endif; ?>

            <?php if ($success): ?>
                <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><?= $success ?></div>
                </div>
            <?php endif; ?>

            <div class="muted">
                <a href="login.php">Voltar ao login</a>
            </div>
        </div>
    </div>
</body>
</html>