<?php
/**
 * Página de Login - MontaLoja
 * Formulário de autenticação de clientes e donos de loja
 */

// Carregar configurações da loja (já inicia a sessão com o nome correto)
require_once __DIR__ . '/includes/store-config.php';

// Verificar se já está logado como cliente
if (isCustomerLoggedIn()) {
    header("Location: " . storeUrl("minha-conta"));
    exit;
}

// Verificar se já está logado como dono/admin da loja
if (isset($_SESSION['user_id']) && isset($_SESSION['user_store_id']) && $_SESSION['user_store_id'] == $currentStoreId) {
    header('Location: /dashboard.php');
    exit;
}

$error = '';
$success = '';

// Check for registration success message
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'] ?? '';
    $remember = isset($_POST['remember']);

    if (empty($email) || empty($password)) {
        $error = 'Preencha todos os campos.';
    } else {
        try {
            // PRIMEIRO: Verificar se é dono/admin da loja na tabela users
            $stmt = $pdo->prepare("
                SELECT * FROM users 
                WHERE store_id = ? AND email = ? AND is_active = 1 
                AND role IN ('owner', 'admin', 'employee')
                AND deleted_at IS NULL
            ");
            $stmt->execute([$currentStoreId, $email]);
            $user = $stmt->fetch(PDO::FETCH_ASSOC);

            if ($user && $user['password_hash'] && password_verify($password, $user['password_hash'])) {
                // Login de DONO/ADMIN - criar sessão de usuário
                $_SESSION['user_id'] = $user['id'];
                $_SESSION['user_name'] = $user['name'];
                $_SESSION['user_email'] = $user['email'];
                $_SESSION['user_role'] = $user['role'];
                $_SESSION['store_id'] = $currentStoreId; // usado pelo dashboard.php
                $_SESSION['user_store_id'] = $currentStoreId;
                $_SESSION['tenant_id'] = $currentStoreId;

                // Atualizar updated_at como indicador de último login
                $updateStmt = $pdo->prepare("UPDATE users SET updated_at = NOW() WHERE id = ?");
                $updateStmt->execute([$user['id']]);

                // Redirecionar para dashboard
                header('Location: /dashboard.php');
                exit;
            }

            // SEGUNDO: Se não é dono, verificar se é cliente na tabela customers
            $stmt = $pdo->prepare("SELECT * FROM customers WHERE store_id = ? AND email = ? AND is_active = 1");
            $stmt->execute([$currentStoreId, $email]);
            $customer = $stmt->fetch(PDO::FETCH_ASSOC);

            if ($customer && $customer['password'] && password_verify($password, $customer['password'])) {
                // Login de CLIENTE - criar sessão de cliente
                $_SESSION['customer_id'] = $customer['id'];
                $_SESSION['customer_name'] = $customer['name'];
                $_SESSION['customer_email'] = $customer['email'];
                $_SESSION['customer_store_id'] = $currentStoreId;

                // Atualizar last_login
                $updateStmt = $pdo->prepare("UPDATE customers SET last_login = NOW() WHERE id = ?");
                $updateStmt->execute([$customer['id']]);

                // Redirecionar para minha conta
                $redirect = $_SESSION['redirect_after_login'] ?? storeUrl("minha-conta");
                unset($_SESSION['redirect_after_login']);

                header("Location: " . $redirect);
                exit;
            } else {
                $error = 'Email ou senha incorretos.';
            }
        } catch (PDOException $e) {
            $error = 'Erro ao fazer login. Tente novamente.';
            error_log("Login error: " . $e->getMessage());
        }
    }
}
?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Entrar - <?php echo htmlspecialchars($storeName); ?></title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700;800&display=swap" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/iconify-icon@1.0.7/dist/iconify-icon.min.js"></script>
<link rel="stylesheet" href="/pages/storefront/templates/retail/modern/includes/styles.css?v=1.0.4">
<?php include __DIR__ . "/includes/dynamic-styles.php"; ?>
<style>
/* Dynamic Color Variables from Store Settings */
:root {
    --primary: <?php echo htmlspecialchars($primaryColor ?? '#2563EB'); ?>;
    --primary-soft: <?php echo htmlspecialchars($primaryColor ?? '#2563EB'); ?>14;
    --primary-hover: <?php echo htmlspecialchars($customSettings['colors']['secondary'] ?? $primaryColor ?? '#1D4ED8'); ?>;
    --accent: <?php echo htmlspecialchars($accentColor ?? '#10B981'); ?>;
    --accent-soft: <?php echo htmlspecialchars($accentColor ?? '#10B981'); ?>1A;
    --bg: <?php echo htmlspecialchars($bgColor ?? '#FAFBFC'); ?>;
    --bg-white: <?php echo htmlspecialchars($cardColor ?? '#FFFFFF'); ?>;
    --surface: <?php echo htmlspecialchars($cardColor ?? '#FFFFFF'); ?>;
    --text: <?php echo htmlspecialchars($textColor ?? '#111827'); ?>;
    --text-secondary: <?php echo htmlspecialchars($textSecondary ?? '#6B7280'); ?>;
}

