from flask import Flask, jsonify, request, send_file, make_response
from flask_cors import CORS
from flask_jwt_extended import JWTManager, jwt_required, get_jwt_identity, create_access_token, create_refresh_token
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address
from datetime import datetime, timedelta, timezone
import random
import xml.etree.ElementTree as ET
from io import BytesIO, StringIO
import base64
import qrcode
from PIL import Image, ImageDraw, ImageFont
import os
import bcrypt
import re
from functools import wraps
from database import init_database
from services import UserService, OrderService, ProductService, DashboardService, ExtendedProductService, SalesService

app = Flask(__name__)

# Configure CORS to allow requests from your frontend domain
CORS(app, 
     origins=[
         "http://localhost:3000",  # Development frontend
         "http://localhost:5173",  # Vite dev server
         "http://localhost:5174",  # Vite dev server (alternate port)
         "http://127.0.0.1:5173",  # Vite dev server (IP)
         "http://127.0.0.1:5174",  # Vite dev server (IP alternate port)
         "https://reports.brunomurer.com.br",  # Production frontend
         "http://reports.brunomurer.com.br"   # Production frontend (HTTP fallback)
     ],
     methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"],
     allow_headers=["Content-Type", "Authorization"],
     supports_credentials=True
)

# JWT Configuration
app.config['JWT_SECRET_KEY'] = os.environ.get('JWT_SECRET_KEY', 'dev-secret-change-me')
app.config['JWT_ACCESS_TOKEN_EXPIRES'] = timedelta(hours=1)
app.config['JWT_REFRESH_TOKEN_EXPIRES'] = timedelta(days=30)
app.config['JWT_TOKEN_LOCATION'] = ['headers']
app.config['JWT_HEADER_NAME'] = 'Authorization'
app.config['JWT_HEADER_TYPE'] = 'Bearer'

# Initialize JWT
jwt = JWTManager(app)

# Rate Limiting
limiter = Limiter(
    app=app,
    key_func=get_remote_address,
    default_limits=["200 per day", "50 per hour"]
)

# Initialize database tables
try:
    init_database()
    print("✅ Database tables initialized successfully")
except Exception as e:
    print(f"❌ Failed to initialize database: {e}")

# Create default users if they don't exist
def create_default_users():
    """Create default admin and user accounts"""
    try:
        # Create admin user
        if not UserService.get_user_by_username("admin"):
            UserService.create_user("admin", "admin@lemis.com", "admin123", "admin")
            print("✅ Created default admin user")

        # Create regular user
        if not UserService.get_user_by_username("user"):
            UserService.create_user("user", "user@lemis.com", "user123", "user")
            print("✅ Created default user")

    except Exception as e:
        print(f"❌ Failed to create default users: {e}")

create_default_users()

# Handle preflight OPTIONS requests
@app.before_request
def handle_preflight():
    if request.method == "OPTIONS":
        response = make_response()
        response.headers.add("Access-Control-Allow-Origin", "*")
        response.headers.add('Access-Control-Allow-Headers', "Content-Type,Authorization")
        response.headers.add('Access-Control-Allow-Methods', "GET,PUT,POST,DELETE,OPTIONS")
        return response

# Security validation functions
def validate_email(email):
    """Validate email format"""
    pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
    return re.match(pattern, email) is not None

def validate_password(password):
    """Validate password strength"""
    if len(password) < 6:
        return False, "Password must be at least 6 characters long"
    if not re.search(r'[A-Z]', password):
        return False, "Password must contain at least one uppercase letter"
    if not re.search(r'[a-z]', password):
        return False, "Password must contain at least one lowercase letter"
    if not re.search(r'[0-9]', password):
        return False, "Password must contain at least one number"
    return True, "Password is valid"

def sanitize_input(text):
    """Sanitize user input to prevent XSS"""
    if not text:
        return text
    # Remove potential script tags and other dangerous content
    text = re.sub(r'<[^>]*>', '', text)
    text = re.sub(r'javascript:', '', text, flags=re.IGNORECASE)
    text = re.sub(r'on\w+\s*=', '', text, flags=re.IGNORECASE)
    return text.strip()

def admin_required(fn):
    """Decorator to require admin role"""
    @wraps(fn)
    @jwt_required()
    def wrapper(*args, **kwargs):
        current_user = get_jwt_identity()
        user = UserService.get_user_by_username(current_user)
        if not user or user.role != 'admin':
            return jsonify({"error": "Admin access required"}), 403
        return fn(*args, **kwargs)
    return wrapper

# JWT Callbacks
@jwt.user_lookup_loader
def user_lookup_callback(_jwt_header, jwt_data):
    """Load user from JWT data"""
    identity = jwt_data["sub"]
    return UserService.get_user_by_username(identity)

@jwt.expired_token_loader
def expired_token_callback(jwt_header, jwt_payload):
    """Handle expired tokens"""
    return jsonify({
        "error": "Token has expired",
        "message": "Please refresh your token or login again"
    }), 401

@jwt.invalid_token_loader
def invalid_token_callback(error):
    """Handle invalid tokens"""
    return jsonify({
        "error": "Invalid token",
        "message": "Token is invalid or malformed"
    }), 401

@jwt.unauthorized_loader
def missing_token_callback(error):
    """Handle missing tokens"""
    return jsonify({
        "error": "Missing token",
        "message": "Authorization token is required"
    }), 401

# Authentication Endpoints
@app.route('/api/auth/login', methods=['POST'])
@limiter.limit("5 per minute")
def login():
    """Authenticate user and return JWT tokens"""
    try:
        data = request.get_json()
        if not data or 'username' not in data or 'password' not in data:
            return jsonify({"error": "Username and password are required"}), 400

        username = sanitize_input(data['username'])
        password = data['password']

        # Validate input
        if not username or not password:
            return jsonify({"error": "Username and password cannot be empty"}), 400

        # Find user
        user = UserService.get_user_by_username(username)
        if not user:
            return jsonify({"error": "Invalid credentials"}), 401

        # Verify password
        if not user.check_password(password):
            return jsonify({"error": "Invalid credentials"}), 401

        # Update last login
        UserService.update_last_login(username)

        # Create tokens
        access_token = create_access_token(identity=username, additional_claims={"role": user.role})
        refresh_token = create_refresh_token(identity=username)

        return jsonify({
            "message": "Login successful",
            "access_token": access_token,
            "refresh_token": refresh_token,
            "user": {
                "id": user.id,
                "username": user.username,
                "email": user.email,
                "role": user.role
            },
            "expires_in": int(app.config['JWT_ACCESS_TOKEN_EXPIRES'].total_seconds())
        }), 200

    except Exception as e:
        return jsonify({"error": "Login failed", "details": str(e)}), 500

@app.route('/api/auth/register', methods=['POST'])
@limiter.limit("3 per hour")
def register():
    """Register a new user"""
    try:
        data = request.get_json()
        if not data:
            return jsonify({"error": "No data provided"}), 400

        username = sanitize_input(data.get('username', ''))
        email = sanitize_input(data.get('email', ''))
        password = data.get('password', '')

        # Validate required fields
        if not username or not email or not password:
            return jsonify({"error": "Username, email, and password are required"}), 400

        # Validate email format
        if not validate_email(email):
            return jsonify({"error": "Invalid email format"}), 400

        # Validate password strength
        is_valid_password, password_error = validate_password(password)
        if not is_valid_password:
            return jsonify({"error": password_error}), 400

        # Check if user already exists
        if UserService.get_user_by_username(username):
            return jsonify({"error": "Username already exists"}), 409

        # Check if email already exists
        if UserService.get_user_by_email(email):
            return jsonify({"error": "Email already exists"}), 409

        # Create new user
        new_user = UserService.create_user(username, email, password, "user")

        return jsonify({
            "message": "User registered successfully",
            "user": {
                "id": new_user.id,
                "username": new_user.username,
                "email": new_user.email,
                "role": new_user.role
            }
        }), 201

    except Exception as e:
        return jsonify({"error": "Registration failed", "details": str(e)}), 500

