<?php
// ===================================
// ARCHIVO: login.php
// Sistema de login para usuarios regulares
// ===================================

$page_title = "Iniciar Sesión";
$page_description = "Acceda a su cuenta de mayorista";
$breadcrumbs = [
    ['label' => 'Iniciar Sesión']
];
$additional_css = ['assets/css/forms.css'];

require_once 'config/session.php';
debugSession('Login');

require_once 'config/database.php';
require_once 'includes/functions.php';

// Si ya está logueado, redirigir según su rol
if (isLoggedIn()) {
    if (isAdmin()) {
        header('Location: admin/dashboard.php');
    } elseif (isApproved()) {
        header('Location: catalog.php');
    } else {
        header('Location: pending-approval.php');
    }
    exit;
}

$errors = [];
$email = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $email = sanitizeInput($_POST['email'], 'email');
    $password = $_POST['password'];
    $remember_me = isset($_POST['remember_me']);
    
    if (empty($email) || empty($password)) {
        $errors[] = "Email y contraseña son requeridos";
    } else {
        try {
            $stmt = $pdo->prepare("
                SELECT id, email, password_hash, business_name, business_type, 
                       contact_name, role, is_approved, created_at
                FROM users 
                WHERE email = ?
            ");
            $stmt->execute([$email]);
            $user = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if ($user && password_verify($password, $user['password_hash'])) {
                // Login exitoso
                loginUser($user);
                
                // Configurar "recordarme" si está seleccionado
                if ($remember_me) {
                    setRememberMeToken($user['id']);
                }
                
                // Redirigir según el estado del usuario
                if ($user['role'] === 'admin') {
                    header('Location: admin/dashboard.php');
                } elseif ($user['is_approved']) {
                    // Usuario aprobado - ir al catálogo
                    $redirect = $_GET['redirect'] ?? 'catalog.php';
                    header('Location: ' . $redirect);
                } else {
                    // Usuario pendiente de aprobación
                    header('Location: pending-approval.php');
                }
                exit;
                
            } else {
                $errors[] = "Email o contraseña incorrectos";
                
                // Log intento fallido
                if ($user) {
                    logFailedLogin($email, 'invalid_password');
                } else {
                    logFailedLogin($email, 'user_not_found');
                }
            }
            
        } catch (PDOException $e) {
            error_log("Login error: " . $e->getMessage());
            $errors[] = "Error del sistema. Intente nuevamente.";
        }
    }
}

