from flask import Flask, request, jsonify, render_template_string, session, redirect, url_for
from flask_sqlalchemy import SQLAlchemy
from flask_cors import CORS
from datetime import datetime, timedelta
from functools import wraps
import os
import requests
import pytz
import jwt
from email_functions import generar_html_email, enviar_email_smtp

# Timezone de España
TIMEZONE_MADRID = pytz.timezone('Europe/Madrid')

app = Flask(__name__)
app.secret_key = 'lotify-secret-key-2025-backup-system'
app.config['JWT_SECRET_KEY'] = 'lotify-jwt-secret-key-2025-api-token'
app.config['JWT_EXPIRATION_HOURS'] = 24  # Token válido por 24 horas
CORS(app)

# Configuración de la base de datos
basedir = os.path.abspath(os.path.dirname(__file__))
# Usar directorio data para persistencia en Docker
data_dir = os.path.join(basedir, 'data')
os.makedirs(data_dir, exist_ok=True)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(data_dir, 'backup_peticiones.db')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

db = SQLAlchemy(app)

# Modelo de la base de datos
class PeticionBackup(db.Model):
    __tablename__ = 'peticiones_backup'
    
    id = db.Column(db.Integer, primary_key=True)
    datetime_registro = db.Column(db.DateTime, nullable=False, default=lambda: datetime.now(TIMEZONE_MADRID))
    
    # Campos de la petición
    empresa = db.Column(db.Text, nullable=True)
    empleado = db.Column(db.Text, nullable=True)
    telefono = db.Column(db.Text, nullable=True)
    email = db.Column(db.Text, nullable=True)
    codigo_lote = db.Column(db.Text, nullable=True)
    tipo_lote = db.Column(db.Text, nullable=True)
    entrega = db.Column(db.Text, nullable=True)
    direccion = db.Column(db.Text, nullable=True)
    franja_horaria_desde = db.Column(db.Text, nullable=True)
    franja_horaria_hasta = db.Column(db.Text, nullable=True)
    desglose_direccion = db.Column(db.Text, nullable=True)
    desglose_detalle_direccion = db.Column(db.Text, nullable=True)
    desglose_cp = db.Column(db.Text, nullable=True)
    desglose_poblacion = db.Column(db.Text, nullable=True)
    desglose_provincia = db.Column(db.Text, nullable=True)
    identificador_cliente = db.Column(db.Text, nullable=True)
    observaciones = db.Column(db.Text, nullable=True)
    sociedad = db.Column(db.Text, nullable=True)
    delegacion = db.Column(db.Text, nullable=True)
    
    def to_dict(self):
        return {
            'id': self.id,
            'datetime_registro': self.datetime_registro.isoformat(),
            'empresa': self.empresa,
            'empleado': self.empleado,
            'telefono': self.telefono,
            'email': self.email,
            'codigo_lote': self.codigo_lote,
            'tipo_lote': self.tipo_lote,
            'entrega': self.entrega,
            'direccion': self.direccion,
            'franja_horaria_desde': self.franja_horaria_desde,
            'franja_horaria_hasta': self.franja_horaria_hasta,
            'desglose_direccion': self.desglose_direccion,
            'desglose_detalle_direccion': self.desglose_detalle_direccion,
            'desglose_cp': self.desglose_cp,
            'desglose_poblacion': self.desglose_poblacion,
            'desglose_provincia': self.desglose_provincia,
            'identificador_cliente': self.identificador_cliente,
            'observaciones': self.observaciones,
            'sociedad': self.sociedad,
            'delegacion': self.delegacion
        }

# Modelo para historial de envíos de email
class EmailEnvio(db.Model):
    __tablename__ = 'email_envios'
    
    id = db.Column(db.Integer, primary_key=True)
    peticion_id = db.Column(db.Integer, db.ForeignKey('peticiones_backup.id'), nullable=False)
    email_destino = db.Column(db.Text, nullable=False)
    fecha_envio = db.Column(db.DateTime, nullable=False, default=lambda: datetime.now(TIMEZONE_MADRID))
    estado = db.Column(db.Text, nullable=False)  # 'exitoso' o 'error'
    mensaje_error = db.Column(db.Text, nullable=True)
    
    peticion = db.relationship('PeticionBackup', backref='envios_email')

# Crear las tablas
with app.app_context():
    db.create_all()

# Credenciales para API (en producción usar variables de entorno o base de datos)
API_CREDENTIALS = {
    'lotify': 'Lot1fyrequest3r$'
}

def generar_token(username):
    """
    Genera un JWT token para el usuario
    """
    payload = {
        'username': username,
        'exp': datetime.utcnow() + timedelta(hours=app.config['JWT_EXPIRATION_HOURS']),
        'iat': datetime.utcnow()
    }
    token = jwt.encode(payload, app.config['JWT_SECRET_KEY'], algorithm='HS256')
    return token

def verificar_token(token):
    """
    Verifica y decodifica un JWT token
    """
    try:
        payload = jwt.decode(token, app.config['JWT_SECRET_KEY'], algorithms=['HS256'])
        return payload
    except jwt.ExpiredSignatureError:
        return None  # Token expirado
    except jwt.InvalidTokenError:
        return None  # Token inválido