@app.route('/api/auth/refresh', methods=['POST'])
@jwt_required(refresh=True)
def refresh_token():
    """Refresh access token using refresh token"""
    try:
        current_user = get_jwt_identity()
        user = UserService.get_user_by_username(current_user)

        if not user:
            return jsonify({"error": "User not found"}), 404

        access_token = create_access_token(
            identity=current_user,
            additional_claims={"role": user.role}
        )

        return jsonify({
            "message": "Token refreshed successfully",
            "access_token": access_token,
            "expires_in": int(app.config['JWT_ACCESS_TOKEN_EXPIRES'].total_seconds())
        }), 200

    except Exception as e:
        return jsonify({"error": "Token refresh failed", "details": str(e)}), 500

@app.route('/api/auth/logout', methods=['POST'])
@jwt_required()
def logout():
    """Logout user (client should discard tokens)"""
    try:
        current_user = get_jwt_identity()
        return jsonify({
            "message": "Logout successful",
            "user": current_user
        }), 200

    except Exception as e:
        return jsonify({"error": "Logout failed", "details": str(e)}), 500

@app.route('/api/auth/profile', methods=['GET'])
@jwt_required()
def get_user_profile():
    """Get current user profile"""
    try:
        current_user = get_jwt_identity()
        user = UserService.get_user_by_username(current_user)

        if not user:
            return jsonify({"error": "User not found"}), 404

        return jsonify({
            "user": {
                "id": user.id,
                "username": user.username,
                "email": user.email,
                "role": user.role,
                "created_at": user.created_at.isoformat() if user.created_at else None,
                "last_login": user.last_login.isoformat() if user.last_login else None
            }
        }), 200

    except Exception as e:
        return jsonify({"error": "Failed to get user profile", "details": str(e)}), 500

@app.route('/api/auth/change-password', methods=['POST'])
@jwt_required()
@limiter.limit("3 per hour")
def change_password():
    """Change user password"""
    try:
        current_user = get_jwt_identity()
        user = UserService.get_user_by_username(current_user)

        if not user:
            return jsonify({"error": "User not found"}), 404

        data = request.get_json()
        if not data or 'current_password' not in data or 'new_password' not in data:
            return jsonify({"error": "Current password and new password are required"}), 400

        current_password = data['current_password']
        new_password = data['new_password']

        # Verify current password
        if not user.check_password(current_password):
            return jsonify({"error": "Current password is incorrect"}), 401

        # Validate new password
        is_valid_password, password_error = validate_password(new_password)
        if not is_valid_password:
            return jsonify({"error": password_error}), 400

        # Update password
        user.set_password(new_password)
        # Note: In a real implementation, you would need to add an update method to UserService

        return jsonify({"message": "Password changed successfully"}), 200

    except Exception as e:
        return jsonify({"error": "Password change failed", "details": str(e)}), 500

# Mock data based on the original HTML dashboard
@app.route('/api/dashboard/summary', methods=['GET'])
def get_dashboard_summary():
    """Get daily sales summary"""
    try:
        summary_data = DashboardService.get_dashboard_summary()
        return jsonify(summary_data)
    except Exception as e:
        return jsonify({"error": str(e)}), 500

@app.route('/api/orders/status', methods=['GET'])
def get_orders_status():
    """Get orders by status"""
    try:
        status_data = DashboardService.get_orders_status()
        return jsonify(status_data)
    except Exception as e:
        return jsonify({"error": str(e)}), 500

@app.route('/api/orders/marketplace-breakdown', methods=['GET'])
def get_marketplace_breakdown():
    """Get orders breakdown by marketplace"""
    try:
        breakdown_data = DashboardService.get_marketplace_breakdown()
        return jsonify(breakdown_data)
    except Exception as e:
        return jsonify({"error": str(e)}), 500

@app.route('/api/orders/detailed-status', methods=['GET'])
def get_detailed_order_status():
    """Get detailed order status by marketplace"""
    return jsonify({
        "headers": ["Plataforma", "Recebido", "Separado", "Etiqueta", "Embalado", "Problema"],
        "data": [
            {
                "platform": "Mercado Livre",
                "logo": "https://cdn.worldvectorlogo.com/logos/mercado-livre-2.svg",
                "received": 10,
                "separated": 96,
                "labeled": 63,
                "packed": 7,
                "problem": 2
            },
            {
                "platform": "Shopee",
                "logo": "https://img.icons8.com/m_outlined/512/shopee.png",
                "received": 11,
                "separated": 31,
                "labeled": 0,
                "packed": 1,
                "problem": 1
            },
            {
                "platform": "Magalu",
                "logo": "https://sys.lojalemis.com/wp-content/uploads/icons/magalu.png",
                "received": 3,
                "separated": 8,
                "labeled": 0,
                "packed": 13,
                "problem": 0
            },
            {
                "platform": "Amazon",
                "logo": "https://www.svgrepo.com/show/112049/amazon-logo.svg",
                "received": 1,
                "separated": 2,
                "labeled": 2,
                "packed": 4,
                "problem": 1
            },
            {
                "platform": "Site",
                "logo": "https://sys.lojalemis.com/wp-content/uploads/icons/lemis.png",
                "received": 0,
                "separated": 1,
                "labeled": 0,
                "packed": 0,
                "problem": 0
            },
            {
                "platform": "BelezaNaWeb",
                "logo": "https://sys.lojalemis.com/wp-content/uploads/icons/blz.png",
                "received": 0,
                "separated": 0,
                "labeled": 0,
                "packed": 0,
                "problem": 0
            },
            {
                "platform": "WebContinental",
                "logo": "https://sys.lojalemis.com/wp-content/uploads/icons/webcontinental.png",
                "received": 6,
                "separated": 1,
                "labeled": 5,
                "packed": 0,
                "problem": 1
            },
            {
                "platform": "RDMarketplace",
                "logo": "https://sys.lojalemis.com/wp-content/uploads/icons/rdmarketplace.png",
                "received": 0,
                "separated": 0,
                "labeled": 0,
                "packed": 0,
                "problem": 0
            },
            {
                "platform": "Outros",
                "logo": "",
                "received": 0,
                "separated": 0,
                "labeled": 0,
                "packed": 0,
                "problem": 0
            }
        ]
    })

@app.route('/api/sales/monthly', methods=['GET'])
def get_monthly_sales():
    """Get monthly sales data for charts"""
    return jsonify({
        "monthly_total": 308055.40,
        "monthly_average": 15402.77,
        "monthly_expected": 477485.87,
        "monthly_goal": 403000.00,
        "progress_percentage": (308055.40 / 403000.00) * 100
    })

@app.route('/api/sales/chart-data', methods=['GET'])
def get_sales_chart_data():
    """Get sales chart data for line chart"""
    # Generate sample daily sales data for the current month
    today = datetime.now()
    days_in_month = 30  # Simplified

    sales_data = []
    for i in range(days_in_month):
        date = (today.replace(day=1) + timedelta(days=i)).strftime("%d/%m/%Y")
        weekday = (today.replace(day=1) + timedelta(days=i)).strftime("%A")[:3]

        # Generate realistic sales data
        base_sales = 15000 + random.randint(-8000, 15000)
        sales_data.append({
            "date": date,
            "weekday": weekday,
            "sales": max(0, base_sales),
            "goal": 13000,
            "average": 13000 + random.randint(-2000, 3000)
        })

    return jsonify(sales_data)

