<?php require_once __DIR__ . '/../includes/header.php'; ?>

<div style="max-width:600px; margin:0 auto;">

    <div style="background:linear-gradient(135deg,#1e293b,#0f172a); border-radius:20px; padding:28px 32px; color:#f1f5f9; margin-bottom:24px;">
        <h1 style="font-size:1.6rem; font-weight:800; margin:0;">Meu Perfil</h1>
        <p style="color:#94a3b8; margin-top:4px; font-size:0.9rem;">Configurações da sua conta</p>
    </div>

    <?php if (!empty($success)): ?>
        <div style="background:rgba(34,197,94,0.1); color:#16a34a; border:1px solid #86efac; padding:12px 16px; border-radius:10px; margin-bottom:20px; font-weight:600;"><?= h($success) ?></div>
    <?php endif; ?>
    <?php if (!empty($error)): ?>
        <div style="background:rgba(239,68,68,0.1); color:#dc2626; border:1px solid #fca5a5; padding:12px 16px; border-radius:10px; margin-bottom:20px; font-weight:600;"><?= h($error) ?></div>
    <?php endif; ?>

    <!-- Dados pessoais -->
    <div style="background:#fff; border:1px solid #e2e8f0; border-radius:16px; padding:28px; margin-bottom:20px;">
        <h3 style="font-size:1rem; font-weight:800; color:#0f172a; margin:0 0 20px;">Dados Pessoais</h3>
        <form method="post" action="index.php?page=user_profile">
            <input type="hidden" name="csrf_token" value="<?= h(csrf_token()) ?>">
            <input type="hidden" name="action" value="update_profile">
            <div style="margin-bottom:16px;">
                <label style="display:block; font-size:0.85rem; font-weight:600; color:#475569; margin-bottom:6px;">Nome</label>
                <input type="text" name="name" value="<?= h($user['name']) ?>" required
                    style="width:100%; padding:11px 14px; border:1px solid #e2e8f0; border-radius:10px; font-size:0.95rem; color:#0f172a; outline:none;">
            </div>
            <div style="margin-bottom:16px;">
                <label style="display:block; font-size:0.85rem; font-weight:600; color:#475569; margin-bottom:6px;">E-mail</label>
                <input type="email" value="<?= h($user['email']) ?>" disabled
                    style="width:100%; padding:11px 14px; border:1px solid #e2e8f0; border-radius:10px; font-size:0.95rem; color:#94a3b8; background:#f8fafc; cursor:not-allowed;">
            </div>
            <div style="margin-bottom:20px;">
                <label style="display:block; font-size:0.85rem; font-weight:600; color:#475569; margin-bottom:6px;">Fuso Horário</label>
                <select name="timezone" style="width:100%; padding:11px 14px; border:1px solid #e2e8f0; border-radius:10px; font-size:0.95rem; color:#0f172a; background:#fff; outline:none;">
                    <?php
                    $tzUser = $user['timezone'] ?? 'America/Sao_Paulo';
                    $tzGroups = [
                        'Brasil' => ['America/Sao_Paulo'=>'São Paulo / Brasília (UTC-3)','America/Manaus'=>'Manaus (UTC-4)','America/Belem'=>'Belém / Fortaleza (UTC-3)','America/Recife'=>'Recife (UTC-3)','America/Cuiaba'=>'Cuiabá (UTC-4)','America/Porto_Velho'=>'Porto Velho (UTC-4)','America/Boa_Vista'=>'Boa Vista (UTC-4)','America/Rio_Branco'=>'Rio Branco / Acre (UTC-5)','America/Noronha'=>'Fernando de Noronha (UTC-2)'],
                        'América do Norte' => ['America/New_York'=>'Nova York (UTC-5)','America/Chicago'=>'Chicago (UTC-6)','America/Denver'=>'Denver (UTC-7)','America/Los_Angeles'=>'Los Angeles (UTC-8)','America/Toronto'=>'Toronto (UTC-5)','America/Vancouver'=>'Vancouver (UTC-8)','America/Mexico_City'=>'Cidade do México (UTC-6)'],
                        'América do Sul' => ['America/Argentina/Buenos_Aires'=>'Buenos Aires (UTC-3)','America/Lima'=>'Lima (UTC-5)','America/Bogota'=>'Bogotá (UTC-5)','America/Santiago'=>'Santiago (UTC-4)','America/Caracas'=>'Caracas (UTC-4)','America/Montevideo'=>'Montevidéu (UTC-3)'],
                        'Europa' => ['Europe/Lisbon'=>'Lisboa (UTC+0)','Europe/London'=>'Londres (UTC+0)','Europe/Madrid'=>'Madri (UTC+1)','Europe/Paris'=>'Paris (UTC+1)','Europe/Berlin'=>'Berlim (UTC+1)','Europe/Rome'=>'Roma (UTC+1)','Europe/Moscow'=>'Moscou (UTC+3)'],
                        'UTC' => ['UTC'=>'UTC (UTC+0)'],
                    ];
                    foreach ($tzGroups as $groupName => $tzList):
                    ?>
                        <optgroup label="<?= h($groupName) ?>">
                        <?php foreach ($tzList as $tz => $label): ?>
                            <option value="<?= h($tz) ?>" <?= $tzUser === $tz ? 'selected' : '' ?>><?= h($label) ?></option>
                        <?php endforeach; ?>
                        </optgroup>
                    <?php endforeach; ?>
                </select>
            </div>
            <button type="submit" style="background:#3b82f6; color:#fff; border:none; padding:11px 24px; border-radius:10px; font-weight:700; font-size:0.95rem; cursor:pointer;">Salvar alterações</button>
        </form>
    </div>

    <!-- 2FA -->
    <div style="background:#fff; border:1px solid #e2e8f0; border-radius:16px; padding:28px; margin-bottom:20px;">
        <h3 style="font-size:1rem; font-weight:800; color:#0f172a; margin:0 0 8px;">Autenticação em Dois Fatores (2FA)</h3>
        <p style="font-size:0.9rem; color:#64748b; margin:0 0 20px;">Adicione uma camada extra de segurança usando um app autenticador (Google Authenticator, Authy, etc).</p>
        <?php if (!empty($user['totp_enabled'])): ?>
            <div style="display:flex; align-items:center; gap:12px; margin-bottom:16px;">
                <span style="background:#dcfce7; color:#16a34a; border-radius:8px; padding:4px 12px; font-weight:700; font-size:0.85rem;">ATIVO</span>
                <span style="color:#64748b; font-size:0.9rem;">2FA está ativado na sua conta.</span>
            </div>
            <form method="post" action="index.php?page=user_profile">
                <input type="hidden" name="csrf_token" value="<?= h(csrf_token()) ?>">
                <input type="hidden" name="action" value="disable_2fa">
                <button type="submit" style="background:#ef4444; color:#fff; border:none; padding:11px 24px; border-radius:10px; font-weight:700; font-size:0.95rem; cursor:pointer;"
                    onclick="return confirm('Desativar o 2FA tornará sua conta menos segura. Confirmar?')">Desativar 2FA</button>
            </form>
        <?php else: ?>
            <div style="display:flex; align-items:center; gap:12px; margin-bottom:16px;">
                <span style="background:#fee2e2; color:#dc2626; border-radius:8px; padding:4px 12px; font-weight:700; font-size:0.85rem;">INATIVO</span>
                <span style="color:#64748b; font-size:0.9rem;">2FA não está ativado.</span>
            </div>
            <a href="index.php?page=setup_2fa" style="display:inline-block; background:#3b82f6; color:#fff; padding:11px 24px; border-radius:10px; font-weight:700; font-size:0.95rem; text-decoration:none;">Ativar 2FA</a>
        <?php endif; ?>
    </div>

    <!-- Alterar senha -->
    <div style="background:#fff; border:1px solid #e2e8f0; border-radius:16px; padding:28px;">
        <h3 style="font-size:1rem; font-weight:800; color:#0f172a; margin:0 0 20px;">Alterar Senha</h3>
        <form method="post" action="index.php?page=user_profile">
            <input type="hidden" name="csrf_token" value="<?= h(csrf_token()) ?>">
            <input type="hidden" name="action" value="change_password">
            <div style="margin-bottom:16px;">
                <label style="display:block; font-size:0.85rem; font-weight:600; color:#475569; margin-bottom:6px;">Senha atual</label>
                <input type="password" name="current_password" required
                    style="width:100%; padding:11px 14px; border:1px solid #e2e8f0; border-radius:10px; font-size:0.95rem; color:#0f172a;">
            </div>
            <div style="margin-bottom:16px;">
                <label style="display:block; font-size:0.85rem; font-weight:600; color:#475569; margin-bottom:6px;">Nova senha</label>
                <input type="password" name="new_password" required minlength="8"
                    style="width:100%; padding:11px 14px; border:1px solid #e2e8f0; border-radius:10px; font-size:0.95rem; color:#0f172a;">
            </div>
            <div style="margin-bottom:20px;">
                <label style="display:block; font-size:0.85rem; font-weight:600; color:#475569; margin-bottom:6px;">Confirmar nova senha</label>
                <input type="password" name="new_password_confirm" required minlength="8"
                    style="width:100%; padding:11px 14px; border:1px solid #e2e8f0; border-radius:10px; font-size:0.95rem; color:#0f172a;">
            </div>
            <button type="submit" style="background:#0f172a; color:#fff; border:none; padding:11px 24px; border-radius:10px; font-weight:700; font-size:0.95rem; cursor:pointer;">Alterar senha</button>
        </form>
    </div>

