<?php
/**
 * Página de Login - MontaLoja
 * Usa header e footer do template landing_v1
 * Suporta login de usuários normais e super admins
 */
require_once __DIR__ . '/../includes/config.php';

$pdo = getDB();
$error = '';
$success = '';

// Se já está logado, redirecionar
if (isset($_SESSION['is_super_admin']) && $_SESSION['is_super_admin']) {
    header('Location: /pages/superadmin/dashboard.php');
    exit;
}

if (isset($_SESSION['user_id'])) {
    if ($_SESSION['user_role'] === 'admin') {
        header('Location: /pages/superadmin/dashboard.php');
    } else {
        header('Location: /dashboard.php');
    }
    exit;
}

// Mensagem de registro bem sucedido
if (isset($_GET['logout'])) {
    $success = 'Você foi desconectado com sucesso.';
}

if (isset($_GET['registered'])) {
    $success = 'Conta criada com sucesso! Faça login para continuar.';
}

// Processar login
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $email = trim($_POST['email'] ?? '');
    $password = $_POST['password'] ?? '';

    if (empty($email) || empty($password)) {
        $error = 'Preencha todos os campos.';
    } else {
        $loginSuccess = false;
        
        // 1. Primeiro, verificar na tabela super_admins
        $stmt = $pdo->prepare('SELECT * FROM super_admins WHERE email = ? AND is_active = 1');
        $stmt->execute([$email]);
        $superAdmin = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($superAdmin && password_verify($password, $superAdmin['password_hash'])) {
            // Login como Super Admin
            $_SESSION['is_super_admin'] = true;
            $_SESSION['super_admin_id'] = $superAdmin['id'];
            $_SESSION['user_name'] = $superAdmin['name'] ?? 'Super Admin';
            $_SESSION['user_email'] = $superAdmin['email'];

            // Atualizar último login
            $pdo->prepare('UPDATE super_admins SET last_login_at = NOW() WHERE id = ?')->execute([$superAdmin['id']]);

            header('Location: /pages/superadmin/dashboard.php');
            exit;
        }
        
        // 2. Se não for super admin, verificar na tabela users
        $stmt = $pdo->prepare("
            SELECT u.*, s.name as store_name, s.slug as store_slug, s.status as store_status
            FROM users u
            LEFT JOIN stores s ON u.store_id = s.id
            WHERE u.email = ? AND u.is_active = 1
        ");
        $stmt->execute([$email]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($user && password_verify($password, $user['password_hash'])) {
            // Login bem sucedido como usuário normal
            $_SESSION['user_id'] = $user['id'];
            $_SESSION['user_name'] = $user['name'];
            $_SESSION['user_email'] = $user['email'];
            $_SESSION['user_role'] = $user['role'];
            $_SESSION['store_id'] = $user['store_id'];
            $_SESSION['store_name'] = $user['store_name'];
            $_SESSION['store_slug'] = $user['store_slug'];

            // Redirecionar baseado no role
            if ($user['role'] === 'admin') {
                header('Location: /pages/superadmin/dashboard.php');
            } else {
                header('Location: /dashboard.php');
            }
            exit;
        }
        
        // Se chegou aqui, login falhou
        $error = 'E-mail ou senha incorretos.';
    }
}

// Incluir header do template
include __DIR__ . '/../templates/landing_v1/header.php';

// RGB para gradientes (usar variáveis do header)
$r = hexdec(substr($themeColors['primary'], 1, 2));
$g = hexdec(substr($themeColors['primary'], 3, 2));
$b = hexdec(substr($themeColors['primary'], 5, 2));
?>

<style>
/* ========================================
   ESTILOS ESPECÍFICOS DA PÁGINA DE LOGIN
   ======================================== */
body {
    min-height: 100vh;
    display: flex;
    flex-direction: column;
}

.bg-pattern {
    position: fixed;
    inset: 0;
    background: radial-gradient(circle at 20% 80%, rgba(<?php echo "$r, $g, $b"; ?>, 0.1) 0%, transparent 50%),
                radial-gradient(circle at 80% 20%, rgba(<?php echo "$r, $g, $b"; ?>, 0.08) 0%, transparent 50%);
    pointer-events: none;
    z-index: 0;
}

.main-content {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 100px 25px 165px 25px;
    position: relative;
    z-index: 1;
}

.login-container {
    width: 100%;
    max-width: 420px;
}

.login-header {
    text-align: center;
    margin-bottom: 2rem;
}

.login-header h1 {
    font-size: 1.75rem;
    margin-bottom: .5rem;
}

.login-header h1 span {
    background: var(--gradient-gold);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    background-clip: text;
}

.login-header p {
    color: var(--text-muted);
}

.login-form {
    background: var(--bg-card);
    border: 1px solid var(--border);
    border-radius: 16px;
    padding: 2rem;
}

.form-group {
    margin-bottom: 1.25rem;
}

.form-label {
    display: block;
    margin-bottom: .5rem;
    font-weight: 500;
    font-size: .9rem;
}

.form-input {
    width: 100%;
    padding: .875rem 1rem;
    background: var(--bg-darker);
    border: 2px solid var(--border);
    border-radius: 8px;
    color: var(--text-primary);
    font-size: 1rem;
    transition: all .3s;
}

.form-input:focus {
    outline: none;
    border-color: var(--gold);
    box-shadow: 0 0 0 4px rgba(<?php echo "$r, $g, $b"; ?>, 0.15);
}

.form-input::placeholder {
    color: var(--text-muted);
}

.btn-login {
    width: 100%;
    padding: 1rem;
    margin-top: 0.5rem;
}

.alert {
    padding: 1rem;
    border-radius: 8px;
    margin-bottom: 1.5rem;
    display: flex;
    align-items: center;
    gap: .75rem;
    font-size: .9rem;
}

.alert-error {
    background: rgba(239, 68, 68, 0.15);
    border: 1px solid rgba(239, 68, 68, 0.3);
    color: #FCA5A5;
}

.alert-success {
    background: rgba(34, 197, 94, 0.15);
    border: 1px solid rgba(34, 197, 94, 0.3);
    color: #86EFAC;
}

.forgot-password {
    display: block;
    text-align: right;
    margin-top: .5rem;
    font-size: .85rem;
    color: var(--text-muted);
}

.forgot-password a {
    color: var(--gold);
    text-decoration: none;
}

.forgot-password a:hover {
    text-decoration: underline;
}

.register-cta {
    text-align: center;
    margin-top: 2rem;
    padding: 1.5rem;
    background: rgba(<?php echo "$r, $g, $b"; ?>, 0.1);
    border: 1px solid rgba(<?php echo "$r, $g, $b"; ?>, 0.2);
    border-radius: 12px;
}

.register-cta p {
    color: var(--text-secondary);
    margin-bottom: 1rem;
}

.register-cta a {
    display: inline-flex;
    align-items: center;
    gap: .5rem;
    color: var(--gold);
    font-weight: 600;
    text-decoration: none;
}

.register-cta a:hover {
    text-decoration: underline;
}

@media(max-width: 767px) {
    .main-content { padding-top: 165px; }
}
</style>

<div class="bg-pattern"></div>

<!-- MAIN CONTENT -->
<main class="main-content">
    <div class="login-container">
        <div class="login-header">
            <h1>Bem-vindo de <span>volta</span>!</h1>
            <p>Entre na sua conta para continuar</p>
        </div>

        <form class="login-form" method="POST" action="">
            <?php if ($error): ?>
            <div class="alert alert-error">
                <iconify-icon icon="solar:danger-triangle-bold"></iconify-icon>
                <?php echo htmlspecialchars($error); ?>
            </div>
            <?php endif; ?>

            <?php if ($success): ?>
            <div class="alert alert-success">
                <iconify-icon icon="solar:check-circle-bold"></iconify-icon>
                <?php echo htmlspecialchars($success); ?>
            </div>
            <?php endif; ?>

            <div class="form-group">
                <label class="form-label">E-mail</label>
                <input type="email" name="email" class="form-input" placeholder="seu@email.com" required value="<?php echo htmlspecialchars($_GET['email'] ?? $_POST['email'] ?? ''); ?>">
            </div>

            <div class="form-group">
                <label class="form-label">Senha</label>
                <input type="password" name="password" class="form-input" placeholder="Sua senha" required>
                <span class="forgot-password"><a href="#">Esqueceu a senha?</a></span>
            </div>

            <button type="submit" class="btn btn-primary btn-login">
                <iconify-icon icon="solar:login-2-bold"></iconify-icon>
                Entrar
            </button>
        </form>

        <div class="register-cta">
            <p>Ainda não tem uma conta?</p>
            <a href="/pages/cadastro/">
                <iconify-icon icon="solar:add-circle-bold"></iconify-icon>
                Criar conta gratuita
            </a>
        </div>
    </div>
</main>

<?php
// Incluir footer do template
include __DIR__ . '/../templates/landing_v1/footer.php';
?>