@app.route('/api/sales/platform-breakdown', methods=['GET'])
def get_platform_sales_breakdown():
    """Get sales breakdown by platform for pie chart"""
    return jsonify([
        {"platform": "MercadoLivre", "sales": 106064.59, "percentage": 37},
        {"platform": "Shopee", "sales": 135791.19, "percentage": 47.3},
        {"platform": "Magalu", "sales": 18762.86, "percentage": 6.5},
        {"platform": "Amazon", "sales": 3717, "percentage": 1.3},
        {"platform": "Site", "sales": 2040.8, "percentage": 0.7},
        {"platform": "BelezaNaWeb", "sales": 1921.2, "percentage": 0.7},
        {"platform": "Outros", "sales": 18650.76, "percentage": 6.5}
    ])

@app.route('/api/business/daily-sales/<date>', methods=['GET'])
def get_daily_sales(date):
    """
    Replicate vendas_hoje.php logic - Get sales data for specific date with platform breakdown
    """
    try:
        # Parse date parameter
        if not date:
            date = datetime.now().strftime('%Y-%m-%d')

        # Get daily sales data from database
        daily_sales_data = OrderService.get_daily_sales_data(date)

        return jsonify(daily_sales_data)

    except Exception as e:
        return jsonify({"error": str(e)}), 500

@app.route('/api/business/sales-period', methods=['GET'])
def get_sales_period():
    """
    Replicate vendas_periodo.php logic - Get sales data for date range with 7-day averages
    """
    try:
        # Get date parameters
        data_ini = request.args.get('dataIni', datetime.now().strftime('%Y-%m-%d'))
        data_fin = request.args.get('dataFin', datetime.now().strftime('%Y-%m-%d'))

        # Get sales period data from database
        period_data = OrderService.get_sales_period_data(data_ini, data_fin)

        return jsonify(period_data)

    except Exception as e:
        return jsonify({"error": str(e)}), 500

def calculate_7day_average(target_date, data_values, platform):
    """
    Calculate 7-day average for a specific platform - replicates PHP function
    """
    try:
        target_dt = datetime.strptime(target_date, '%Y-%m-%d')
        sum_values = 0
        days_counted = 0

        # Calculate average of last 7 days
        for i in range(7):
            check_date = (target_dt - timedelta(days=i)).strftime('%Y-%m-%d')
            if check_date in data_values and platform in data_values[check_date]:
                sum_values += data_values[check_date][platform]
                days_counted += 1

        return round(sum_values / days_counted, 2) if days_counted > 0 else 0

    except:
        return 0

@app.route('/api/business/product-analysis', methods=['GET'])
def get_product_analysis():
    """
    Replicate vendas_produtos.php logic - Product performance analysis
    """
    try:
        # Get date parameters
        data_ini = request.args.get('dataIni', (datetime.now() - timedelta(days=30)).strftime('%Y-%m-%d'))
        data_fin = request.args.get('dataFin', datetime.now().strftime('%Y-%m-%d'))

        # Mock product analysis data
        # In real implementation, this would query orders and products tables
        lojas = ['Geral', 'Shopee Store', 'Shopee One', 'Shopee KS', 'MercadoLivre One', 'MercadoLivre Store', 'Magalu One', 'Magalu Store', 'Site']

        product_analysis = {}

        for loja in lojas:
            product_analysis[loja] = {
                "items": {
                    "101528": {
                        "nome": "Produto Exemplo 1",
                        "url": f"/produto/101528",
                        "custo": 25.50,
                        "unidades": 85,
                        "valor": 599.90
                    },
                    "103170": {
                        "nome": "Produto Exemplo 2",
                        "url": f"/produto/103170",
                        "custo": 15.75,
                        "unidades": 120,
                        "valor": 899.25
                    },
                    "104285": {
                        "nome": "Produto Exemplo 3",
                        "url": f"/produto/104285",
                        "custo": 35.00,
                        "unidades": 45,
                        "valor": 1249.50
                    }
                },
                "marcas": {
                    "2512": {"valor": 8999.90, "nome": "Marca A"},
                    "2153": {"valor": 2994.90, "nome": "Marca B"},
                    "1897": {"valor": 1549.75, "nome": "Marca C"}
                },
                "totals": {
                    "custo_total": 0,
                    "venda_total": 0,
                    "margem_total": 0,
                    "lucro_total": 0
                }
            }

            # Calculate totals for the store
            custo_loja = 0
            venda_loja = 0

            for item in product_analysis[loja]["items"].values():
                custo_loja += item['custo'] * item['unidades']
                venda_loja += item['valor']

            margem_total = ((venda_loja - custo_loja) / venda_loja) * 100 if venda_loja > 0 else 0
            lucro_total = venda_loja - custo_loja

            product_analysis[loja]["totals"] = {
                "custo_total": round(custo_loja, 2),
                "venda_total": round(venda_loja, 2),
                "margem_total": round(margem_total, 2),
                "lucro_total": round(lucro_total, 2)
            }

        return jsonify({
            "date_range": {
                "start": data_ini,
                "end": data_fin
            },
            "lojas": lojas,
            "product_analysis": product_analysis
        })

    except Exception as e:
        return jsonify({"error": str(e)}), 500

@app.route('/api/business/margin-analysis', methods=['GET'])
def get_margin_analysis():
    """
    Replicate vendas_margens.php logic - Profit margin analysis
    """
    try:
        # Get date parameters
        data_ini = request.args.get('dataIni', (datetime.now() - timedelta(days=30)).strftime('%Y-%m-%d'))
        data_fin = request.args.get('dataFin', datetime.now().strftime('%Y-%m-%d'))

        # Mock margin analysis data
        margin_analysis = {
            "date_range": {
                "start": data_ini,
                "end": data_fin
            },
            "overall_metrics": {
                "total_cost": 45250.75,
                "total_sales": 125480.30,
                "total_profit": 80229.55,
                "average_margin": 63.92
            },
            "by_platform": {
                "MercadoLivre": {
                    "cost": 15230.50,
                    "sales": 42015.75,
                    "profit": 26785.25,
                    "margin": 63.75
                },
                "Shopee": {
                    "cost": 18540.25,
                    "sales": 48562.80,
                    "profit": 30022.55,
                    "margin": 61.85
                },
                "Magalu": {
                    "cost": 3480.00,
                    "sales": 8902.75,
                    "profit": 5422.75,
                    "margin": 60.92
                },
                "Amazon": {
                    "cost": 1200.00,
                    "sales": 2999.00,
                    "profit": 1799.00,
                    "margin": 60.00
                },
                "Site": {
                    "cost": 6800.00,
                    "sales": 22000.00,
                    "profit": 15200.00,
                    "margin": 69.09
                }
            },
            "top_profitable_products": [
                {
                    "id": "101528",
                    "name": "Produto Premium A",
                    "cost": 45.00,
                    "price": 120.00,
                    "units_sold": 150,
                    "profit": 11250.00,
                    "margin": 62.50
                },
                {
                    "id": "103170",
                    "name": "Produto Premium B",
                    "cost": 35.50,
                    "price": 95.00,
                    "units_sold": 200,
                    "profit": 11900.00,
                    "margin": 62.11
                }
            ],
            "low_margin_products": [
                {
                    "id": "104285",
                    "name": "Produto Básico C",
                    "cost": 8.50,
                    "price": 15.00,
                    "units_sold": 300,
                    "profit": 1950.00,
                    "margin": 43.33
                }
            ]
        }

        return jsonify(margin_analysis)

    except Exception as e:
        return jsonify({"error": str(e)}), 500