.main-content {
    display: flex;
    align-items: center;
    justify-content: center;
    min-height: calc(100vh - 200px);
    padding: 24px;
}

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

.auth-card {
    background: var(--surface);
    border-radius: var(--radius-lg);
    border: 1px solid var(--border);
    padding: 40px;
    box-shadow: var(--shadow);
}

.auth-header {
    text-align: center;
    margin-bottom: 32px;
}

.auth-icon {
    width: 64px;
    height: 64px;
    border-radius: 50%;
    background: var(--primary-soft);
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 0 auto 16px;
    color: var(--primary);
}

.auth-title {
    font-size: 1.75rem;
    font-weight: 800;
    color: var(--text);
    margin-bottom: 8px;
}

.auth-subtitle {
    color: var(--text-secondary);
    font-size: 0.95rem;
}

.form-group {
    margin-bottom: 20px;
}

.form-label {
    display: block;
    font-weight: 600;
    font-size: 0.9rem;
    color: var(--text);
    margin-bottom: 8px;
}

.form-input {
    width: 100%;
    height: 52px;
    padding: 0 16px;
    border: 1px solid var(--border);
    border-radius: var(--radius);
    background: var(--bg);
    font-size: 1rem;
    color: var(--text);
    transition: all 0.2s;
    font-family: inherit;
    box-sizing: border-box;
}

.form-input:focus {
    outline: none;
    border-color: var(--primary);
    background: var(--surface);
    box-shadow: 0 0 0 3px var(--primary-soft);
}

.input-wrapper {
    position: relative;
}

.input-wrapper .input-icon {
    position: absolute;
    left: 16px;
    top: 50%;
    transform: translateY(-50%);
    color: var(--muted);
    font-size: 1.2rem;
}

.input-wrapper .form-input {
    padding-left: 48px;
}

.input-wrapper .toggle-password {
    position: absolute;
    right: 16px;
    top: 50%;
    transform: translateY(-50%);
    background: none;
    border: none;
    color: var(--muted);
    cursor: pointer;
    padding: 4px;
}

.form-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
}

.checkbox-wrapper {
    display: flex;
    align-items: center;
    gap: 8px;
}

.checkbox-wrapper input {
    width: 18px;
    height: 18px;
    accent-color: var(--primary);
}

.checkbox-wrapper label {
    font-size: 0.9rem;
    color: var(--text-secondary);
    cursor: pointer;
}

.forgot-link {
    color: var(--primary);
    text-decoration: none;
    font-size: 0.9rem;
    font-weight: 500;
}

.btn-submit {
    width: 100%;
    height: 52px;
    background: var(--primary);
    color: white;
    border: none;
    border-radius: var(--radius);
    font-weight: 700;
    font-size: 1rem;
    cursor: pointer;
    transition: all 0.2s;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    font-family: inherit;
}

.btn-submit:hover {
    background: var(--primary-hover);
    transform: translateY(-2px);
}

.divider {
    display: flex;
    align-items: center;
    gap: 16px;
    margin: 28px 0;
}

.divider::before,
.divider::after {
    content: '';
    flex: 1;
    height: 1px;
    background: var(--border);
}

.divider span {
    color: var(--muted);
    font-size: 0.85rem;
}

.btn-social {
    width: 100%;
    height: 52px;
    background: var(--surface);
    border: 1px solid var(--border);
    border-radius: var(--radius);
    font-weight: 600;
    font-size: 0.95rem;
    cursor: pointer;
    transition: all 0.2s;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 10px;
    font-family: inherit;
    color: var(--text);
}

.btn-social:hover {
    background: var(--surface-hover);
    border-color: var(--primary);
}