</div>

    <!-- Sessões recentes -->
    <?php
    try {
        $sessionRows = db()->prepare("SELECT ip_address, user_agent, created_at FROM user_sessions WHERE user_id = ? ORDER BY created_at DESC LIMIT 5");
        $sessionRows->execute([$user['id']]);
        $sessions = $sessionRows->fetchAll();
    } catch (Throwable $e) { $sessions = []; }
    if ($sessions):
    ?>
    <div style="background:#fff; border:1px solid #e2e8f0; border-radius:16px; padding:28px; margin-top:20px;">
        <h3 style="font-size:1rem; font-weight:800; color:#0f172a; margin:0 0 16px;">Acessos Recentes</h3>
        <table style="width:100%; border-collapse:collapse; font-size:0.88rem;">
            <thead>
                <tr style="background:#f8fafc; text-align:left;">
                    <th style="padding:8px 12px; color:#475569; font-weight:700; border-bottom:1px solid #e2e8f0;">Data/Hora</th>
                    <th style="padding:8px 12px; color:#475569; font-weight:700; border-bottom:1px solid #e2e8f0;">IP</th>
                    <th style="padding:8px 12px; color:#475569; font-weight:700; border-bottom:1px solid #e2e8f0;">Dispositivo</th>
                </tr>
            </thead>
            <tbody>
            <?php foreach ($sessions as $s): ?>
                <tr style="border-bottom:1px solid #f1f5f9;">
                    <td style="padding:8px 12px; color:#334155; font-family:monospace;"><?= h(date('d/m/Y H:i', strtotime($s['created_at']))) ?></td>
                    <td style="padding:8px 12px; color:#334155; font-family:monospace;"><?= h($s['ip_address']) ?></td>
                    <td style="padding:8px 12px; color:#64748b; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; max-width:260px;" title="<?= h($s['user_agent']) ?>"><?= h(substr($s['user_agent'], 0, 60)) ?><?= strlen($s['user_agent']) > 60 ? '…' : '' ?></td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php endif; ?>

<?php require_once __DIR__ . '/../includes/footer.php'; ?>