@app.route('/api/advanced/xml-process', methods=['POST'])
@jwt_required()
@limiter.limit("10 per minute")
def process_xml():
    """
    Process XML files for invoices and orders - replicates ler_xml/ functionality
    """
    try:
        if 'file' not in request.files:
            return jsonify({"error": "No file provided"}), 400

        file = request.files['file']
        if file.filename == '':
            return jsonify({"error": "No file selected"}), 400

        if not file.filename.lower().endswith('.xml'):
            return jsonify({"error": "File must be XML format"}), 400

        # Read and parse XML content
        xml_content = file.read()
        root = ET.fromstring(xml_content)

        # Extract NFe information (Brazilian invoice standard)
        processed_data = {
            "filename": file.filename,
            "processed_at": datetime.now().isoformat(),
            "invoice_info": {},
            "products": [],
            "taxes": {},
            "totals": {}
        }

        # Extract main invoice information
        if root.find(".//{http://www.portalfiscal.inf.br/nfe}infNFe") is not None:
            inf_nfe = root.find(".//{http://www.portalfiscal.inf.br/nfe}infNFe")

            # Invoice number and series
            ide = inf_nfe.find(".//{http://www.portalfiscal.inf.br/nfe}ide")
            if ide is not None:
                processed_data["invoice_info"]["number"] = ide.findtext(".//{http://www.portalfiscal.inf.br/nfe}nNF", "")
                processed_data["invoice_info"]["series"] = ide.findtext(".//{http://www.portalfiscal.inf.br/nfe}serie", "")
                processed_data["invoice_info"]["issue_date"] = ide.findtext(".//{http://www.portalfiscal.inf.br/nfe}dhEmi", "")

            # Products/Items
            for det in inf_nfe.findall(".//{http://www.portalfiscal.inf.br/nfe}det"):
                product = {
                    "item_number": det.get("nItem", ""),
                    "code": det.findtext(".//{http://www.portalfiscal.inf.br/nfe}cProd", ""),
                    "name": det.findtext(".//{http://www.portalfiscal.inf.br/nfe}xProd", ""),
                    "ncm": det.findtext(".//{http://www.portalfiscal.inf.br/nfe}NCM", ""),
                    "cfop": det.findtext(".//{http://www.portalfiscal.inf.br/nfe}CFOP", ""),
                    "quantity": det.findtext(".//{http://www.portalfiscal.inf.br/nfe}qCom", "0"),
                    "unit_price": det.findtext(".//{http://www.portalfiscal.inf.br/nfe}vUnCom", "0"),
                    "total_value": det.findtext(".//{http://www.portalfiscal.inf.br/nfe}vProd", "0")
                }
                processed_data["products"].append(product)

            # Totals
            total = inf_nfe.find(".//{http://www.portalfiscal.inf.br/nfe}total")
            if total is not None:
                icms_total = total.find(".//{http://www.portalfiscal.inf.br/nfe}ICMSTot")
                if icms_total is not None:
                    processed_data["totals"] = {
                        "total_products": icms_total.findtext(".//{http://www.portalfiscal.inf.br/nfe}vProd", "0"),
                        "total_icms": icms_total.findtext(".//{http://www.portalfiscal.inf.br/nfe}vICMS", "0"),
                        "total_taxes": icms_total.findtext(".//{http://www.portalfiscal.inf.br/nfe}vTotTrib", "0"),
                        "grand_total": icms_total.findtext(".//{http://www.portalfiscal.inf.br/nfe}vNF", "0")
                    }

        return jsonify(processed_data)

    except ET.ParseError as e:
        return jsonify({"error": f"XML parsing error: {str(e)}"}), 400
    except Exception as e:
        return jsonify({"error": str(e)}), 500

@app.route('/api/advanced/barcode/generate', methods=['POST'])
@jwt_required()
@limiter.limit("20 per minute")
def generate_barcode():
    """
    Generate barcode images - replicates barcode/generator/ functionality
    """
    try:
        data = request.get_json()
        if not data or 'code' not in data:
            return jsonify({"error": "Code parameter is required"}), 400

        code = data['code']
        barcode_type = data.get('type', 'code128')  # Default to Code 128
        width = data.get('width', 300)
        height = data.get('height', 100)

        # Generate barcode using python-barcode (simplified implementation)
        # In a real implementation, you would use a proper barcode library

        # Create a simple barcode representation
        barcode_image = generate_simple_barcode(code, width, height)

        # Convert to base64 for web transmission
        buffered = BytesIO()
        barcode_image.save(buffered, format="PNG")
        barcode_base64 = base64.b64encode(buffered.getvalue()).decode('utf-8')

        return jsonify({
            "barcode": f"data:image/png;base64,{barcode_base64}",
            "code": code,
            "type": barcode_type,
            "dimensions": f"{width}x{height}"
        })

    except Exception as e:
        return jsonify({"error": str(e)}), 500

def generate_simple_barcode(code, width, height):
    """
    Generate a simple barcode image (simplified implementation)
    In production, use a proper barcode library like python-barcode
    """
    # Create a new image with white background
    img = Image.new('RGB', (width, height), color='white')
    draw = ImageDraw.Draw(img)

    # Simple barcode representation (just for demonstration)
    # In real implementation, use proper barcode encoding

    # Draw barcode lines (simplified)
    bar_width = 2
    spacing = 1
    x_pos = 10

    for char in code:
        if char.isdigit():
            # Draw bars for digits (simplified)
            bar_height = height - 20 if int(char) % 2 == 0 else height - 40
            draw.rectangle([x_pos, 10, x_pos + bar_width, bar_height], fill='black')
        x_pos += bar_width + spacing

    # Add the code text below the barcode
    try:
        font = ImageFont.load_default()
        text_bbox = draw.textbbox((0, 0), code, font=font)
        text_width = text_bbox[2] - text_bbox[0]
        text_x = (width - text_width) // 2
        draw.text((text_x, height - 15), code, fill='black', font=font)
    except:
        # Fallback if font loading fails
        draw.text((10, height - 15), code, fill='black')

    return img

@app.route('/api/advanced/barcode/qrcode', methods=['POST'])
@jwt_required()
@limiter.limit("15 per minute")
def generate_qrcode():
    """
    Generate QR code images
    """
    try:
        data = request.get_json()
        if not data or 'data' not in data:
            return jsonify({"error": "Data parameter is required"}), 400

        qr_data = data['data']
        size = data.get('size', 200)
        fill_color = data.get('fill_color', 'black')
        back_color = data.get('back_color', 'white')

        # Generate QR code
        qr = qrcode.QRCode(
            version=1,
            error_correction=qrcode.constants.ERROR_CORRECT_L,
            box_size=10,
            border=4,
        )
        qr.add_data(qr_data)
        qr.make(fit=True)

        # Create QR code image
        img = qr.make_image(fill_color=fill_color, back_color=back_color)
        img = img.resize((size, size), Image.Resampling.LANCZOS)

        # Convert to base64
        buffered = BytesIO()
        img.save(buffered, format="PNG")
        qr_base64 = base64.b64encode(buffered.getvalue()).decode('utf-8')

        return jsonify({
            "qrcode": f"data:image/png;base64,{qr_base64}",
            "data": qr_data,
            "size": f"{size}x{size}"
        })

    except Exception as e:
        return jsonify({"error": str(e)}), 500

@app.route('/api/advanced/xml/list-files', methods=['GET'])
def list_xml_files():
    """
    List available XML files in uploads directory
    """
    try:
        # In a real implementation, this would list files from a configured uploads directory
        # For now, return mock data
        mock_files = [
            {"name": "Nfe_26230108749430000201550020001470251424764640_4304573909.xml", "size": "12.5 KB", "date": "2025-01-15"},
            {"name": "Nfe_26230305383942000110550020000069901703382874_4633443246.xml", "size": "8.3 KB", "date": "2025-01-14"},
            {"name": "Nfe_26230305383942000110550030001539241509913752_4542164672.xml", "size": "15.2 KB", "date": "2025-01-13"}
        ]

        return jsonify({
            "files": mock_files,
            "total": len(mock_files)
        })

    except Exception as e:
        return jsonify({"error": str(e)}), 500

