from flask import Blueprint, render_template
import mysql.connector
import os

config_bp = Blueprint('config', __name__)  # ✅ CORRECT name here

def get_db_connection():
    return mysql.connector.connect(
        host=os.getenv('MYSQL_HOST'),
        user=os.getenv('MYSQL_USER'),
        password=os.getenv('MYSQL_PASSWORD'),
        database=os.getenv('MYSQL_DB'),
        port=int(os.getenv('MYSQL_PORT', 3306))
    )

@config_bp.route('/config')  # ✅ Must match blueprint name
def config_page():
    try:
        conn = get_db_connection()
        cur = conn.cursor()
        cur.execute("SELECT * FROM config LIMIT 1")
        row = cur.fetchone()
        cur.close()
        conn.close()

        config_data = {
            'company_name': row[0] if row else '',
            'logo_path': row[2] if row else '',
            'primary_color': row[3] if row else '#000000',
            'secondary_color': row[4] if row else '#FFFFFF',
        }

        return render_template("config.html", config=config_data)
    except Exception as e:
        return f"<h1>❌ ERROR: {str(e)}</h1>"