def token_required(f):
    """
    Decorador para proteger endpoints con JWT
    """
    @wraps(f)
    def decorated(*args, **kwargs):
        token = None
        
        # Obtener token del header Authorization
        if 'Authorization' in request.headers:
            auth_header = request.headers['Authorization']
            try:
                # Formato esperado: "Bearer <token>"
                token = auth_header.split(' ')[1]
            except IndexError:
                return jsonify({
                    'success': False,
                    'error': 'Formato de token inválido. Use: Bearer <token>'
                }), 401
        
        if not token:
            return jsonify({
                'success': False,
                'error': 'Token no proporcionado. Incluya el header: Authorization: Bearer <token>'
            }), 401
        
        # Verificar token
        payload = verificar_token(token)
        if payload is None:
            return jsonify({
                'success': False,
                'error': 'Token inválido o expirado'
            }), 401
        
        # Pasar información del usuario a la función
        return f(current_user=payload['username'], *args, **kwargs)
    
    return decorated

@app.route('/', methods=['GET'])
def index():
    """
    Ruta raíz
    """
    return "Silence is gold", 200

@app.route('/api/auth/login', methods=['POST'])
def api_login():
    """
    Endpoint para obtener un token JWT.
    
    Body (JSON):
    {
        "username": "lotify",
        "password": "Lot1fyrequest3r$"
    }
    
    Respuesta exitosa:
    {
        "success": true,
        "token": "eyJ0eXAiOiJKV1QiLCJhbGc...",
        "expires_in": 86400,
        "token_type": "Bearer"
    }
    """
    try:
        data = request.get_json()
        
        if not data:
            return jsonify({
                'success': False,
                'error': 'Se requiere JSON con username y password'
            }), 400
        
        username = data.get('username')
        password = data.get('password')
        
        if not username or not password:
            return jsonify({
                'success': False,
                'error': 'Se requieren username y password'
            }), 400
        
        # Verificar credenciales
        if username not in API_CREDENTIALS or API_CREDENTIALS[username] != password:
            return jsonify({
                'success': False,
                'error': 'Credenciales inválidas'
            }), 401
        
        # Generar token
        token = generar_token(username)
        
        return jsonify({
            'success': True,
            'token': token,
            'expires_in': app.config['JWT_EXPIRATION_HOURS'] * 3600,  # En segundos
            'token_type': 'Bearer'
        }), 200
    
    except Exception as e:
        return jsonify({
            'success': False,
            'error': f'Error al generar token: {str(e)}'
        }), 500

@app.route('/backup', methods=['POST'])
def guardar_backup():
    """
    Endpoint para guardar peticiones de backup.
    Acepta cualquier tipo de dato, nulos, vacíos, etc.
    """
    try:
        data = request.get_json(force=True, silent=True) or {}
        
        # Crear nueva entrada en la base de datos
        nueva_peticion = PeticionBackup(
            empresa=data.get('empresa'),
            empleado=data.get('empleado'),
            telefono=data.get('telefono'),
            email=data.get('email'),
            codigo_lote=data.get('codigo_lote'),
            tipo_lote=data.get('tipo_lote'),
            entrega=data.get('entrega'),
            direccion=data.get('direccion'),
            franja_horaria_desde=data.get('franja_horaria_desde'),
            franja_horaria_hasta=data.get('franja_horaria_hasta'),
            desglose_direccion=data.get('desglose_direccion'),
            desglose_detalle_direccion=data.get('desglose_detalle_direccion'),
            desglose_cp=data.get('desglose_cp'),
            desglose_poblacion=data.get('desglose_poblacion'),
            desglose_provincia=data.get('desglose_provincia'),
            identificador_cliente=data.get('identificador_cliente'),
            observaciones=data.get('observaciones'),
            sociedad=data.get('sociedad'),
            delegacion=data.get('delegacion')
        )
        
        db.session.add(nueva_peticion)
        db.session.commit()
        
        return jsonify({
            'success': True,
            'message': 'Backup guardado correctamente',
            'id': nueva_peticion.id,
            'datetime': nueva_peticion.datetime_registro.isoformat()
        }), 201
        
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'success': False,
            'message': 'Error al guardar backup',
            'error': str(e)
        }), 500

@app.route('/backup/<int:id>', methods=['GET'])
def obtener_backup(id):
    """
    Endpoint opcional para consultar un backup por ID
    """
    peticion = PeticionBackup.query.get_or_404(id)
    return jsonify(peticion.to_dict()), 200

@app.route('/backup/list', methods=['GET'])
def listar_backups():
    """
    Endpoint opcional para listar todos los backups
    Soporta paginación con parámetros: page (default 1) y per_page (default 50)
    """
    page = request.args.get('page', 1, type=int)
    per_page = request.args.get('per_page', 50, type=int)
    
    peticiones = PeticionBackup.query.order_by(PeticionBackup.datetime_registro.desc()).paginate(
        page=page, per_page=per_page, error_out=False
    )
    
    return jsonify({
        'total': peticiones.total,
        'page': peticiones.page,
        'per_page': peticiones.per_page,
        'pages': peticiones.pages,
        'data': [p.to_dict() for p in peticiones.items]
    }), 200