@app.route('/api/advanced/barcode/types', methods=['GET'])
def get_barcode_types():
    """
    Get available barcode types and their specifications
    """
    try:
        barcode_types = {
            "code128": {
                "name": "Code 128",
                "description": "High-density barcode supporting alphanumeric characters",
                "max_length": "unlimited",
                "use_cases": ["product codes", "shipping labels", "inventory"]
            },
            "code39": {
                "name": "Code 39",
                "description": "Alphanumeric barcode with good readability",
                "max_length": "43 characters",
                "use_cases": ["inventory", "assets", "identification"]
            },
            "ean13": {
                "name": "EAN-13",
                "description": "13-digit barcode for retail products",
                "max_length": "13 digits",
                "use_cases": ["retail products", "UPC codes"]
            },
            "upc": {
                "name": "UPC-A",
                "description": "12-digit barcode for North American retail",
                "max_length": "12 digits",
                "use_cases": ["retail products", "North American market"]
            },
            "qrcode": {
                "name": "QR Code",
                "description": "2D barcode for storing various types of data",
                "max_length": "4,296 alphanumeric characters",
                "use_cases": ["URLs", "contact info", "product details", "marketing"]
            }
        }

        return jsonify(barcode_types)

    except Exception as e:
        return jsonify({"error": str(e)}), 500

# =====================================================
# EXPORT ENDPOINTS
# =====================================================

@app.route('/api/export/daily-sales-csv', methods=['GET'])
def export_daily_sales_csv():
    """
    Export daily sales data as CSV - replicates PHP export functionality
    """
    try:
        date = request.args.get('date', datetime.now().strftime('%Y-%m-%d'))

        # Get daily sales data
        daily_data = OrderService.get_daily_sales_data(date)

        # Create CSV content
        csv_content = generate_daily_sales_csv(daily_data)

        # Return as downloadable file
        response = make_response(csv_content)
        response.headers['Content-Type'] = 'text/csv'
        response.headers['Content-Disposition'] = f'attachment; filename=vendas-diarias-{date}.csv'

        return response

    except Exception as e:
        return jsonify({"error": str(e)}), 500

@app.route('/api/export/period-sales-csv', methods=['GET'])
def export_period_sales_csv():
    """
    Export period sales data as CSV with 7-day averages
    """
    try:
        start_date = request.args.get('start_date', (datetime.now() - timedelta(days=30)).strftime('%Y-%m-%d'))
        end_date = request.args.get('end_date', datetime.now().strftime('%Y-%m-%d'))

        # Get period data
        period_data = OrderService.get_sales_period_data(start_date, end_date)

        # Create CSV content
        csv_content = generate_period_sales_csv(period_data)

        # Return as downloadable file
        response = make_response(csv_content)
        response.headers['Content-Type'] = 'text/csv'
        response.headers['Content-Disposition'] = f'attachment; filename=vendas-periodo-{start_date}-a-{end_date}.csv'

        return response

    except Exception as e:
        return jsonify({"error": str(e)}), 500

@app.route('/api/export/product-analysis-csv', methods=['GET'])
def export_product_analysis_csv():
    """
    Export product analysis data as CSV
    """
    try:
        start_date = request.args.get('start_date', (datetime.now() - timedelta(days=30)).strftime('%Y-%m-%d'))
        end_date = request.args.get('end_date', datetime.now().strftime('%Y-%m-%d'))

        # Get product analysis data
        product_data = SalesService.get_product_analysis_data(start_date, end_date)

        # Create CSV content
        csv_content = generate_product_analysis_csv(product_data)

        # Return as downloadable file
        response = make_response(csv_content)
        response.headers['Content-Type'] = 'text/csv'
        response.headers['Content-Disposition'] = f'attachment; filename=analise-produtos-{start_date}-a-{end_date}.csv'

        return response

    except Exception as e:
        return jsonify({"error": str(e)}), 500

def generate_daily_sales_csv(daily_data):
    """
    Generate CSV content for daily sales data
    """
    import io
    import csv

    output = io.StringIO()
    writer = csv.writer(output, delimiter=';', quotechar='"')

    # Write header
    writer.writerow(['Plataforma', 'Pedidos', 'Valor Total', 'Frete Total'])

    # Write data
    for platform, data in daily_data['platform_totals'].items():
        writer.writerow([
            platform,
            data['orders'],
            f"R$ {data['total']:.2f}".replace('.', ','),
            f"R$ {data['freight']:.2f}".replace('.', ',')
        ])

    # Write summary
    writer.writerow([])
    writer.writerow(['Resumo do Dia'])
    writer.writerow(['Valor Pedidos', f"R$ {daily_data['summary']['valor_pedidos']:.2f}".replace('.', ',')])
    writer.writerow(['Valor Fretes', f"R$ {daily_data['summary']['valor_fretes']:.2f}".replace('.', ',')])
    writer.writerow(['Valor Total', f"R$ {daily_data['summary']['valor_total']:.2f}".replace('.', ',')])
    writer.writerow(['Número de Pedidos', daily_data['summary']['num_pedidos']])

    return output.getvalue()

def generate_period_sales_csv(period_data):
    """
    Generate CSV content for period sales data with 7-day averages
    """
    import io
    import csv

    output = io.StringIO()
    writer = csv.writer(output, delimiter=';', quotechar='"')

    # Write daily data
    writer.writerow(['=== VENDAS DIÁRIAS ==='])
    writer.writerow(['Data', 'Geral', 'MercadoLivre', 'Shopee', 'Magalu', 'Amazon', 'Site', 'BelezaNaWeb', 'WebContinental'])

    for date, data in period_data['daily_data'].items():
        writer.writerow([
            date,
            f"R$ {data['geral']:.2f}".replace('.', ','),
            f"R$ {data['MercadoLivre']:.2f}".replace('.', ','),
            f"R$ {data['Shopee']:.2f}".replace('.', ','),
            f"R$ {data['Magalu']:.2f}".replace('.', ','),
            f"R$ {data['Amazon']:.2f}".replace('.', ','),
            f"R$ {data['Site']:.2f}".replace('.', ','),
            f"R$ {data['BelezaNaWeb']:.2f}".replace('.', ','),
            f"R$ {data['WebContinental']:.2f}".replace('.', ',')
        ])

    # Write 7-day averages
    writer.writerow([])
    writer.writerow(['=== MÉDIAS MÓVEIS DE 7 DIAS ==='])
    writer.writerow(['Data', 'Geral', 'MercadoLivre', 'Shopee', 'Magalu', 'Amazon', 'Site', 'BelezaNaWeb', 'WebContinental'])

    for date, data in period_data['moving_averages'].items():
        writer.writerow([
            date,
            f"R$ {data['geral']:.2f}".replace('.', ','),
            f"R$ {data['MercadoLivre']:.2f}".replace('.', ','),
            f"R$ {data['Shopee']:.2f}".replace('.', ','),
            f"R$ {data['Magalu']:.2f}".replace('.', ','),
            f"R$ {data['Amazon']:.2f}".replace('.', ','),
            f"R$ {data['Site']:.2f}".replace('.', ','),
            f"R$ {data['BelezaNaWeb']:.2f}".replace('.', ','),
            f"R$ {data['WebContinental']:.2f}".replace('.', ',')
        ])

    return output.getvalue()

