<?php
// Garantir que a função asset() esteja disponível
if (!function_exists('asset')) {
    require_once __DIR__ . '/../../src/Helpers/GlobalHelpers.php';
}

// Inicializar SkinHelper
use App\Helpers\SkinHelper;

// Conectar ao banco para o SkinHelper (já que não temos BaseController aqui)
try {
    $dbConfig = require __DIR__ . '/../../config/database.php';
    $master = $dbConfig['master'];
    $dsn = sprintf(
        '%s:host=%s;port=%d;dbname=%s;charset=%s',
        $master['driver'],
        $master['host'],
        $master['port'],
        $master['database'],
        $master['charset']
    );
    $db = new PDO($dsn, $master['username'], $master['password'], $master['options']);
    SkinHelper::setDatabase($db);
} catch (Exception $e) {
    error_log("Erro ao conectar banco no login: " . $e->getMessage());
}

$skinDisplayName = SkinHelper::getDisplayName();
$skinLogo = SkinHelper::getLogo();
$skinConfig = SkinHelper::getSkinConfig();
$activeSkin = SkinHelper::getActiveSkin();

// Cores específicas para cada skin na tela de login
if ($activeSkin === 'aurion') {
    $skinPrimaryColor = '#3788D8'; // Azul para botões
    $skinDarkBg = '#001223'; // Background escuro
    $loginSidebarBg = '#001223'; // Background da sidebar
} else {
    // Sanctus ou outras skins
    $skinPrimaryColor = SkinHelper::getColor('primary') ?? '#122763';
    $skinDarkBg = '#F8F9FA'; // Background claro
    $loginSidebarBg = '#FFFFFF'; // Background branco da sidebar
}
?>
<!DOCTYPE html>
<html lang="pt-BR">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Acesso ao Sistema | <?= htmlspecialchars($skinDisplayName) ?></title>

    <!-- Favicon da skin -->
    <link rel="icon" type="image/png" href="<?= SkinHelper::getFavicon() ?>">

    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">

    <!-- Bootstrap Icons -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.0/font/bootstrap-icons.css" rel="stylesheet">

    <!-- Google Fonts -->
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">

    <!-- Define appUrl e APP_BASE_PATH ANTES de qualquer script que possa usá-lo -->
    <script>
        (function () {
            // Detecta o diretório base dinamicamente baseado no caminho atual
            const currentPath = window.location.pathname;
            const pathParts = currentPath.split('/').filter(p => p);

            // Se estiver em um subdiretório (ex: /Systhema, /printjetdigital)
            let detectedBase = '';
            if (pathParts.length > 0 && pathParts[0] !== '') {
                detectedBase = '/' + pathParts[0];
            }

            const normalizedBase = detectedBase === '/' ? '' : detectedBase;
            window.APP_BASE_PATH = normalizedBase;

            window.appUrl = function (path = '/') {
                const safePath = typeof path === 'string' ? path : '';
                const normalizedPath = '/' + safePath.replace(/^\/+/, '');

                // Se não tem base path, retorna apenas o path normalizado
                if (!window.APP_BASE_PATH) {
                    return normalizedPath;
                }

                // Retorna base + path (ex: /Systhema/dashboard ou /printjetdigital/dashboard)
                return window.APP_BASE_PATH + normalizedPath;
            };

            window.url = window.appUrl;
        })();
    </script>

    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        :root {
            --primary: <?= $skinPrimaryColor ?>;
            --primary-dark: <?= $skinPrimaryColor ?>;
            --secondary: #00B4D8;
            --accent: #FF6B35;
            --bg-light: #F8F9FA;
            --bg-white: #FFFFFF;
            --text-dark: #1A1A1A;
            --text-gray: #6C757D;
            --border-light: #E0E6ED;
            --shadow: rgba(0, 0, 0, 0.08);
        }

        body {
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
            background: <?= $skinDarkBg ?>;
            height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 0;
            overflow: hidden;
        }

        .login-wrapper {
            display: flex;
            width: 100%;
            height: 100vh;
            max-height: 100vh;
            background: var(--bg-white);
            overflow: hidden;
            box-shadow: 0 20px 60px var(--shadow), 0 0 0 1px rgba(0, 0, 0, 0.05);
        }

        .login-sidebar {
            flex: 0 0 50%;
            width: 50%;
            background: <?= $loginSidebarBg ?>;
            padding: 3rem;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            position: relative;
            overflow: hidden;
        }

        .login-sidebar::before {
            content: '';
            position: absolute;
            top: -50%;
            right: -50%;
            width: 100%;
            height: 100%;
            background: radial-gradient(circle, rgba(255, 255, 255, 0.1) 0%, transparent 70%);
            animation: pulse 8s ease-in-out infinite;
        }

        @keyframes pulse {

            0%,
            100% {
                transform: scale(1);
                opacity: 0.3;
            }

            50% {
                transform: scale(1.1);
                opacity: 0.5;
            }
        }

        .sidebar-content {
            position: relative;
            z-index: 1;
            flex: 1;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
        }

        .aurion-logo-container {
            text-align: center;
            width: 100%;
            max-width: 100%;
            margin: 0 auto;
            display: flex;
            align-items: center;
            justify-content: center;
            height: 100%;
        }

        .aurion-logo-container img {
            max-width: 900px;
            width: auto;
            height: auto;
            max-height: 700px;
            object-fit: contain;
            display: block;
            margin: 0 auto;
        }

        .company-info {
            margin-top: 2rem;
            padding-top: 1.5rem;
            border-top: 1px solid var(--border-light);
            font-size: 0.75rem;
            color: var(--text-gray);
            text-align: center;
            line-height: 1.5;
        }

        .company-info strong {
            color: var(--text-dark);
            font-weight: 600;
        }

        .login-form-section {
            flex: 0 0 50%;
            width: 50%;
            padding: 3rem;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            background: var(--bg-white);
            overflow-y: auto;
        }

        .login-form-container {
            width: 100%;
            max-width: 420px;
            margin: 0 auto;
            display: flex;
            flex-direction: column;
            justify-content: center;
        }

        .client-logo-container {
            text-align: center;
            margin-bottom: 2rem;
            padding: 1.5rem;
            background: linear-gradient(135deg, #F8F9FA 0%, #FFFFFF 100%);
            border-radius: 12px;
            border: 2px solid var(--border-light);
        }

        .client-logo-container img {
            max-width: 180px;
            max-height: 70px;
            object-fit: contain;
            transition: transform 0.3s;
        }

        .client-logo-container img:hover {
            transform: scale(1.05);
        }

        .client-logo-container p {
            margin-top: 0.5rem;
            margin-bottom: 0;
            font-size: 0.8rem;
            color: var(--text-gray);
            font-weight: 500;
        }

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

        .form-title {
            font-size: 1.5rem;
            font-weight: 700;
            margin-bottom: 0.25rem;
            color: var(--primary);
        }

        .form-subtitle {
            font-size: 0.85rem;
            color: var(--text-gray);
        }

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

        .form-label {
            display: block;
            margin-bottom: 0.4rem;
            color: var(--text-dark);
            font-weight: 600;
            font-size: 0.8rem;
        }

        .form-control {
            width: 100%;
            padding: 0.75rem 0.875rem;
            background: var(--bg-light);
            border: 2px solid var(--border-light);
            border-radius: 8px;
            color: var(--text-dark);
            font-size: 0.9rem;
            transition: all 0.3s;
        }

        .form-control:focus {
            outline: none;
            background: var(--bg-white);
            border-color: var(--primary);
            box-shadow: 0 0 0 3px rgba(0, 18, 35, 0.1);
        }

        .form-control::placeholder {
            color: var(--text-gray);
        }

        .btn-login {
            width: 100%;
            padding: 0.875rem;
            background: <?= $skinPrimaryColor ?>;
            border: none;
            border-radius: 8px;
            color: white;
            font-weight: 600;
            font-size: 0.9rem;
            cursor: pointer;
            transition: all 0.3s;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            box-shadow: 0 4px 12px rgba(0, 18, 35, 0.2);
        }

        .btn-login:hover {
            transform: translateY(-2px);
            <?php if ($activeSkin === 'aurion'): ?>
            background: #2a6fb8;
            <?php else: ?>
            background: <?= $skinPrimaryColor ?>;
            opacity: 0.9;
            <?php endif; ?>
            box-shadow: 0 8px 20px rgba(0, 18, 35, 0.3);
        }

        .btn-login:active {
            transform: translateY(0);
        }

        .divider {
            margin: 1.2rem 0;
            text-align: center;
            position: relative;
        }

        .divider::before {
            content: '';
            position: absolute;
            left: 0;
            top: 50%;
            width: 100%;
            height: 1px;
            background: var(--border-light);
        }

        .divider span {
            position: relative;
            background: var(--bg-white);
            padding: 0 1rem;
            color: var(--text-gray);
            font-size: 0.75rem;
            font-weight: 500;
        }

        .footer-link {
            text-align: center;
            margin-top: 1rem;
            padding-top: 1rem;
            border-top: 1px solid var(--border-light);
        }

        .footer-link a {
            color: var(--primary);
            text-decoration: none;
            font-weight: 600;
            font-size: 0.85rem;
            transition: color 0.2s;
        }

        .footer-link a:hover {
            color: var(--primary-dark);
        }

        @media (max-width: 768px) {
            .login-wrapper {
                flex-direction: column;
                min-height: auto;
            }

            .login-sidebar {
                flex: 0 0 auto;
                width: 100%;
                padding: 2rem;
                min-height: 350px;
            }

            .login-form-section {
                flex: 0 0 auto;
                width: 100%;
                padding: 2rem;
            }

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

            .sidebar-title {
                font-size: 1.5rem;
            }

            .form-title {
                font-size: 1.5rem;
            }
        }
    </style>
</head>

<body>
    <div class="login-wrapper">
        <!-- Sidebar Informativa -->
        <div class="login-sidebar">
            <div class="sidebar-content">
                <!-- Logo da Skin -->
                <div class="aurion-logo-container">
                    <img src="<?= htmlspecialchars($skinLogo) ?>" alt="<?= htmlspecialchars($skinDisplayName) ?>"
                        onerror="this.onerror=null; this.src='<?= asset('/storage/uploads/logos/aurion/aurion.png') ?>';">
                </div>
            </div>
        </div>

        <!-- Formulário de Login -->
        <div class="login-form-section">
            <div class="login-form-container">
                <!-- Logo do Cliente -->
                <div class="client-logo-container">
                    <?php
                    // Determinar o caminho da logo
                    $logoPath = '/storage/uploads/logos/aurion/generico.jpg'; // Fallback padrão

                    if (!empty($companyLogo) && trim($companyLogo) !== '') {
                        $logoValue = trim($companyLogo);

                        // Normalizar o caminho: garantir que comece com /storage/
                        if (strpos($logoValue, '/storage/') === 0) {
                            // Já está no formato correto
                            $logoPath = $logoValue;
                        } elseif (strpos($logoValue, 'storage/') === 0) {
                            // Adicionar / no início
                            $logoPath = '/' . $logoValue;
                        } elseif (strpos($logoValue, '/') === false && strpos($logoValue, '\\') === false) {
                            // Apenas o nome do arquivo, construir caminho completo
                            $logoPath = '/storage/uploads/logos/' . $logoValue;
                        } else {
                            // Usar o valor como está
                            $logoPath = $logoValue;
                        }
                    }

                    // Usar asset() para gerar o caminho correto com base path
                    $logoUrl = asset($logoPath);
                    $fallbackUrl = asset('/storage/uploads/logos/tupan.png');
                    ?>
                    <img src="<?php echo htmlspecialchars($logoUrl); ?>" alt="Logo do Cliente"
                        onerror="this.onerror=null; this.src='<?php echo htmlspecialchars($fallbackUrl); ?>';">
                    <p>Bem-vindo ao sistema</p>
                </div>

                <div class="form-header">
                    <h1 class="form-title">Acesso ao Sistema</h1>
                    <p class="form-subtitle">Informe suas credenciais para continuar</p>
                </div>

                <form id="loginForm">
                    <div class="form-group">
                        <label for="email" class="form-label">Email</label>
                        <input type="email" class="form-control" id="email" name="email" placeholder="seu@email.com"
                            required autocomplete="username">
                    </div>

                    <div class="form-group">
                        <label for="password" class="form-label">Senha</label>
                        <input type="password" class="form-control" id="password" name="password" placeholder="••••••••"
                            required autocomplete="current-password">
                    </div>

                    <button type="submit" class="btn-login">
                        <i class="bi bi-shield-lock me-2"></i> Acessar Sistema
                    </button>

                    <div class="company-info">
                        <strong>Desenvolvido por Systhema Tecnologia</strong><br>
                        © 2025 - Todos os direitos reservados
                    </div>
                </form>

                <!-- <div class="divider">
                    <span>Primeira vez?</span>
                </div>

                <div class="footer-link">
                    <a href="register">
                        <i class="bi bi-building me-2"></i>Criar Nova Conta Empresarial
                    </a>
                </div> -->
            </div>
        </div>
    </div>

    <!-- Bootstrap JS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>

    <!-- jQuery -->
    <script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>

    <!-- SweetAlert2 -->
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

    <script>
        $(document).ready(function () {
            $('#loginForm').on('submit', function (e) {
                e.preventDefault();

                const email = $('#email').val();
                const password = $('#password').val();

                // Mostra loading
                Swal.fire({
                    title: 'Processando...',
                    allowOutsideClick: false,
                    didOpen: () => {
                        Swal.showLoading();
                    }
                });

                $.ajax({
                    url: appUrl('login'),
                    type: 'POST',
                    xhrFields: {
                        withCredentials: true
                    },
                    crossDomain: false,
                    data: {
                        email,
                        password
                    },
                    dataType: 'json',
                    beforeSend: function (xhr) {
                        // Garantir que cookies sejam enviados
                        xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
                    },
                    success: function (response) {
                        console.log('Resposta de sucesso recebida:', response);

                        // Fechar o loading do SweetAlert
                        Swal.close();

                        if (response && response.success) {
                            Swal.fire({
                                icon: 'success',
                                title: 'Sucesso!',
                                text: response.message || 'Login realizado com sucesso',
                                showConfirmButton: false,
                                timer: 1500
                            }).then(() => {
                                const redirectUrl = response.data && response.data
                                    .redirect ?
                                    response.data.redirect :
                                    appUrl('dashboard');
                                console.log('Redirecionando para:', redirectUrl);
                                window.location.href = redirectUrl;
                            });
                        } else {
                            Swal.fire({
                                icon: 'error',
                                title: 'Erro',
                                text: response && response.message ? response.message :
                                    'Resposta inválida do servidor'
                            });
                        }
                    },
                    error: function (xhr, status, error) {
                        console.error('Erro no login:', {
                            status: xhr.status,
                            statusText: xhr.statusText,
                            error: error,
                            responseText: xhr.responseText,
                            responseJSON: xhr.responseJSON,
                            readyState: xhr.readyState
                        });

                        // Fechar o loading do SweetAlert
                        Swal.close();

                        // CASO ESPECIAL: se o servidor já retornou HTML (provavelmente já logado / redirecionado)
                        // e o status é 200, considerar como login bem-sucedido e ir direto para o dashboard
                        if (xhr.status === 200 && xhr.responseText && xhr.responseText.trim()
                            .startsWith('<')) {
                            console.warn(
                                'Resposta HTML recebida no login, redirecionando para o dashboard.'
                            );
                            window.location.href = appUrl('dashboard');
                            return;
                        }

                        let errorMessage = 'Ocorreu um erro. Tente novamente.';
                        let errorDetails = '';

                        // Verificar se a resposta é JSON válido (pode ser que o servidor retornou sucesso mas com status de erro)
                        try {
                            let response = xhr.responseJSON;

                            // Se não conseguiu parsear automaticamente, tentar manualmente
                            if (!response && xhr.responseText) {
                                try {
                                    response = JSON.parse(xhr.responseText);
                                } catch (e) {
                                    console.warn('Não foi possível parsear resposta como JSON:',
                                        e);
                                }
                            }

                            // Se a resposta indica sucesso mas veio como erro (status 200 mas parseado como erro)
                            if (response && response.success) {
                                console.log('Resposta de sucesso recebida no handler de erro:',
                                    response);
                                Swal.fire({
                                    icon: 'success',
                                    title: 'Sucesso!',
                                    text: response.message ||
                                        'Login realizado com sucesso',
                                    showConfirmButton: false,
                                    timer: 1500
                                }).then(() => {
                                    const redirectUrl = response.data && response.data
                                        .redirect ?
                                        response.data.redirect :
                                        appUrl('dashboard');
                                    window.location.href = redirectUrl;
                                });
                                return;
                            }

                            if (response) {
                                if (response.message) {
                                    errorMessage = response.message;
                                }
                                if (response.errors) {
                                    errorDetails = Object.values(response.errors).flat().join(
                                        '\n');
                                }
                            } else if (xhr.responseText) {
                                // Tentar extrair mensagem de erro de HTML ou texto
                                const text = xhr.responseText.trim();
                                if (text.length > 0 && text.length < 500 && !text.startsWith(
                                    '<')) {
                                    errorMessage = text;
                                }
                            }
                        } catch (e) {
                            console.error('Erro ao processar resposta de erro:', e);
                        }

                        const finalMessage = errorDetails ? errorMessage + '\n\n' +
                            errorDetails : errorMessage;

                        Swal.fire({
                            icon: 'error',
                            title: 'Erro ao fazer login',
                            text: finalMessage,
                            width: '500px'
                        });
                    }
                });
            });
        });
    </script>
</body>

</html>