@app.route('/api/registros', methods=['GET'])
@token_required
def consultar_registros(current_user):
    """
    Endpoint para consultar registros con filtros opcionales.
    Requiere autenticación con Bearer Token.
    
    Headers requeridos:
    - Authorization: Bearer <token>
    
    Parámetros de query:
    - empresa: Filtrar por nombre de empresa (búsqueda parcial, case-insensitive)
    - fecha_desde: Filtrar desde fecha (formato: YYYY-MM-DD o YYYY-MM-DD HH:MM:SS)
    - fecha_hasta: Filtrar hasta fecha (formato: YYYY-MM-DD o YYYY-MM-DD HH:MM:SS)
    - page: Número de página (default: 1)
    - per_page: Registros por página (default: 100, max: 1000)
    - order: Orden de resultados 'asc' o 'desc' (default: 'desc')
    
    Ejemplos:
    - /api/registros
    - /api/registros?empresa=Acme
    - /api/registros?fecha_desde=2025-01-01&fecha_hasta=2025-01-31
    - /api/registros?empresa=Acme&fecha_desde=2025-01-01&per_page=50
    """
    try:
        # Parámetros de paginación
        page = request.args.get('page', 1, type=int)
        per_page = min(request.args.get('per_page', 100, type=int), 1000)  # Max 1000
        order = request.args.get('order', 'desc').lower()
        
        # Construir query base
        query = PeticionBackup.query
        
        # Filtro por empresa
        empresa = request.args.get('empresa', '').strip()
        if empresa:
            query = query.filter(PeticionBackup.empresa.ilike(f'%{empresa}%'))
        
        # Filtro por fecha desde
        fecha_desde = request.args.get('fecha_desde', '').strip()
        if fecha_desde:
            try:
                # Intentar parsear con hora
                if ' ' in fecha_desde:
                    fecha_desde_dt = datetime.strptime(fecha_desde, '%Y-%m-%d %H:%M:%S')
                else:
                    fecha_desde_dt = datetime.strptime(fecha_desde, '%Y-%m-%d')
                
                # Localizar en timezone Madrid
                fecha_desde_dt = TIMEZONE_MADRID.localize(fecha_desde_dt)
                query = query.filter(PeticionBackup.datetime_registro >= fecha_desde_dt)
            except ValueError:
                return jsonify({
                    'error': 'Formato de fecha_desde inválido. Use YYYY-MM-DD o YYYY-MM-DD HH:MM:SS'
                }), 400
        
        # Filtro por fecha hasta
        fecha_hasta = request.args.get('fecha_hasta', '').strip()
        if fecha_hasta:
            try:
                # Intentar parsear con hora
                if ' ' in fecha_hasta:
                    fecha_hasta_dt = datetime.strptime(fecha_hasta, '%Y-%m-%d %H:%M:%S')
                else:
                    # Si solo es fecha, incluir todo el día
                    fecha_hasta_dt = datetime.strptime(fecha_hasta, '%Y-%m-%d')
                    fecha_hasta_dt = fecha_hasta_dt.replace(hour=23, minute=59, second=59)
                
                # Localizar en timezone Madrid
                fecha_hasta_dt = TIMEZONE_MADRID.localize(fecha_hasta_dt)
                query = query.filter(PeticionBackup.datetime_registro <= fecha_hasta_dt)
            except ValueError:
                return jsonify({
                    'error': 'Formato de fecha_hasta inválido. Use YYYY-MM-DD o YYYY-MM-DD HH:MM:SS'
                }), 400
        
        # Aplicar ordenamiento
        if order == 'asc':
            query = query.order_by(PeticionBackup.datetime_registro.asc())
        else:
            query = query.order_by(PeticionBackup.datetime_registro.desc())
        
        # Ejecutar query con paginación
        peticiones = query.paginate(page=page, per_page=per_page, error_out=False)
        
        # Preparar respuesta
        response = {
            'success': True,
            'total': peticiones.total,
            'page': peticiones.page,
            'per_page': peticiones.per_page,
            'pages': peticiones.pages,
            'has_next': peticiones.has_next,
            'has_prev': peticiones.has_prev,
            'filtros_aplicados': {
                'empresa': empresa if empresa else None,
                'fecha_desde': fecha_desde if fecha_desde else None,
                'fecha_hasta': fecha_hasta if fecha_hasta else None,
                'order': order
            },
            'data': [p.to_dict() for p in peticiones.items]
        }
        
        return jsonify(response), 200
    
    except Exception as e:
        return jsonify({
            'success': False,
            'error': f'Error al consultar registros: {str(e)}'
        }), 500

@app.route('/health', methods=['GET'])
def health_check():
    """
    Endpoint para verificar que el servicio está funcionando
    """
    return jsonify({
        'status': 'ok',
        'message': 'Sistema de backup funcionando correctamente'
    }), 200

# Credenciales de acceso
USUARIO_ADMIN = 'lotify'
CONTRASENA_ADMIN = 'Lot1fyrequest3r$'