def generate_product_analysis_csv(product_data):
    """
    Generate CSV content for product analysis data
    """
    import io
    import csv

    output = io.StringIO()
    writer = csv.writer(output, delimiter=';', quotechar='"')

    # Write data for each store
    for store, store_data in product_data.items():
        writer.writerow([f'=== {store.upper()} ==='])
        writer.writerow(['Produto', 'Código', 'Unidades', 'Valor', 'Custo', 'Margem'])

        for item_id, item in store_data['items'].items():
            margem = ((item['valor'] - (item['custo'] * item['unidades'])) / item['valor']) * 100 if item['valor'] > 0 else 0
            writer.writerow([
                item['nome'],
                item_id,
                item['unidades'],
                f"R$ {item['valor']:.2f}".replace('.', ','),
                f"R$ {item['custo'] * item['unidades']:.2f}".replace('.', ','),
                f"{margem:.2f}%"
            ])

        # Write store totals
        totals = store_data['totals']
        writer.writerow([])
        writer.writerow(['Totais da Loja'])
        writer.writerow(['Custo Total', f"R$ {totals['custo_total']:.2f}".replace('.', ',')])
        writer.writerow(['Venda Total', f"R$ {totals['venda_total']:.2f}".replace('.', ',')])
        writer.writerow(['Margem Total', f"{totals['margem_total']:.2f}%"])
        writer.writerow(['Lucro Total', f"R$ {totals['lucro_total']:.2f}".replace('.', ',')])
        writer.writerow([])

    return output.getvalue()

@app.route('/api/admin/users', methods=['GET'])
@admin_required
def get_all_users():
    """Admin endpoint to get all users (admin only)"""
    try:
        users_list = []
        users = UserService.get_all_users()
        for user in users:
            users_list.append({
                "id": user.id,
                "username": user.username,
                "email": user.email,
                "role": user.role,
                "created_at": user.created_at.isoformat() if user.created_at else None,
                "last_login": user.last_login.isoformat() if user.last_login else None
            })

        return jsonify({
            "users": users_list,
            "total": len(users_list)
        }), 200

    except Exception as e:
        return jsonify({"error": "Failed to get users", "details": str(e)}), 500

@app.route('/api/admin/users/<user_id>', methods=['DELETE'])
@admin_required
def delete_user(user_id):
    """Admin endpoint to delete a user (admin only)"""
    try:
        user_id = int(user_id)

        # Don't allow deleting the current admin
        current_user = get_jwt_identity()
        current_user_obj = UserService.get_user_by_username(current_user)
        if current_user_obj and current_user_obj.id == user_id:
            return jsonify({"error": "Cannot delete your own account"}), 400

        # Delete user using service
        success = UserService.delete_user(user_id)

        if not success:
            return jsonify({"error": "User not found"}), 404

        return jsonify({"message": f"User deleted successfully"}), 200

    except Exception as e:
        return jsonify({"error": "Failed to delete user", "details": str(e)}), 500

@app.route('/api/admin/system-status', methods=['GET'])
@admin_required
def get_system_status():
    """Admin endpoint to get system status (admin only)"""
    try:
        return jsonify({
            "system_status": "online",
            "server_time": datetime.now(timezone.utc).isoformat(),
            "total_users": len(UserService.get_all_users()),
            "active_endpoints": [
                "/api/dashboard/*",
                "/api/business/*",
                "/api/advanced/*",
                "/api/auth/*",
                "/api/admin/*"
            ],
            "rate_limits": {
                "login": "5 per minute",
                "registration": "3 per hour",
                "password_change": "3 per hour",
                "xml_processing": "10 per minute",
                "barcode_generation": "20 per minute",
                "qrcode_generation": "15 per minute"
            },
            "security_features": [
                "JWT Authentication",
                "Password Hashing (bcrypt)",
                "Rate Limiting",
                "Input Sanitization",
                "XSS Prevention",
                "CORS Protection"
            ]
        }), 200

    except Exception as e:
        return jsonify({"error": "Failed to get system status", "details": str(e)}), 500

@app.route('/api/admin/audit-log', methods=['GET'])
@admin_required
def get_audit_log():
    """Admin endpoint to get system audit log (admin only)"""
    try:
        # Mock audit log (in real implementation, this would come from database)
        audit_log = [
            {
                "timestamp": (datetime.now(timezone.utc) - timedelta(hours=1)).isoformat(),
                "user": "admin",
                "action": "login",
                "ip_address": "192.168.1.100",
                "status": "success"
            },
            {
                "timestamp": (datetime.now(timezone.utc) - timedelta(hours=2)).isoformat(),
                "user": "user",
                "action": "xml_process",
                "ip_address": "192.168.1.101",
                "status": "success"
            },
            {
                "timestamp": (datetime.now(timezone.utc) - timedelta(hours=3)).isoformat(),
                "user": "admin",
                "action": "barcode_generate",
                "ip_address": "192.168.1.100",
                "status": "success"
            }
        ]

        return jsonify({
            "audit_log": audit_log,
            "total_entries": len(audit_log)
        }), 200

    except Exception as e:
        return jsonify({"error": "Failed to get audit log", "details": str(e)}), 500