.register-link {
    text-align: center;
    margin-top: 28px;
    color: var(--text-secondary);
    font-size: 0.95rem;
}

.register-link a {
    color: var(--primary);
    text-decoration: none;
    font-weight: 600;
}

.alert {
    padding: 14px 16px;
    border-radius: var(--radius);
    margin-bottom: 24px;
    font-size: 0.9rem;
    display: flex;
    align-items: center;
    gap: 10px;
}

.alert-error {
    background: rgba(239, 68, 68, 0.1);
    color: #EF4444;
    border: 1px solid rgba(239, 68, 68, 0.2);
}

.alert-success {
    background: rgba(16, 185, 129, 0.1);
    color: #10B981;
    border: 1px solid rgba(16, 185, 129, 0.2);
}

.back-link {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 24px;
    color: var(--text-secondary);
    text-decoration: none;
    font-size: 0.9rem;
}

.back-link:hover {
    color: var(--primary);
}

@media (max-width: 768px) {
    .auth-card {
        padding: 28px 20px;
    }
    .form-footer {
        flex-direction: column;
        gap: 12px;
        align-items: flex-start;
    }
}
</style>
</head>
<body>

<?php include __DIR__ . '/../../../includes/cart.php'; ?>

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

<main class="main-content">
    <div class="auth-container">
        <a href="<?php echo storeUrl(); ?>" class="back-link">
            <iconify-icon icon="solar:arrow-left-linear" width="20"></iconify-icon>
            Voltar para a loja
        </a>

        <div class="auth-card">
            <div class="auth-header">
                <div class="auth-icon">
                    <iconify-icon icon="solar:user-bold" width="32"></iconify-icon>
                </div>
                <h1 class="auth-title">Bem-vindo de volta!</h1>
                <p class="auth-subtitle">Entre na sua conta para continuar</p>
            </div>

            <?php if ($error): ?>
            <div class="alert alert-error">
                <iconify-icon icon="solar:danger-triangle-bold" width="20"></iconify-icon>
                <?php echo htmlspecialchars($error); ?>
            </div>
            <?php endif; ?>

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

            <form method="POST" id="loginForm">
                <div class="form-group">
                    <label class="form-label">Email</label>
                    <div class="input-wrapper">
                        <iconify-icon icon="solar:letter-bold" class="input-icon"></iconify-icon>
                        <input type="email" name="email" class="form-input" placeholder="seu@email.com" required
                               value="<?php echo htmlspecialchars($_POST['email'] ?? ''); ?>">
                    </div>
                </div>

                <div class="form-group">
                    <label class="form-label">Senha</label>
                    <div class="input-wrapper">
                        <iconify-icon icon="solar:lock-bold" class="input-icon"></iconify-icon>
                        <input type="password" name="password" id="password" class="form-input" placeholder="••••••••" required>
                        <button type="button" class="toggle-password" onclick="togglePassword()">
                            <iconify-icon icon="solar:eye-bold" id="eye-icon" width="20"></iconify-icon>
                        </button>
                    </div>
                </div>

                <div class="form-footer">
                    <div class="checkbox-wrapper">
                        <input type="checkbox" id="remember" name="remember">
                        <label for="remember">Lembrar de mim</label>
                    </div>
                    <a href="<?php echo storeUrl('recuperar-senha'); ?>" class="forgot-link">Esqueci a senha</a>
                </div>

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

            <div class="divider">
                <span>ou continue com</span>
            </div>

            <button type="button" class="btn-social" onclick="alert('Login com Google em breve!')">
                <iconify-icon icon="logos:google-icon"></iconify-icon>
                Google
            </button>

            <p class="register-link">
                Não tem uma conta? <a href="<?php echo storeUrl('registrar'); ?>">Criar conta</a>
            </p>
        </div>
    </div>
</main>

<?php include __DIR__ . '/includes/footer.php'; ?>
<script>
function togglePassword() {
    const passwordInput = document.getElementById('password');
    const eyeIcon = document.getElementById('eye-icon');
    if (passwordInput.type === 'password') {
        passwordInput.type = 'text';
        eyeIcon.setAttribute('icon', 'solar:eye-closed-bold');
    } else {
        passwordInput.type = 'password';
        eyeIcon.setAttribute('icon', 'solar:eye-bold');
    }
}
</script>

</body>
</html>