// Función para configurar token "recordarme"
function setRememberMeToken($user_id) {
    $token = generateSecureToken(32);
    $expires = date('Y-m-d H:i:s', strtotime('+30 days'));
    
    try {
        global $pdo;
        $stmt = $pdo->prepare("
            INSERT INTO remember_tokens (user_id, token, expires_at) 
            VALUES (?, ?, ?)
            ON DUPLICATE KEY UPDATE token = ?, expires_at = ?
        ");
        $stmt->execute([$user_id, $token, $expires, $token, $expires]);
        
        // Configurar cookie
        setcookie('remember_token', $token, strtotime('+30 days'), '/', '', true, true);
        
    } catch (PDOException $e) {
        error_log("Remember token error: " . $e->getMessage());
    }
}

// Función para registrar intentos fallidos
function logFailedLogin($email, $reason) {
    try {
        global $pdo;
        $stmt = $pdo->prepare("
            INSERT INTO login_attempts (email, ip_address, reason, attempted_at) 
            VALUES (?, ?, ?, NOW())
        ");
        $stmt->execute([$email, $_SERVER['REMOTE_ADDR'], $reason]);
    } catch (PDOException $e) {
        error_log("Failed login log error: " . $e->getMessage());
    }
}

// Verificar si hay mensaje flash
$flash = getFlashMessage();

require_once 'includes/header.php';
?>

<main class="main-content">
    <div class="container">
        <div class="login-container">
            <div class="login-header">
                <h1>🔐 Iniciar Sesión</h1>
                <p>Acceda a su cuenta de mayorista</p>
            </div>

            <div class="login-form">
                <?php if ($flash): ?>
                    <div class="alert alert-<?php echo $flash['type']; ?>">
                        <p><?php echo htmlspecialchars($flash['message']); ?></p>
                    </div>
                <?php endif; ?>

                <?php if (!empty($errors)): ?>
                    <div class="alert alert-error">
                        <?php foreach ($errors as $error): ?>
                            <p><?php echo htmlspecialchars($error); ?></p>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>

                <!-- Información de demo/testing -->
                <div class="demo-info">
                    <h4>🧪 Para testing</h4>
                    <p><strong>Admin:</strong> admin@lunamayorista.com.ar / password<br>
                    <strong>Usuario:</strong> Registrarse y solicitar aprobación</p>
                </div>

                <form method="POST" action="login.php" id="loginForm">
                    <div class="form-group">
                        <label for="email">Email</label>
                        <input type="email" id="email" name="email" required 
                               value="<?php echo htmlspecialchars($email); ?>"
                               placeholder="su@email.com"
                               autocomplete="email">
                    </div>
                    
                    <div class="form-group">
                        <label for="password">Contraseña</label>
                        <input type="password" id="password" name="password" required
                               placeholder="••••••••"
                               autocomplete="current-password">
                    </div>
                    
                    <div class="remember-me">
                        <input type="checkbox" id="remember_me" name="remember_me">
                        <label for="remember_me">Recordarme por 30 días</label>
                    </div>
                    
                    <button type="submit" class="btn btn-primary login-btn" id="loginBtn">
                        Iniciar Sesión
                    </button>
                    
                    <div class="forgot-password">
                        <a href="forgot-password.php">¿Olvidó su contraseña?</a>
                    </div>
                </form>

                <div class="divider">
                    <span>¿No tiene cuenta?</span>
                </div>

                <div class="register-link">
                    <a href="register.php" class="btn btn-secondary btn-full">
                        Registrar nuevo comercio
                    </a>
                </div>
            </div>

            <div class="login-footer">
                <p>¿Necesita ayuda? <a href="mailto:soporte@lunamayorista.com.ar">Contacte soporte</a></p>
                <p><a href="index.php">← Volver al inicio</a></p>
            </div>
        </div>
    </div>
</main>

<style>
.login-container {
    max-width: 500px;
    margin: 4rem auto;
    background: white;
    border-radius: 12px;
    box-shadow: 0 10px 30px rgba(0,0,0,0.1);
    overflow: hidden;
}

.login-header {
    background: linear-gradient(135deg, #2c3e50, #3498db);
    color: white;
    padding: 2rem;
    text-align: center;
}

.login-header h1 {
    margin: 0 0 0.5rem 0;
    font-size: 1.8rem;
}

.login-header p {
    margin: 0;
    opacity: 0.9;
}

.login-form {
    padding: 2rem;
}

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

.form-group label {
    display: block;
    margin-bottom: 0.5rem;
    font-weight: 500;
    color: #2c3e50;
}

.form-group input {
    width: 100%;
    padding: 0.75rem;
    border: 2px solid #ecf0f1;
    border-radius: 6px;
    font-size: 1rem;
    transition: border-color 0.3s ease;
    box-sizing: border-box;
}

.form-group input:focus {
    outline: none;
    border-color: #3498db;
    box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.1);
}

.remember-me {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    margin-bottom: 1.5rem;
}

.remember-me input[type="checkbox"] {
    width: auto;
}

.login-btn {
    width: 100%;
    background: linear-gradient(135deg, #3498db, #2980b9);
    color: white;
    border: none;
    padding: 1rem;
    border-radius: 6px;
    font-size: 1rem;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.3s ease;
}

.login-btn:hover {
    transform: translateY(-2px);
    box-shadow: 0 5px 15px rgba(52, 152, 219, 0.3);
}

.login-btn:disabled {
    opacity: 0.6;
    cursor: not-allowed;
    transform: none;
}

.forgot-password {
    text-align: center;
    margin-top: 1rem;
}

.forgot-password a {
    color: #7f8c8d;
    text-decoration: none;
    font-size: 0.9rem;
}

.divider {
    position: relative;
    margin: 1.5rem 0;
    text-align: center;
    color: #7f8c8d;
}

.divider::before {
    content: '';
    position: absolute;
    top: 50%;
    left: 0;
    right: 0;
    height: 1px;
    background: #ecf0f1;
}

.divider span {
    background: white;
    padding: 0 1rem;
}

.register-link {
    text-align: center;
}

.btn-full {
    display: block;
    width: 100%;
    text-decoration: none;
    text-align: center;
}

.demo-info {
    background: #e8f5e8;
    border-left: 4px solid #27ae60;
    padding: 1rem;
    margin-bottom: 1.5rem;
    border-radius: 0 4px 4px 0;
}

.demo-info h4 {
    margin: 0 0 0.5rem 0;
    color: #27ae60;
}

.demo-info p {
    margin: 0;
    font-size: 0.9rem;
    color: #2c3e50;
}

.login-footer {
    padding: 1.5rem 2rem;
    background: #f8f9fa;
    text-align: center;
    border-top: 1px solid #ecf0f1;
}

.login-footer a {
    color: #3498db;
    text-decoration: none;
    font-weight: 500;
}

.login-footer a:hover {
    text-decoration: underline;
}

/* Responsive */
@media (max-width: 768px) {
    .login-container {
        margin: 2rem 1rem;
    }
    
    .login-header {
        padding: 1.5rem;
    }
    
    .login-form {
        padding: 1.5rem;
    }
}
</style>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const form = document.getElementById('loginForm');
    const submitBtn = document.getElementById('loginBtn');
    const emailInput = document.getElementById('email');
    const passwordInput = document.getElementById('password');
    
    // Auto-focus en email
    emailInput.focus();
    
    // Validación en tiempo real
    emailInput.addEventListener('blur', function() {
        validateEmail(this);
    });
    
    passwordInput.addEventListener('input', function() {
        if (this.value.length > 0) {
            this.style.borderColor = '#27ae60';
        } else {
            this.style.borderColor = '#ecf0f1';
        }
    });
    
    // Manejar envío del formulario
    form.addEventListener('submit', function(e) {
        if (!validateForm()) {
            e.preventDefault();
            return false;
        }
        
        // Mostrar estado de carga
        submitBtn.disabled = true;
        submitBtn.textContent = 'Iniciando sesión...';
        submitBtn.style.background = '#95a5a6';
        
        // Reactivar si hay error (no recarga la página)
        setTimeout(() => {
            submitBtn.disabled = false;
            submitBtn.textContent = 'Iniciar Sesión';
            submitBtn.style.background = '';
        }, 5000);
    });
    
    // Función de validación de email
    function validateEmail(input) {
        const email = input.value.trim();
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        
        if (email && !emailRegex.test(email)) {
            input.style.borderColor = '#e74c3c';
            showInputError(input, 'Email inválido');
            return false;
        } else if (email) {
            input.style.borderColor = '#27ae60';
            clearInputError(input);
            return true;
        }
        
        input.style.borderColor = '#ecf0f1';
        clearInputError(input);
        return true;
    }
    
    // Validación completa del formulario
    function validateForm() {
        const email = emailInput.value.trim();
        const password = passwordInput.value;
        
        let isValid = true;
        
        if (!email) {
            showInputError(emailInput, 'Email requerido');
            isValid = false;
        }
        
        if (!password) {
            showInputError(passwordInput, 'Contraseña requerida');
            isValid = false;
        }
        
        if (!validateEmail(emailInput)) {
            isValid = false;
        }
        
        return isValid;
    }
    
    // Funciones auxiliares para mostrar errores
    function showInputError(input, message) {
        clearInputError(input);
        
        const errorDiv = document.createElement('div');
        errorDiv.className = 'input-error';
        errorDiv.textContent = message;
        errorDiv.style.color = '#e74c3c';
        errorDiv.style.fontSize = '0.8rem';
        errorDiv.style.marginTop = '0.25rem';
        
        input.parentNode.appendChild(errorDiv);
        input.style.borderColor = '#e74c3c';
    }
    
    function clearInputError(input) {
        const existingError = input.parentNode.querySelector('.input-error');
        if (existingError) {
            existingError.remove();
        }
    }
    
    // Detectar Enter para enviar formulario
    document.addEventListener('keypress', function(e) {
        if (e.key === 'Enter' && (emailInput === document.activeElement || passwordInput === document.activeElement)) {
            form.requestSubmit();
        }
    });
    
    // Limpiar mensajes de error al escribir
    emailInput.addEventListener('input', () => clearInputError(emailInput));
    passwordInput.addEventListener('input', () => clearInputError(passwordInput));
});
</script>

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