@app.route('/api/notifications', methods=['GET'])
def get_notifications():
    """Get dashboard notifications"""
    return jsonify({
        "count": 16,
        "categories": {
            "shopee_performance": {
                "title": "Verificar desempenho da Shopee",
                "message": "Shopee Store, Shopee Ks, Shopee One",
                "urgent": True
            },
            "problem_orders": {
                "title": "Pedidos com problema",
                "items": [
                    {"id": "#345146", "date": "13/08/2025"},
                    {"id": "#347337", "date": "19/08/2025"},
                    {"id": "#347471", "date": "19/08/2025"},
                    {"id": "#347694", "date": "19/08/2025"},
                    {"id": "#347799", "date": "20/08/2025"}
                ]
            },
            "freight_combine_orders": {
                "title": "Pedidos com frete a combinar",
                "items": [
                    {"id": "#342650", "date": "20/08/2025", "address": "Rua 1 número 188, apto 901 CEP 74.115-050 Goiânia- Go"}
                ]
            },
            "duplicate_orders": {
                "title": "Vendas Duplicadas",
                "items": [
                    {"id": "#348063", "type": "1ª"},
                    {"id": "#348091", "type": "1ª"},
                    {"id": "#348064", "type": "2ª"},
                    {"id": "#348092", "type": "2ª"},
                    {"id": "#348065", "type": "3ª"},
                    {"id": "#348093", "type": "3ª"},
                    {"id": "#348066", "type": "4ª"},
                    {"id": "#348094", "type": "4ª"},
                    {"id": "#348067", "type": "5ª"},
                    {"id": "#348095", "type": "5ª"},
                    {"id": "#348068", "type": "6ª"},
                    {"id": "#348096", "type": "6ª"},
                    {"id": "#348069", "type": "7ª"},
                    {"id": "#348097", "type": "7ª"},
                    {"id": "#348070", "type": "8ª"},
                    {"id": "#348098", "type": "8ª"},
                    {"id": "#348071", "type": "9ª"},
                    {"id": "#348099", "type": "9ª"},
                    {"id": "#348072", "type": "10ª"},
                    {"id": "#348100", "type": "10ª"},
                    {"id": "#348073", "type": "11ª"},
                    {"id": "#348101", "type": "11ª"},
                    {"id": "#348074", "type": "12ª"},
                    {"id": "#348102", "type": "12ª"}
                ]
            },
            "labels_without_tracking": {
                "title": "Pedidos com Etiqueta sem rastreio",
                "items": [
                    {"id": "#347995"},
                    {"id": "#347997"},
                    {"id": "#348005"},
                    {"id": "#348006"},
                    {"id": "#348011"},
                    {"id": "#348018"},
                    {"id": "#348023"},
                    {"id": "#348027"},
                    {"id": "#348029"},
                    {"id": "#348031"},
                    {"id": "#348041"},
                    {"id": "#348069"},
                    {"id": "#348084"},
                    {"id": "#348087"},
                    {"id": "#348089"},
                    {"id": "#348092"},
                    {"id": "#348096"}
                ]
            },
            "suggested_purchases": {
                "title": "Pedidos sugeridos",
                "items": [
                    {
                        "supplier": "VIAESTETIC",
                        "min_order": 100.00,
                        "current_order": 4259.80,
                        "link": "https://sys.lojalemis.com/compras/?relatorio=relavendas&days_query=60&days_stock=30&fornecedor_vazio=290319&pedido_minimo=100"
                    },
                    {
                        "supplier": "COALA",
                        "min_order": 850.00,
                        "current_order": 990.78,
                        "link": "https://sys.lojalemis.com/compras/?relatorio=relavendas&days_query=60&days_stock=30&fornecedor_vazio=174069&pedido_minimo=850"
                    },
                    {
                        "supplier": "DEPIL BELLA",
                        "min_order": 1000.00,
                        "current_order": 1479.89,
                        "link": "https://sys.lojalemis.com/compras/?relatorio=relavendas&days_query=60&days_stock=30&fornecedor_vazio=125249&pedido_minimo=1000"
                    },
                    {
                        "supplier": "CIMED",
                        "min_order": 300.00,
                        "current_order": 951.97,
                        "link": "https://sys.lojalemis.com/compras/?relatorio=relavendas&days_query=60&days_stock=30&fornecedor_vazio=98052&pedido_minimo=300"
                    },
                    {
                        "supplier": "JR PERIM COSMETICOS",
                        "min_order": 600.00,
                        "current_order": 3673.38,
                        "link": "https://sys.lojalemis.com/compras/?relatorio=relavendas&days_query=60&days_stock=30&fornecedor_vazio=95786&pedido_minimo=600"
                    },
                    {
                        "supplier": "WAPA",
                        "min_order": 1000.00,
                        "current_order": 1124.26,
                        "link": "https://sys.lojalemis.com/compras/?relatorio=relavendas&days_query=60&days_stock=30&fornecedor_vazio=89486&pedido_minimo=1000"
                    },
                    {
                        "supplier": "MART",
                        "min_order": 1000.00,
                        "current_order": 1307.36,
                        "link": "https://sys.lojalemis.com/compras/?relatorio=relavendas&days_query=60&days_stock=30&fornecedor_vazio=71055&pedido_minimo=1000"
                    },
                    {
                        "supplier": "GRANADO",
                        "min_order": 800.00,
                        "current_order": 2379.64,
                        "link": "https://sys.lojalemis.com/compras/?relatorio=relavendas&days_query=60&days_stock=30&fornecedor_vazio=71074&pedido_minimo=800"
                    },
                    {
                        "supplier": "LENVIE",
                        "min_order": 1500.00,
                        "current_order": 6742.37,
                        "link": "https://sys.lojalemis.com/compras/?relatorio=relavendas&days_query=60&days_stock=30&fornecedor_vazio=71174&pedido_minimo=1500"
                    },
                    {
                        "supplier": "ROJEMAC",
                        "min_order": 2500.00,
                        "current_order": 9870.37,
                        "link": "https://sys.lojalemis.com/compras/?relatorio=relavendas&days_query=60&days_stock=30&fornecedor_vazio=71119&pedido_minimo=2500"
                    },
                    {
                        "supplier": "ALLEANZA",
                        "min_order": 1500.00,
                        "current_order": 1797.63,
                        "link": "https://sys.lojalemis.com/compras/?relatorio=relavendas&days_query=60&days_stock=30&fornecedor_vazio=71167&pedido_minimo=1500"
                    },
                    {
                        "supplier": "COLISEU",
                        "min_order": 1300.00,
                        "current_order": 9588.31,
                        "link": "https://sys.lojalemis.com/compras/?relatorio=relavendas&days_query=60&days_stock=30&fornecedor_vazio=71057&pedido_minimo=1300"
                    },
                    {
                        "supplier": "MAESTRAL",
                        "min_order": 1000.00,
                        "current_order": 6476.38,
                        "link": "https://sys.lojalemis.com/compras/?relatorio=relavendas&days_query=60&days_stock=30&fornecedor_vazio=71239&pedido_minimo=1000"
                    }
                ]
            }
        }
    })

# =====================================================
# EXTENDED PRODUCT MANAGEMENT ENDPOINTS
# =====================================================

@app.route('/api/products/extended', methods=['POST'])
@jwt_required()
def create_extended_product():
    """Create a product with codes, galleries, and attributes (WordPress-like)"""
    try:
        user_id = get_jwt_identity()
        user = UserService.get_user_by_id(int(user_id))
        if not user or not user.is_active:
            return jsonify({"error": "Unauthorized"}), 401

        data = request.get_json()
        if not data:
            return jsonify({"error": "No data provided"}), 400

        product = ExtendedProductService.create_product_with_details(data)
        return jsonify({
            "message": "Product created successfully",
            "product_id": product.id,
            "product": {
                "id": product.id,
                "sku": product.sku,
                "name": product.name,
                "sale_price": product.sale_price,
                "category": product.category
            }
        }), 201
    except ValueError as e:
        return jsonify({"error": str(e)}), 400
    except Exception as e:
        logger.error(f"Error creating extended product: {e}")
        return jsonify({"error": "Internal server error"}), 500

@app.route('/api/products/search', methods=['GET'])
@jwt_required()
def search_products():
    """Search products with filters (replicating WordPress search)"""
    try:
        user_id = get_jwt_identity()
        user = UserService.get_user_by_id(int(user_id))
        if not user or not user.is_active:
            return jsonify({"error": "Unauthorized"}), 401

        query = request.args.get('q', '')
        category = request.args.get('category', '')
        min_price = request.args.get('min_price', type=float)
        max_price = request.args.get('max_price', type=float)
        in_stock_only = request.args.get('in_stock_only', type=bool, default=False)
        limit = request.args.get('limit', 50, type=int)

        filters = {}
        if category:
            filters['category'] = category
        if min_price is not None:
            filters['min_price'] = min_price
        if max_price is not None:
            filters['max_price'] = max_price
        if in_stock_only:
            filters['in_stock_only'] = in_stock_only

        products = ExtendedProductService.search_products(query, filters, limit)
        return jsonify({
            "products": products,
            "count": len(products),
            "query": query,
            "filters": filters
        }), 200
    except Exception as e:
        logger.error(f"Error searching products: {e}")
        return jsonify({"error": "Internal server error"}), 500

@app.route('/api/products/<int:product_id>/extended', methods=['GET'])
@jwt_required()
def get_extended_product(product_id):
    """Get a single product with all details"""
    try:
        user_id = get_jwt_identity()
        user = UserService.get_user_by_id(int(user_id))
        if not user or not user.is_active:
            return jsonify({"error": "Unauthorized"}), 401

        product = ProductService.get_product_by_id(product_id)
        if not product:
            return jsonify({"error": "Product not found"}), 404

        # Get extended data
        products = ExtendedProductService.search_products('', {}, 1)
        product_data = next((p for p in products if p['id'] == product_id), None)

        if not product_data:
            return jsonify({"error": "Product data not found"}), 404

        return jsonify(product_data), 200
    except Exception as e:
        logger.error(f"Error getting extended product: {e}")
        return jsonify({"error": "Internal server error"}), 500

# =====================================================
# SALES MANAGEMENT ENDPOINTS
# =====================================================

@app.route('/api/sales', methods=['POST'])
@jwt_required()
def create_sale():
    """Create a new sale (replicating WordPress sale creation)"""
    try:
        user_id = get_jwt_identity()
        user = UserService.get_user_by_id(int(user_id))
        if not user or not user.is_active:
            return jsonify({"error": "Unauthorized"}), 401

        data = request.get_json()
        if not data:
            return jsonify({"error": "No data provided"}), 400

        sale = SalesService.create_sale(data)
        return jsonify({
            "message": "Sale created successfully",
            "sale_id": sale.id,
            "id_venda": sale.id_venda,
            "total": sale.total
        }), 201
    except ValueError as e:
        return jsonify({"error": str(e)}), 400
    except Exception as e:
        logger.error(f"Error creating sale: {e}")
        return jsonify({"error": "Internal server error"}), 500