def login_required(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        if not session.get('logged_in'):
            return redirect(url_for('login'))
        return f(*args, **kwargs)
    return decorated_function

@app.route('/admin/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form.get('username')
        password = request.form.get('password')
        
        if username == USUARIO_ADMIN and password == CONTRASENA_ADMIN:
            session['logged_in'] = True
            return redirect(url_for('admin_view'))
        else:
            return render_template_string(LOGIN_TEMPLATE, error=True)
    
    return render_template_string(LOGIN_TEMPLATE, error=False)

@app.route('/admin/logout')
def logout():
    session.pop('logged_in', None)
    return redirect(url_for('login'))

@app.route('/admin')
@login_required
def admin_view():
    page = request.args.get('page', 1, type=int)
    per_page = 50
    
    # Obtener parámetros de ordenamiento y filtrado
    sort_by = request.args.get('sort', 'datetime_registro')
    sort_order = request.args.get('order', 'desc')
    
    # Filtros
    filters = {}
    for field in ['empresa', 'empleado', 'telefono', 'email', 'codigo_lote', 'tipo_lote', 
                  'entrega', 'direccion', 'desglose_poblacion', 'desglose_provincia', 
                  'identificador_cliente', 'sociedad', 'delegacion']:
        value = request.args.get(f'filter_{field}', '').strip()
        if value:
            filters[field] = value
    
    # Construir query
    query = PeticionBackup.query
    
    # Aplicar filtros
    for field, value in filters.items():
        column = getattr(PeticionBackup, field)
        query = query.filter(column.ilike(f'%{value}%'))
    
    # Aplicar ordenamiento
    if hasattr(PeticionBackup, sort_by):
        column = getattr(PeticionBackup, sort_by)
        if sort_order == 'asc':
            query = query.order_by(column.asc())
        else:
            query = query.order_by(column.desc())
    else:
        query = query.order_by(PeticionBackup.datetime_registro.desc())
    
    peticiones = query.paginate(page=page, per_page=per_page, error_out=False)
    
    return render_template_string(ADMIN_TEMPLATE, 
                                 peticiones=peticiones, 
                                 sort_by=sort_by, 
                                 sort_order=sort_order,
                                 filters=filters)

def api_datos_empresa_completo(empresa, identificador=None, access_key=None):
    """
    Obtiene datos completos de la empresa desde la API de Lotify
    """
    url = f'https://sigan.lotify.es/lotify_api/plataforma/data/{empresa}'
    
    params = {
        'oirausu': 'requester',
        'access_key': 'pass'
    }
    
    try:
        response = requests.get(url, params=params, timeout=10)
        response.raise_for_status()
        data = response.json()
        
        if 'plataforma' in data:
            return data
        return None
    except Exception as e:
        print(f"Error al obtener datos de la API: {e}")
        return None

@app.route('/admin/email/<int:id>')
@login_required
def ver_email(id):
    peticion = PeticionBackup.query.get_or_404(id)
    historial = EmailEnvio.query.filter_by(peticion_id=id).order_by(EmailEnvio.fecha_envio.desc()).all()
    
    html_email = generar_html_email(peticion, api_datos_empresa_completo)
    
    return render_template_string(EMAIL_VIEWER_TEMPLATE, 
                                 peticion=peticion, 
                                 html_email=html_email,
                                 historial=historial)

@app.route('/admin/email/<int:id>/enviar', methods=['POST'])
@login_required
def enviar_email(id):
    peticion = PeticionBackup.query.get_or_404(id)
    data = request.get_json()
    email_destino = data.get('email', peticion.email)
    
    if not email_destino:
        return jsonify({'success': False, 'message': 'Email de destino requerido'}), 400
    
    # Generar HTML del email
    html_content = generar_html_email(peticion, api_datos_empresa_completo)
    
    # Enviar email
    exito, error = enviar_email_smtp(email_destino, 'Reserva Lotify recibida', html_content)
    
    # Registrar en historial
    envio = EmailEnvio(
        peticion_id=id,
        email_destino=email_destino,
        estado='exitoso' if exito else 'error',
        mensaje_error=error
    )
    db.session.add(envio)
    db.session.commit()
    
    if exito:
        return jsonify({
            'success': True, 
            'message': f'Email enviado correctamente a {email_destino}',
            'envio': {
                'id': envio.id,
                'email': envio.email_destino,
                'fecha': envio.fecha_envio.strftime('%Y-%m-%d %H:%M:%S'),
                'estado': envio.estado
            }
        }), 200
    else:
        return jsonify({'success': False, 'message': f'Error al enviar email: {error}'}), 500

EMAIL_VIEWER_TEMPLATE = '''
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Ver Email - Lotify Backup</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: #f5f5f5;
            display: flex;
            height: 100vh;
            overflow: hidden;
        }
        .email-content {
            flex: 1;
            overflow-y: auto;
            background: white;
        }
        .sidebar {
            width: 300px;
            background: white;
            border-left: 1px solid #ddd;
            display: flex;
            flex-direction: column;
            overflow-y: auto;
        }
        .sidebar-header {
            padding: 20px;
            border-bottom: 1px solid #ddd;
            background: #667eea;
            color: white;
        }
        .sidebar-header h2 {
            font-size: 18px;
            margin-bottom: 10px;
        }
        .btn-enviar {
            width: 100%;
            padding: 12px;
            background: #28a745;
            color: white;
            border: none;
            border-radius: 6px;
            font-size: 14px;
            font-weight: 600;
            cursor: pointer;
            transition: background 0.3s;
        }
        .btn-enviar:hover {
            background: #218838;
        }
        .historial {
            padding: 20px;
            flex: 1;
        }
        .historial h3 {
            font-size: 16px;
            margin-bottom: 15px;
            color: #333;
        }
        .historial-item {
            padding: 12px;
            background: #f8f9fa;
            border-radius: 6px;
            margin-bottom: 10px;
            border-left: 4px solid #28a745;
        }
        .historial-item.error {
            border-left-color: #dc3545;
        }
        .historial-item .email {
            font-weight: 600;
            color: #333;
            margin-bottom: 4px;
        }
        .historial-item .fecha {
            font-size: 12px;
            color: #666;
        }
        .historial-item .estado {
            font-size: 12px;
            margin-top: 4px;
        }
        .historial-item .estado.exitoso {
            color: #28a745;
        }
        .historial-item .estado.error {
            color: #dc3545;
        }
        .historial-empty {
            text-align: center;
            color: #999;
            padding: 20px;
        }
        
        /* Modal */
        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0,0,0,0.5);
            align-items: center;
            justify-content: center;
        }
        .modal.show {
            display: flex;
        }
        .modal-content {
            background: white;
            padding: 30px;
            border-radius: 10px;
            width: 90%;
            max-width: 500px;
            box-shadow: 0 10px 40px rgba(0,0,0,0.3);
        }
        .modal-header {
            margin-bottom: 20px;
        }
        .modal-header h2 {
            font-size: 20px;
            color: #333;
        }
        .form-group {
            margin-bottom: 20px;
        }
        .form-group label {
            display: block;
            margin-bottom: 8px;
            color: #555;
            font-weight: 500;
        }
        .form-group input {
            width: 100%;
            padding: 12px;
            border: 2px solid #e0e0e0;
            border-radius: 6px;
            font-size: 14px;
        }
        .form-group input:focus {
            outline: none;
            border-color: #667eea;
        }
        .modal-buttons {
            display: flex;
            gap: 10px;
            justify-content: flex-end;
        }
        .btn-modal {
            padding: 10px 20px;
            border: none;
            border-radius: 6px;
            font-size: 14px;
            font-weight: 600;
            cursor: pointer;
            transition: background 0.3s;
        }
        .btn-modal.cancelar {
            background: #6c757d;
            color: white;
        }
        .btn-modal.cancelar:hover {
            background: #5a6268;
        }
        .btn-modal.confirmar {
            background: #28a745;
            color: white;
        }
        .btn-modal.confirmar:hover {
            background: #218838;
        }
        .alert {
            padding: 12px;
            border-radius: 6px;
            margin-bottom: 15px;
            display: none;
        }
        .alert.show {
            display: block;
        }
        .alert.success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        .alert.error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
    </style>
</head>
<body>
    <div class="email-content">
        {{ html_email|safe }}
    </div>
    
    <div class="sidebar">
        <div class="sidebar-header">
            <h2>📧 Gestión de Email</h2>
            <button class="btn-enviar" onclick="abrirModal()">Reenviar Email</button>
        </div>
        
        <div class="historial">
            <h3>Historial de Envíos</h3>
            <div id="historial-container">
                {% if historial %}
                    {% for envio in historial %}
                    <div class="historial-item {{ envio.estado }}">
                        <div class="email">{{ envio.email_destino }}</div>
                        <div class="fecha">{{ envio.fecha_envio.strftime('%Y-%m-%d %H:%M:%S') }}</div>
                        <div class="estado {{ envio.estado }}">
                            {% if envio.estado == 'exitoso' %}
                                ✓ Enviado correctamente
                            {% else %}
                                ✗ Error: {{ envio.mensaje_error }}
                            {% endif %}
                        </div>
                    </div>
                    {% endfor %}
                {% else %}
                    <div class="historial-empty">No hay envíos registrados</div>
                {% endif %}
            </div>
        </div>
    </div>
    
    <!-- Modal -->
    <div id="modal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2>¿Dónde quieres reenviarlo?</h2>
            </div>
            <div id="alert" class="alert"></div>
            <form id="formEnviar" onsubmit="enviarEmail(event)">
                <div class="form-group">
                    <label>Email de destino</label>
                    <input type="email" id="emailDestino" value="{{ peticion.email or '' }}" required>
                </div>
                <div class="modal-buttons">
                    <button type="button" class="btn-modal cancelar" onclick="cerrarModal()">Cancelar</button>
                    <button type="submit" class="btn-modal confirmar">Enviar</button>
                </div>
            </form>
        </div>
    </div>
    
    <script>
        function abrirModal() {
            document.getElementById('modal').classList.add('show');
            document.getElementById('alert').classList.remove('show');
        }
        
        function cerrarModal() {
            document.getElementById('modal').classList.remove('show');
        }
        
        function mostrarAlerta(mensaje, tipo) {
            const alert = document.getElementById('alert');
            alert.textContent = mensaje;
            alert.className = 'alert show ' + tipo;
        }
        
        async function enviarEmail(event) {
            event.preventDefault();
            
            const email = document.getElementById('emailDestino').value;
            const btnSubmit = event.target.querySelector('button[type="submit"]');
            btnSubmit.disabled = true;
            btnSubmit.textContent = 'Enviando...';
            
            try {
                const response = await fetch('/admin/email/{{ peticion.id }}/enviar', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ email: email })
                });
                
                const data = await response.json();
                
                if (data.success) {
                    mostrarAlerta(data.message, 'success');
                    
                    // Agregar al historial
                    const container = document.getElementById('historial-container');
                    const empty = container.querySelector('.historial-empty');
                    if (empty) empty.remove();
                    
                    const nuevoItem = document.createElement('div');
                    nuevoItem.className = 'historial-item exitoso';
                    nuevoItem.innerHTML = `
                        <div class="email">${data.envio.email}</div>
                        <div class="fecha">${data.envio.fecha}</div>
                        <div class="estado exitoso">✓ Enviado correctamente</div>
                    `;
                    container.insertBefore(nuevoItem, container.firstChild);
                    
                    setTimeout(() => {
                        cerrarModal();
                    }, 2000);
                } else {
                    mostrarAlerta(data.message, 'error');
                }
            } catch (error) {
                mostrarAlerta('Error de conexión: ' + error.message, 'error');
            } finally {
                btnSubmit.disabled = false;
                btnSubmit.textContent = 'Enviar';
            }
        }
        
        // Cerrar modal al hacer clic fuera
        document.getElementById('modal').addEventListener('click', function(e) {
            if (e.target === this) {
                cerrarModal();
            }
        });
    </script>
</body>
</html>
'''

LOGIN_TEMPLATE = '''
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login - Lotify Backup</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        .login-container {
            background: white;
            padding: 40px;
            border-radius: 10px;
            box-shadow: 0 10px 40px rgba(0,0,0,0.2);
            width: 100%;
            max-width: 400px;
        }
        h1 {
            color: #333;
            margin-bottom: 30px;
            text-align: center;
            font-size: 24px;
        }
        .form-group {
            margin-bottom: 20px;
        }
        label {
            display: block;
            margin-bottom: 8px;
            color: #555;
            font-weight: 500;
        }
        input {
            width: 100%;
            padding: 12px;
            border: 2px solid #e0e0e0;
            border-radius: 6px;
            font-size: 14px;
            transition: border-color 0.3s;
        }
        input:focus {
            outline: none;
            border-color: #667eea;
        }
        button {
            width: 100%;
            padding: 12px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            border-radius: 6px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: transform 0.2s;
        }
        button:hover {
            transform: translateY(-2px);
        }
        .error {
            background: #fee;
            color: #c33;
            padding: 12px;
            border-radius: 6px;
            margin-bottom: 20px;
            text-align: center;
        }
    </style>
</head>
<body>
    <div class="login-container">
        <h1>🔒 Lotify Backup</h1>
        {% if error %}
        <div class="error">Usuario o contraseña incorrectos</div>
        {% endif %}
        <form method="POST">
            <div class="form-group">
                <label>Usuario</label>
                <input type="text" name="username" required autofocus>
            </div>
            <div class="form-group">
                <label>Contraseña</label>
                <input type="password" name="password" required>
            </div>
            <button type="submit">Iniciar Sesión</button>
        </form>
    </div>
</body>
</html>
'''

ADMIN_TEMPLATE = '''
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin - Lotify Backup</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: #f5f5f5;
            padding: 20px;
        }
        .header {
            background: white;
            padding: 20px;
            border-radius: 10px;
            margin-bottom: 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        h1 {
            color: #333;
            font-size: 24px;
        }
        .logout-btn {
            padding: 10px 20px;
            background: #dc3545;
            color: white;
            text-decoration: none;
            border-radius: 6px;
            font-weight: 500;
            transition: background 0.3s;
        }
        .logout-btn:hover {
            background: #c82333;
        }
        .stats {
            background: white;
            padding: 20px;
            border-radius: 10px;
            margin-bottom: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
        }
        .stat-card {
            padding: 20px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 8px;
            text-align: center;
        }
        .stat-number {
            font-size: 32px;
            font-weight: bold;
            margin-bottom: 5px;
        }
        .stat-label {
            font-size: 14px;
            opacity: 0.9;
        }
        .table-container {
            background: white;
            border-radius: 10px;
            overflow: hidden;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        table {
            width: 100%;
            border-collapse: collapse;
        }
        th {
            background: #667eea;
            color: white;
            padding: 15px;
            text-align: left;
            font-weight: 600;
            font-size: 13px;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }
        td {
            padding: 12px 15px;
            border-bottom: 1px solid #f0f0f0;
            font-size: 14px;
            color: #333;
        }
        tr:hover {
            background: #f8f9fa;
        }
        .pagination {
            display: flex;
            justify-content: center;
            gap: 10px;
            padding: 20px;
            background: white;
            border-radius: 0 0 10px 10px;
        }
        .pagination a {
            padding: 8px 16px;
            background: #667eea;
            color: white;
            text-decoration: none;
            border-radius: 6px;
            transition: background 0.3s;
        }
        .pagination a:hover {
            background: #764ba2;
        }
        .pagination .disabled {
            background: #ccc;
            pointer-events: none;
        }
        .pagination .current {
            background: #764ba2;
        }
        .empty {
            text-align: center;
            padding: 40px;
            color: #999;
        }
        .overflow {
            max-width: 200px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }
        .btn-email {
            padding: 6px 12px;
            background: #28a745;
            color: white;
            text-decoration: none;
            border-radius: 4px;
            font-size: 12px;
            font-weight: 500;
            transition: background 0.3s;
            display: inline-block;
        }
        .btn-email:hover {
            background: #218838;
        }
        .sortable {
            cursor: pointer;
            user-select: none;
            position: relative;
            padding-right: 20px;
        }
        .sortable:hover {
            background: #5568d3;
        }
        .sort-icon {
            position: absolute;
            right: 5px;
            font-size: 10px;
        }
        .filter-row input {
            width: 100%;
            padding: 6px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 12px;
        }
        .filter-row input:focus {
            outline: none;
            border-color: #667eea;
        }
        .filter-row th {
            background: #f8f9fa;
            padding: 8px;
        }
        .btn-clear-filters {
            padding: 8px 16px;
            background: #6c757d;
            color: white;
            text-decoration: none;
            border-radius: 6px;
            font-size: 12px;
            margin-left: 10px;
        }
        .btn-clear-filters:hover {
            background: #5a6268;
        }
    </style>
</head>
<body>
    <div class="header">
        <h1>LOTIFY Requester - Backup de Pedidos</h1>
        <a href="{{ url_for('logout') }}" class="logout-btn">Cerrar Sesión</a>
    </div>
    
    <div class="stats">
        <div class="stats-grid">
            <div class="stat-card">
                <div class="stat-number">{{ peticiones.total }}</div>
                <div class="stat-label">Total Registros</div>
            </div>
            <div class="stat-card">
                <div class="stat-number">{{ peticiones.pages }}</div>
                <div class="stat-label">Total Páginas</div>
            </div>
            <div class="stat-card">
                <div class="stat-number">{{ peticiones.page }}</div>
                <div class="stat-label">Página Actual</div>
            </div>
        </div>
    </div>
    
    <div class="table-container">
        {% if peticiones.items %}
        <div style="overflow-x: auto;">
        <form method="GET" action="{{ url_for('admin_view') }}" id="filterForm">
            <input type="hidden" name="sort" value="{{ sort_by }}">
            <input type="hidden" name="order" value="{{ sort_order }}">
        <table>
            <thead>
                <tr>
                    <th>Acciones</th>
                    <th class="sortable" onclick="sortTable('id')">
                        ID <span class="sort-icon">{% if sort_by == 'id' %}{{ '▼' if sort_order == 'desc' else '▲' }}{% else %}⇅{% endif %}</span>
                    </th>
                    <th class="sortable" onclick="sortTable('datetime_registro')">
                        Fecha/Hora <span class="sort-icon">{% if sort_by == 'datetime_registro' %}{{ '▼' if sort_order == 'desc' else '▲' }}{% else %}⇅{% endif %}</span>
                    </th>
                    <th class="sortable" onclick="sortTable('empresa')">
                        Empresa <span class="sort-icon">{% if sort_by == 'empresa' %}{{ '▼' if sort_order == 'desc' else '▲' }}{% else %}⇅{% endif %}</span>
                    </th>
                    <th class="sortable" onclick="sortTable('empleado')">
                        Empleado <span class="sort-icon">{% if sort_by == 'empleado' %}{{ '▼' if sort_order == 'desc' else '▲' }}{% else %}⇅{% endif %}</span>
                    </th>
                    <th class="sortable" onclick="sortTable('telefono')">
                        Teléfono <span class="sort-icon">{% if sort_by == 'telefono' %}{{ '▼' if sort_order == 'desc' else '▲' }}{% else %}⇅{% endif %}</span>
                    </th>
                    <th class="sortable" onclick="sortTable('email')">
                        Email <span class="sort-icon">{% if sort_by == 'email' %}{{ '▼' if sort_order == 'desc' else '▲' }}{% else %}⇅{% endif %}</span>
                    </th>
                    <th class="sortable" onclick="sortTable('codigo_lote')">
                        Código Lote <span class="sort-icon">{% if sort_by == 'codigo_lote' %}{{ '▼' if sort_order == 'desc' else '▲' }}{% else %}⇅{% endif %}</span>
                    </th>
                    <th class="sortable" onclick="sortTable('tipo_lote')">
                        Tipo Lote <span class="sort-icon">{% if sort_by == 'tipo_lote' %}{{ '▼' if sort_order == 'desc' else '▲' }}{% else %}⇅{% endif %}</span>
                    </th>
                    <th class="sortable" onclick="sortTable('entrega')">
                        Entrega <span class="sort-icon">{% if sort_by == 'entrega' %}{{ '▼' if sort_order == 'desc' else '▲' }}{% else %}⇅{% endif %}</span>
                    </th>
                    <th class="sortable" onclick="sortTable('direccion')">
                        Dirección <span class="sort-icon">{% if sort_by == 'direccion' %}{{ '▼' if sort_order == 'desc' else '▲' }}{% else %}⇅{% endif %}</span>
                    </th>
                    <th>Franja Desde</th>
                    <th>Franja Hasta</th>
                    <th>Desglose Dir.</th>
                    <th>Detalle Dir.</th>
                    <th>CP</th>
                    <th class="sortable" onclick="sortTable('desglose_poblacion')">
                        Población <span class="sort-icon">{% if sort_by == 'desglose_poblacion' %}{{ '▼' if sort_order == 'desc' else '▲' }}{% else %}⇅{% endif %}</span>
                    </th>
                    <th class="sortable" onclick="sortTable('desglose_provincia')">
                        Provincia <span class="sort-icon">{% if sort_by == 'desglose_provincia' %}{{ '▼' if sort_order == 'desc' else '▲' }}{% else %}⇅{% endif %}</span>
                    </th>
                    <th class="sortable" onclick="sortTable('identificador_cliente')">
                        ID Cliente <span class="sort-icon">{% if sort_by == 'identificador_cliente' %}{{ '▼' if sort_order == 'desc' else '▲' }}{% else %}⇅{% endif %}</span>
                    </th>
                    <th>Observaciones</th>
                    <th class="sortable" onclick="sortTable('sociedad')">
                        Sociedad <span class="sort-icon">{% if sort_by == 'sociedad' %}{{ '▼' if sort_order == 'desc' else '▲' }}{% else %}⇅{% endif %}</span>
                    </th>
                    <th class="sortable" onclick="sortTable('delegacion')">
                        Delegación <span class="sort-icon">{% if sort_by == 'delegacion' %}{{ '▼' if sort_order == 'desc' else '▲' }}{% else %}⇅{% endif %}</span>
                    </th>
                </tr>
                <tr class="filter-row">
                    <th></th>
                    <th></th>
                    <th></th>
                    <th><input type="text" name="filter_empresa" value="{{ filters.get('empresa', '') }}" placeholder="Filtrar..."></th>
                    <th><input type="text" name="filter_empleado" value="{{ filters.get('empleado', '') }}" placeholder="Filtrar..."></th>
                    <th><input type="text" name="filter_telefono" value="{{ filters.get('telefono', '') }}" placeholder="Filtrar..."></th>
                    <th><input type="text" name="filter_email" value="{{ filters.get('email', '') }}" placeholder="Filtrar..."></th>
                    <th><input type="text" name="filter_codigo_lote" value="{{ filters.get('codigo_lote', '') }}" placeholder="Filtrar..."></th>
                    <th><input type="text" name="filter_tipo_lote" value="{{ filters.get('tipo_lote', '') }}" placeholder="Filtrar..."></th>
                    <th><input type="text" name="filter_entrega" value="{{ filters.get('entrega', '') }}" placeholder="Filtrar..."></th>
                    <th><input type="text" name="filter_direccion" value="{{ filters.get('direccion', '') }}" placeholder="Filtrar..."></th>
                    <th></th>
                    <th></th>
                    <th></th>
                    <th></th>
                    <th></th>
                    <th><input type="text" name="filter_desglose_poblacion" value="{{ filters.get('desglose_poblacion', '') }}" placeholder="Filtrar..."></th>
                    <th><input type="text" name="filter_desglose_provincia" value="{{ filters.get('desglose_provincia', '') }}" placeholder="Filtrar..."></th>
                    <th><input type="text" name="filter_identificador_cliente" value="{{ filters.get('identificador_cliente', '') }}" placeholder="Filtrar..."></th>
                    <th></th>
                    <th><input type="text" name="filter_sociedad" value="{{ filters.get('sociedad', '') }}" placeholder="Filtrar..."></th>
                    <th><input type="text" name="filter_delegacion" value="{{ filters.get('delegacion', '') }}" placeholder="Filtrar..."></th>
                </tr>
            </thead>
            <tbody>
                {% for p in peticiones.items %}
                <tr>
                    <td style="white-space: nowrap;">
                        <a href="{{ url_for('ver_email', id=p.id) }}" target="_blank" class="btn-email">📧 Ver Email</a>
                    </td>
                    <td>{{ p.id }}</td>
                    <td style="white-space: nowrap;">{{ p.datetime_registro.strftime('%Y-%m-%d %H:%M:%S') }}</td>
                    <td class="overflow">{{ p.empresa or '-' }}</td>
                    <td class="overflow">{{ p.empleado or '-' }}</td>
                    <td>{{ p.telefono or '-' }}</td>
                    <td class="overflow">{{ p.email or '-' }}</td>
                    <td>{{ p.codigo_lote or '-' }}</td>
                    <td>{{ p.tipo_lote or '-' }}</td>
                    <td>{{ p.entrega or '-' }}</td>
                    <td class="overflow">{{ p.direccion or '-' }}</td>
                    <td>{{ p.franja_horaria_desde or '-' }}</td>
                    <td>{{ p.franja_horaria_hasta or '-' }}</td>
                    <td class="overflow">{{ p.desglose_direccion or '-' }}</td>
                    <td class="overflow">{{ p.desglose_detalle_direccion or '-' }}</td>
                    <td>{{ p.desglose_cp or '-' }}</td>
                    <td>{{ p.desglose_poblacion or '-' }}</td>
                    <td>{{ p.desglose_provincia or '-' }}</td>
                    <td>{{ p.identificador_cliente or '-' }}</td>
                    <td class="overflow">{{ p.observaciones or '-' }}</td>
                    <td>{{ p.sociedad or '-' }}</td>
                    <td>{{ p.delegacion or '-' }}</td>
                </tr>
                {% endfor %}
            </tbody>
        </table>
        </form>
        </div>
        
        <div class="pagination">
            {% if peticiones.page > 1 %}
            <a href="?page=1&sort={{ sort_by }}&order={{ sort_order }}{% for k, v in filters.items() %}&filter_{{ k }}={{ v }}{% endfor %}">⏮ Primera</a>
            {% else %}
            <a class="disabled">⏮ Primera</a>
            {% endif %}
            
            {% if peticiones.has_prev %}
            <a href="?page={{ peticiones.prev_num }}&sort={{ sort_by }}&order={{ sort_order }}{% for k, v in filters.items() %}&filter_{{ k }}={{ v }}{% endfor %}">← Anterior</a>
            {% else %}
            <a class="disabled">← Anterior</a>
            {% endif %}
            
            <a class="current">Página {{ peticiones.page }} de {{ peticiones.pages }}</a>
            
            {% if peticiones.has_next %}
            <a href="?page={{ peticiones.next_num }}&sort={{ sort_by }}&order={{ sort_order }}{% for k, v in filters.items() %}&filter_{{ k }}={{ v }}{% endfor %}">Siguiente →</a>
            {% else %}
            <a class="disabled">Siguiente →</a>
            {% endif %}
            
            {% if peticiones.page < peticiones.pages %}
            <a href="?page={{ peticiones.pages }}&sort={{ sort_by }}&order={{ sort_order }}{% for k, v in filters.items() %}&filter_{{ k }}={{ v }}{% endfor %}">Última ⏭</a>
            {% else %}
            <a class="disabled">Última ⏭</a>
            {% endif %}
            
            {% if filters %}
            <a href="{{ url_for('admin_view') }}" class="btn-clear-filters">✖ Limpiar Filtros</a>
            {% endif %}
        </div>
        {% else %}
        <div class="empty">
            <p>No hay registros disponibles</p>
        </div>
        {% endif %}
    </div>
    
    <script>
        function sortTable(column) {
            const currentSort = '{{ sort_by }}';
            const currentOrder = '{{ sort_order }}';
            let newOrder = 'asc';
            
            if (column === currentSort) {
                newOrder = currentOrder === 'asc' ? 'desc' : 'asc';
            }
            
            const form = document.getElementById('filterForm');
            form.querySelector('[name="sort"]').value = column;
            form.querySelector('[name="order"]').value = newOrder;
            form.submit();
        }
        
        // Auto-submit al escribir en filtros (con debounce)
        let filterTimeout;
        document.querySelectorAll('.filter-row input').forEach(input => {
            input.addEventListener('input', function() {
                clearTimeout(filterTimeout);
                filterTimeout = setTimeout(() => {
                    document.getElementById('filterForm').submit();
                }, 800);
            });
        });
    </script>
</body>
</html>
'''

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=8073)