@app.route('/api/sales', methods=['GET'])
@jwt_required()
def get_sales():
    """Get sales with filters (replicating WordPress sales queries)"""
    try:
        user_id = get_jwt_identity()
        user = UserService.get_user_by_id(int(user_id))
        if not user or not user.is_active:
            return jsonify({"error": "Unauthorized"}), 401

        # Get filter parameters
        start_date = request.args.get('start_date')
        end_date = request.args.get('end_date')
        vendedor = request.args.get('vendedor')
        cliente = request.args.get('cliente')
        plataforma = request.args.get('plataforma')
        limit = request.args.get('limit', 100, type=int)

        filters = {}
        if start_date:
            filters['start_date'] = start_date
        if end_date:
            filters['end_date'] = end_date
        if vendedor:
            filters['vendedor'] = vendedor
        if cliente:
            filters['cliente'] = cliente
        if plataforma:
            filters['plataforma'] = plataforma

        sales = SalesService.get_sales(filters, limit)
        return jsonify({
            "sales": sales,
            "count": len(sales),
            "filters": filters
        }), 200
    except Exception as e:
        logger.error(f"Error getting sales: {e}")
        return jsonify({"error": "Internal server error"}), 500

@app.route('/api/sales/<int:sale_id>', methods=['GET'])
@jwt_required()
def get_sale(sale_id):
    """Get a single sale with all details"""
    try:
        user_id = get_jwt_identity()
        user = UserService.get_user_by_id(int(user_id))
        if not user or not user.is_active:
            return jsonify({"error": "Unauthorized"}), 401

        # For now, get all sales and filter
        sales = SalesService.get_sales({}, 1000)
        sale_data = next((s for s in sales if s['id'] == sale_id), None)

        if not sale_data:
            return jsonify({"error": "Sale not found"}), 404

        return jsonify(sale_data), 200
    except Exception as e:
        logger.error(f"Error getting sale: {e}")
        return jsonify({"error": "Internal server error"}), 500

# =====================================================
# PRODUCT CATEGORIES AND ATTRIBUTES ENDPOINTS
# =====================================================

@app.route('/api/products/categories', methods=['GET'])
@jwt_required()
def get_product_categories():
    """Get all product categories"""
    try:
        user_id = get_jwt_identity()
        user = UserService.get_user_by_id(int(user_id))
        if not user or not user.is_active:
            return jsonify({"error": "Unauthorized"}), 401

        db = SessionLocal()
        try:
            from sqlalchemy import distinct
            categories = db.query(distinct(Product.category)).filter(
                Product.category.isnot(None),
                Product.category != ''
            ).all()

            category_list = [cat[0] for cat in categories]
            return jsonify({"categories": category_list}), 200
        finally:
            db.close()
    except Exception as e:
        logger.error(f"Error getting categories: {e}")
        return jsonify({"error": "Internal server error"}), 500

@app.route('/api/products/attributes/linha', methods=['GET'])
@jwt_required()
def get_linha_options():
    """Get available linha (line) options"""
    try:
        user_id = get_jwt_identity()
        user = UserService.get_user_by_id(int(user_id))
        if not user or not user.is_active:
            return jsonify({"error": "Unauthorized"}), 401

        # Predefined linha options based on WordPress analysis
        linha_options = [
            'premium', 'basica', 'fitness', 'casual', 'esportiva',
            'elegante', 'moderna', 'classica', 'tradicional'
        ]
        return jsonify({"linha_options": linha_options}), 200
    except Exception as e:
        logger.error(f"Error getting linha options: {e}")
        return jsonify({"error": "Internal server error"}), 500

# =====================================================
# FILE UPLOAD ENDPOINT
# =====================================================

@app.route('/api/upload/product-image', methods=['POST'])
@jwt_required()
def upload_product_image():
    """Upload product images (replicating WordPress upload functionality)"""
    try:
        user_id = get_jwt_identity()
        user = UserService.get_user_by_id(int(user_id))
        if not user or not user.is_active:
            return jsonify({"error": "Unauthorized"}), 401

        if 'file' not in request.files:
            return jsonify({"error": "No file provided"}), 400

        file = request.files['file']
        if file.filename == '':
            return jsonify({"error": "No file selected"}), 400

        # Validate file type
        allowed_extensions = {'png', 'jpg', 'jpeg', 'gif', 'webp'}
        if '.' not in file.filename:
            return jsonify({"error": "Invalid file"}), 400

        extension = file.filename.rsplit('.', 1)[1].lower()
        if extension not in allowed_extensions:
            return jsonify({"error": "File type not allowed"}), 400

        # Save file (in production, use cloud storage)
        import time
        filename = f"{user_id}_{int(time.time())}_{file.filename}"
        upload_dir = os.path.join(app.root_path, 'uploads', 'products')
        os.makedirs(upload_dir, exist_ok=True)

        file_path = os.path.join(upload_dir, filename)
        file.save(file_path)

        # Return file URL
        file_url = f"/uploads/products/{filename}"
        return jsonify({
            "message": "File uploaded successfully",
            "file_url": file_url,
            "filename": filename
        }), 200
    except Exception as e:
        logger.error(f"Error uploading file: {e}")
        return jsonify({"error": "Internal server error"}), 500

# =====================================================
# DASHBOARD ENHANCED ENDPOINTS
# =====================================================

@app.route('/api/dashboard/sales-performance', methods=['GET'])
@jwt_required()
def get_sales_performance():
    """Get enhanced sales performance data"""
    try:
        user_id = get_jwt_identity()
        user = UserService.get_user_by_id(int(user_id))
        if not user or not user.is_active:
            return jsonify({"error": "Unauthorized"}), 401

        db = SessionLocal()
        try:
            from sqlalchemy import func
            from datetime import datetime, timedelta

            # Get sales data for the last 30 days
            end_date = datetime.utcnow()
            start_date = end_date - timedelta(days=30)

            # Total sales
            total_sales = db.query(func.sum(Sale.total)).filter(
                Sale.data >= start_date,
                Sale.data <= end_date
            ).scalar() or 0

            # Sales by platform
            platform_sales = db.query(
                Sale.plataforma,
                func.count(Sale.id).label('count'),
                func.sum(Sale.total).label('total')
            ).filter(
                Sale.data >= start_date,
                Sale.data <= end_date
            ).group_by(Sale.plataforma).all()

            # Daily sales for chart
            daily_sales = []
            current_date = start_date
            while current_date <= end_date:
                day_total = db.query(func.sum(Sale.total)).filter(
                    Sale.data >= current_date,
                    Sale.data < current_date + timedelta(days=1)
                ).scalar() or 0
                daily_sales.append({
                    'date': current_date.strftime('%Y-%m-%d'),
                    'total': float(day_total)
                })
                current_date += timedelta(days=1)

            return jsonify({
                "total_sales": float(total_sales),
                "platform_breakdown": [{
                    "platform": platform or "Outros",
                    "count": count,
                    "total": float(total or 0)
                } for platform, count, total in platform_sales],
                "daily_sales": daily_sales,
                "period": {
                    "start": start_date.strftime('%Y-%m-%d'),
                    "end": end_date.strftime('%Y-%m-%d')
                }
            }), 200
        finally:
            db.close()
    except Exception as e:
        logger.error(f"Error getting sales performance: {e}")
        return jsonify({"error": "Internal server error"}), 500


if __name__ == '__main__':
    # Respect environment variables for production readiness
    host = os.environ.get('HOST', '66.94.112.114')
    port = int(os.environ.get('PORT', 5033))
    # FLASK_DEBUG=1 or FLASK_ENV=development enable debug; default to False
    flask_debug = os.environ.get('FLASK_DEBUG', '0') in ('1', 'true', 'True') or os.environ.get('FLASK_ENV') == 'development'
    app.run(debug=flask_debug, host=host, port=port)
