import requests
from flask import Flask, request, render_template_string, jsonify
import json
import os
import hmac
import hashlib
import base64
import mysql.connector
from datetime import datetime
from dotenv import load_dotenv
from flask import redirect

# Initialize Flask Application
app = Flask(__name__)

# Load environment variables from .env file (Security Best Practice)
load_dotenv()

# --- CONFIGURATION & CREDENTIALS ---
ZUM_USERNAME = os.getenv("ZUM_USERNAME")
ZUM_PASSWORD = os.getenv("ZUM_PASSWORD")
ZUM_ENV = os.getenv("ZUM_ENV")
ZUM_WEBHOOK_SECRET = os.getenv("ZUM_WEBHOOK_SECRET")
ZUM_WALLET_ID = os.getenv("ZUM_WALLET_ID")
ZUM_SECONDARY_WEBHOOK_URL = os.getenv("ZUM_SECONDARY_WEBHOOK_URL")

# --- DATABASE CONFIGURATION ---
DB_HOST = os.getenv("DB_HOST", "localhost")
DB_USER = os.getenv("DB_USER")
DB_PASSWORD = os.getenv("DB_PASSWORD")
DB_NAME = os.getenv("DB_NAME")
ADMIN_PASSWORD = os.getenv("ADMIN_PASSWORD", "admin123")

app.secret_key = os.getenv("FLASK_SECRET_KEY", "super-secret-key-123")

def get_db_connection():
    """Establishes and returns a MySQL database connection."""
    return mysql.connector.connect(
        host=DB_HOST,
        user=DB_USER,
        password=DB_PASSWORD,
        database=DB_NAME
    )

def init_db():
    """Initializes the database table if it doesn't exist."""
    try:
        conn = get_db_connection()
        cursor = conn.cursor()
        cursor.execute("""
            CREATE TABLE IF NOT EXISTS domains (
                id INT AUTO_INCREMENT PRIMARY KEY,
                domain VARCHAR(255) UNIQUE NOT NULL,
                status VARCHAR(50) DEFAULT 'active',
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
            )
        """)
        conn.commit()
        cursor.close()
        conn.close()
        print("✅ Database Initialized (MySQL)")
    except Exception as e:
        print(f"❌ Database Initialization Error: {e}")

# Call init_db on startup
init_db()

# 1. API ENVIRONMENT SWITCHER
# Automatically selects the Sandbox URL for testing or the App URL for production based on ZUM_ENV.
ZUM_API_URL = "https://api-sandbox.zumrails.com/api" if ZUM_ENV == "test" else "https://api-app.zumrails.com/api"

# Shopify Configuration (Target Store)
SHOPIFY_DOMAIN = os.getenv("SHOPIFY_DOMAIN")
SHOPIFY_ACCESS_TOKEN = os.getenv("SHOPIFY_ACCESS_TOKEN")




def get_order_details(order_id, shop_domain=None):
    """
    Fetches verified order details from Shopify Admin API.
    Returns (first_name, last_name, verified_amount).
    Never trust URL params for amount — always verify server-side.
    """
    target_domain = shop_domain or SHOPIFY_DOMAIN
    if not order_id or not SHOPIFY_ACCESS_TOKEN or not target_domain:
        return "", "", None

    try:
        url = f"https://{target_domain}/admin/api/2024-01/orders/{order_id}.json"
        headers = {"X-Shopify-Access-Token": SHOPIFY_ACCESS_TOKEN}
        resp = requests.get(url, headers=headers, timeout=5)

        print(f"🔍 Shopify API [{resp.status_code}] for order {order_id} on {target_domain}")

        if resp.status_code != 200:
            print(f"⚠️ Shopify fetch failed: {resp.text[:200]}")
            return "", "", None

        order = resp.json().get("order", {})

        # --- AMOUNT (always use Shopify's value, never the URL param) ---
        # The store charges in CAD (presentment currency).
        # total_price is in USD (Shopify's internal currency) — wrong.
        # total_outstanding is 0.00 in test mode (bogus gateway marks it paid) — wrong.
        # presentment_money is the actual CAD amount the customer sees — correct.
        verified_amount = (
            order.get("total_price_set", {})
                .get("presentment_money", {})
                .get("amount")
        )
        # Final safety fallback — should never be needed in production
        if not verified_amount or float(verified_amount) == 0:
            verified_amount = order.get("total_price")
            print(f"⚠️ Fell back to total_price: {verified_amount}")

        # --- NAME: billing → shipping → customer ---
        for src in [order.get("billing_address"), order.get("shipping_address"), order.get("customer")]:
            if src:
                first = (src.get("first_name") or "").strip()
                last  = (src.get("last_name")  or "").strip()
                if first or last:
                    return first, last, verified_amount

        return "", "", verified_amount

    except Exception as e:
        print(f"⚠️ get_order_details error: {e}")
        return "", "", None


# (Legacy/Backup Credentials commented out for reference)
# SHOPIFY_DOMAIN = "ftwx-3.myshopify.com"
# SHOPIFY_ACCESS_TOKEN = "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"


@app.route('/', methods=['GET', 'POST'])
def test():
    """Health check endpoint to verify the server is running."""
    return "Working"

@app.route('/start-payment', methods=['GET', 'POST'])
def start_payment():
    # --- STEP 1: EXTRACT DATA FROM URL ---
    order_id    = request.values.get('order_id')
    amount      = request.values.get('amount')       # untrusted — will be overwritten below
    email       = request.values.get('email')
    shop_domain = request.values.get('shop')
    first_name  = request.values.get('first_name', '').strip()
    last_name   = request.values.get('last_name',  '').strip()

    # --- STEP 1.5: DOMAIN VALIDATION ---
    try:
        conn = get_db_connection()
        cursor = conn.cursor(dictionary=True)
        cursor.execute("SELECT status FROM domains WHERE domain = %s", (shop_domain,))
        db_store = cursor.fetchone()
        cursor.close()
        conn.close()

        if not db_store:
            return f"""<div style="font-family:sans-serif;text-align:center;padding:50px;">
                <h2 style="color:#dc3545;">Store Not Registered</h2>
                <p>The store <b>{shop_domain}</b> is not authorized to use this payment gateway.</p>
                <p>Please contact <b>FintechWerx</b> support for registration.</p></div>"""

        if db_store['status'] != 'active':
            return f"""<div style="font-family:sans-serif;text-align:center;padding:50px;">
                <h2 style="color:#6c757d;">Account Inactive</h2>
                <p>Your Interac payment service is currently <b>inactive</b>.</p>
                <p>Please contact FintechWerx to reactivate your store.</p></div>"""

    except Exception as e:
        print(f"⚠️ Domain Validation Error: {e}")

    # --- STEP 2: VERIFY AMOUNT + FETCH NAMES FROM SHOPIFY (server-side) ---
    # SECURITY: The URL amount is NEVER trusted. We always fetch the real total
    # from Shopify so it cannot be tampered with by editing the URL.
    api_first, api_last, verified_amount = get_order_details(order_id, shop_domain)

    if verified_amount:
        amount = verified_amount          # overwrite URL amount with Shopify's real value
        print(f"✅ Amount verified from Shopify: ${amount}")
    else:
        print(f"🚫 Order {order_id} not found on {shop_domain}. Blocking request.")
        return """
        <div style="font-family:sans-serif;text-align:center;padding:60px 30px;">
            <h2 style="color:#dc3545;">Invalid Payment Link</h2>
            <p style="color:#555;max-width:400px;margin:0 auto;">
                This payment link is invalid or has expired.<br>
                Please return to the store and use the original link from your order confirmation.
            </p>
        </div>
        """

    if api_first and not first_name:
        first_name = api_first
    if api_last and not last_name:
        last_name = api_last

    # --- STEP 3: SEAMLESS MODE ---
    if email and "guest" not in email and order_id and amount:
        print(f"⚡ Seamless Mode: {first_name} {last_name} <{email}>")
        return process_zum_transaction(order_id, amount, email, shop_domain, first_name, last_name)

    # --- STEP 4: FALLBACK FORM (POST submission) ---
    if request.method == 'POST':
        email      = request.form.get('email')
        first_name = request.form.get('first_name', '').strip()
        last_name  = request.form.get('last_name',  '').strip()
        return process_zum_transaction(order_id, amount, email, shop_domain, first_name, last_name)

    # --- STEP 5: RENDER FORM ---
    if first_name or last_name:
        name_section = f"""
        <div style="display:flex;gap:10px;margin-bottom:15px;">
            <div style="flex:1;">
                <label style="display:block;margin-bottom:5px;font-size:13px;color:#555;">First Name</label>
                <input type="text" value="{first_name}" disabled
                       style="width:100%;padding:10px;box-sizing:border-box;background:#f5f5f5;
                              border:1px solid #ddd;border-radius:4px;color:#333;cursor:not-allowed;">
            </div>
            <div style="flex:1;">
                <label style="display:block;margin-bottom:5px;font-size:13px;color:#555;">Last Name</label>
                <input type="text" value="{last_name}" disabled
                       style="width:100%;padding:10px;box-sizing:border-box;background:#f5f5f5;
                              border:1px solid #ddd;border-radius:4px;color:#333;cursor:not-allowed;">
            </div>
        </div>
        <input type="hidden" name="first_name" value="{first_name}">
        <input type="hidden" name="last_name"  value="{last_name}">
        <p style="font-size:12px;color:#555;margin-top:-10px;margin-bottom:15px; background:#fff8e1;border-left:3px solid #FFD100;padding:8px 10px;border-radius:4px;">
            ⚠️ <strong>Important:</strong> The name above must exactly match the name registered 
            with your bank for Interac e-Transfer. Mismatched names may result in payment delays or rejection.
        </p>"""
    else:
        name_section = """
        <div style="display:flex;gap:10px;margin-bottom:15px;">
            <div style="flex:1;">
                <label style="display:block;margin-bottom:5px;font-size:13px;color:#555;">First Name</label>
                <input type="text" name="first_name" required placeholder="John"
                       style="width:100%;padding:10px;box-sizing:border-box;border:1px solid #ddd;border-radius:4px;">
            </div>
            <div style="flex:1;">
                <label style="display:block;margin-bottom:5px;font-size:13px;color:#555;">Last Name</label>
                <input type="text" name="last_name" required placeholder="Smith"
                       style="width:100%;padding:10px;box-sizing:border-box;border:1px solid #ddd;border-radius:4px;">
            </div>
        </div>"""

    return f"""
    <div style="font-family:sans-serif;max-width:420px;margin:50px auto;padding:30px;
                border:1px solid #ddd;border-radius:10px;box-shadow:0 2px 12px rgba(0,0,0,0.08);">
        <h2 style="text-align:center;margin-top:0;">Interac Payment</h2>
        <p style="text-align:center;color:#444;">Order <b>#{order_id}</b> &nbsp;|&nbsp; Total: <b>${amount}</b></p>
        <hr style="border:none;border-top:1px solid #eee;margin-bottom:20px;">
        <p style="color:#666;font-size:14px;margin-bottom:20px;">
            We couldn't detect your email automatically. Please enter it below to receive the Interac payment request.
        </p>
        <form method="POST">
            <input type="hidden" name="order_id" value="{order_id}">
            <input type="hidden" name="amount"   value="{amount}">
            <input type="hidden" name="shop"     value="{shop_domain}">
            {name_section}
            <label style="display:block;margin-bottom:5px;font-size:13px;color:#555;">Email Address</label>
            <input type="email" name="email" required placeholder="name@example.com"
                   style="width:100%;padding:10px;margin-bottom:20px;box-sizing:border-box;
                          border:1px solid #ddd;border-radius:4px;">
            <button type="submit"
                    style="width:100%;padding:13px;background:#FFD100;border:none;
                           border-radius:6px;font-weight:bold;font-size:15px;cursor:pointer;">
                Send Interac Request
            </button>
        </form>
    </div>"""

def verify_zum_signature(payload_bytes, signature):
    """Verifies that the webhook really came from Zum Rails."""
    if not ZUM_WEBHOOK_SECRET:
        return True  # Skip if secret not configured (for dev)

    clean_secret = ZUM_WEBHOOK_SECRET.strip()

    # ZUM Rails sends signature in BASE64 format, not hex
    expected_signature = base64.b64encode(
        hmac.new(
            clean_secret.encode('utf-8'),
            payload_bytes,
            hashlib.sha256
        ).digest()
    ).decode('utf-8')

    return hmac.compare_digest(expected_signature, signature)


# --- 3. THE WEBHOOK HANDLER (The Core Logic) ---
@app.route('/webhook', methods=['POST'])
def webhook():
    """
    Receives real-time updates from Zum Rails.
    1. Forwards data to the client's legacy system.
    2. Updates Shopify Order status (Paid/Failed).
    """
    # --- SECURITY: Verify Signature ---
    signature = request.headers.get('zumrails-signature')
    if not signature or not verify_zum_signature(request.data, signature):
        print("❌ SECURITY ALERT: Invalid Signature Received!")
        return jsonify({"message": "Invalid Signature"}), 401

    data = request.json
    print("\n🔔 WEBHOOK RECEIVED!")

    # --- A. DATA FORWARDING (RELAY) ---
    # We forward data to both the Legacy system AND the new Sandbox.
    destinations = [
        {"name": "Legacy PHP", "url": "https://payments.fintechwerx.com/order/zumrails/postback.php"},
        {"name": "New Sandbox", "url": ZUM_SECONDARY_WEBHOOK_URL}
    ]

    for dest in destinations:
        if not dest["url"]:
            continue
            
        try:
            print(f"➡️ Forwarding to {dest['name']}: {dest['url']}...")
            # Send exactly what we received. 
            # Note: headers (like zumrails-signature) are usually needed by the destination too.
            f_headers = {'zumrails-signature': signature, 'Content-Type': 'application/json'}
            forward_response = requests.post(dest["url"], json=data, headers=f_headers, timeout=5)
            print(f"✅ {dest['name']} Status: {forward_response.status_code}")
        except Exception as e:
            # "Fail Silently" as requested by client
            print(f"⚠️ Failed to forward to {dest['name']}: {e}")

    # --- B. LOGGING (DEBUGGING) ---
    # Save webhook payloads to a file for audit trails.
    try:
        with open('webhook_logs.json', 'a') as f:
            json.dump(data, f, indent=4)
            f.write("\n,\n")
        print("📁 Saved to webhook_logs.json")
    except Exception as e:
        print(f"Error saving log: {e}")

    # --- C. PARSE DATA ---
    # Zum Rails data is nested inside the 'Data' object.
    inner_data = data.get('Data', {})
    event_type = data.get('Event')  # e.g., "Succeeded"
    status = inner_data.get('TransactionStatus')  # e.g., "Completed"

    print(f"🔎 Status: {status} | Event: {event_type}")

    # --- D. STATUS HANDLING ---

    # SCENARIO 1: SUCCESS
    if event_type == 'Succeeded' or status == 'Completed':
        # Extract ID details for reconciliation
        order_id = inner_data.get('Memo')  # Order ID stored in Memo
        amount = inner_data.get('Amount')
        transaction_id = inner_data.get('Id')  # External Zum Rails ID

        if order_id:
            print(f"✅ Payment Succeeded for Order #{order_id}. Updating Shopify...")
            mark_shopify_order_paid(order_id, amount, transaction_id)
        else:
            print("⚠️ Payment completed, but Order ID (Memo) was missing.")

    # SCENARIO 2: FAILURE
    elif event_type == 'Failed' or status in ['Failed', 'Rejected', 'Error']:
        # Extract the specific failure reason
        reason = inner_data.get('FailedTransactionEvent') or "Unknown Error"
        order_id = inner_data.get('Memo')
        amount = inner_data.get('Amount')

        print(f"❌ Payment FAILED for Order #{order_id}")
        print(f"   Reason: {reason}")

        if order_id:
            # Update the order tags/notes so the merchant sees the error
            mark_shopify_order_failed(order_id, amount, reason)

    # SCENARIO 3: OTHER STATES
    else:
        print(f"ℹ️  Transaction is in state: {status} (Ignored)")

    return jsonify({"message": "Received"}), 200


def mark_shopify_order_paid(order_id, amount, transaction_id):
    """
    Updates Shopify Order to 'Paid'.
    CRITICAL: Adds the Zum Rails 'transaction_id' to the invoice for reconciliation.
    """
    url = f"https://{SHOPIFY_DOMAIN}/admin/api/2024-01/orders/{order_id}/transactions.json"

    headers = {
        "X-Shopify-Access-Token": SHOPIFY_ACCESS_TOKEN,
        "Content-Type": "application/json"
    }

    payload = {
        "transaction": {
            "kind": "capture",  # 'Capture' finalizes the payment
            "status": "success",
            "amount": amount,
            "gateway": "interac-manual",

            # ✅ RECONCILIATION ID:
            # This saves the Zum Rails ID onto the Shopify Order Timeline
            "authorization": transaction_id
        }
    }

    try:
        response = requests.post(url, json=payload, headers=headers)
        if response.status_code == 201:
            print(f"🎉 SUCCESS! Order #{order_id} Paid. Ref: {transaction_id}")
        else:
            print(f"❌ Shopify Update Failed: {response.text}")
    except Exception as e:
        print(f"❌ Connection Error: {e}")


def mark_shopify_order_failed(order_id, amount, reason):
    """
    Handles Failed Payments.
    Since we cannot easily 'fail' a pending order via transaction API,
    we use a 'Tag & Note' strategy to alert the merchant.
    """
    url = f"https://{SHOPIFY_DOMAIN}/admin/api/2024-01/orders/{order_id}.json"

    headers = {
        "X-Shopify-Access-Token": SHOPIFY_ACCESS_TOKEN,
        "Content-Type": "application/json"
    }

    # 1. Fetch current tags (to avoid overwriting existing ones)
    try:
        get_response = requests.get(url, headers=headers)
        order_data = get_response.json().get('order', {})
        current_tags = order_data.get('tags', "")
    except:
        current_tags = ""

    # 2. Add "Payment Failed" tags
    new_tags = f"{current_tags}, Payment Failed, Interac Failed"

    # 3. Construct Update Payload
    payload = {
        "order": {
            "id": order_id,
            "tags": new_tags,
            "note": f"⚠️ PAYMENT FAILED \nReason: {reason} \nAmount: {amount}",
        }
    }

    try:
        # Update Order
        response = requests.put(url, json=payload, headers=headers)

        if response.status_code == 200:
            print(f"✅ Shopify Updated: Order #{order_id} tagged as FAILED.")
            # 4. Optional: Void the pending transaction to clean up
            void_transaction(order_id)
        else:
            print(f"❌ Shopify Update Failed: {response.text}")

    except Exception as e:
        print(f"❌ Connection Error: {e}")


def void_transaction(order_id):
    """Helper to void a pending transaction on Shopify."""
    url = f"https://{SHOPIFY_DOMAIN}/admin/api/2024-01/orders/{order_id}/transactions.json"
    headers = {"X-Shopify-Access-Token": SHOPIFY_ACCESS_TOKEN, "Content-Type": "application/json"}

    payload = {"transaction": {"kind": "void"}}
    requests.post(url, json=payload, headers=headers)


def process_zum_transaction(order_id, amount, email, shop_domain=None, first_name="", last_name=""):
    """
    Interacts with Zum Rails API to send the payment request.
    1. Authenticates (Gets Token).
    2. Sends Interac Request.
    3. Returns Success/Error HTML.
    """
    print(f"🚀 Sending Request to: {email} for ${amount}")

    short_memo = str(order_id)[-15:]  # Truncate Memo if too long
    # Use real name if available; fall back to email-based extraction
    zum_first = first_name if first_name else email.split('@')[0]
    zum_last  = last_name  if last_name  else "Shopify"

    try:
        # A. AUTHENTICATION
        auth_response = requests.post(f"{ZUM_API_URL}/authorize", json={
            "Username": ZUM_USERNAME,
            "Password": ZUM_PASSWORD
        })

        if auth_response.status_code != 200:
            return f"<h3>Auth Error</h3><p>{auth_response.text}</p>"

        token = auth_response.json().get('result', {}).get('Token')

        # B. SEND TRANSACTION
        headers = {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}

        payload = {
            "ZumRailsType": "AccountsReceivable",  # Incoming Money
            "TransactionMethod": "Interac",
            "Amount": float(amount),
            "Memo": short_memo,
            "Comment": f"Shopify Order #{order_id} | Store: {shop_domain}",
            "InteracNotificationChannel": "email",
            "WalletId": ZUM_WALLET_ID,  # Required Target Wallet
            "User": {
                "FirstName": zum_first,
                "LastName": zum_last,
                "Email": email

            }
        }

        response = requests.post(f"{ZUM_API_URL}/transaction", json=payload, headers=headers)
        result = response.json()

        print("DEBUG RESPONSE:", result)

        if response.status_code == 200 and not result.get('IsError'):
            interac_url = result.get('result', {}).get('InteracUrl')

            if interac_url:
                return redirect(interac_url)

            # Fallback (if URL missing)
            return f"""
            <div style="font-family: sans-serif; text-align: center; padding: 50px;">
                <h1 style="color: #28a745;">✓ Request Sent!</h1>
                <p>We sent an email to <b>{email}</b>.</p>
                <p>Please check your inbox to pay <b>${amount}</b>.</p>
            </div>
            """
        else:
            error_msg = result.get('responseException', {}).get('exceptionMessage') or str(
                result.get('errors') or result.get('Message'))
            return f"<h3>Transaction Failed: {error_msg}</h3>"

    except Exception as e:
        return f"<h3>Server Error: {str(e)}</h3>"


# --- DASHBOARD & ADMIN ROUTES ---

from flask import session, url_for

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        password = request.form.get('password')
        if password == ADMIN_PASSWORD:
            session['logged_in'] = True
            return redirect(url_for('dashboard'))
        return "<h3>Invalid Password!</h3><a href='/login'>Try again</a>"
    
    return """
    <div style="font-family: 'Inter', sans-serif; max-width: 400px; margin: 100px auto; padding: 40px; border-radius: 12px; background: #1a1a1a; color: white; box-shadow: 0 10px 30px rgba(0,0,0,0.5);">
        <h2 style="text-align: center; margin-bottom: 30px;">FintechWerx Admin</h2>
        <form method="POST">
            <label style="display:block; margin-bottom: 10px; color: #aaa;">Enter Admin Password:</label>
            <input type="password" name="password" required autofocus
                   style="width: 100%; padding: 12px; margin-bottom: 20px; border-radius: 6px; border: 1px solid #333; background: #2a2a2a; color: white;">
            <button type="submit" 
                    style="width: 100%; padding: 12px; border: none; border-radius: 6px; background: #FFD100; color: black; font-weight: bold; cursor: pointer;">
                Login to Dashboard
            </button>
        </form>
    </div>
    """

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

@app.route('/dashboard', methods=['GET'])
def dashboard():
    if not session.get('logged_in'):
        return redirect(url_for('login'))
    
    try:
        conn = get_db_connection()
        cursor = conn.cursor(dictionary=True)
        cursor.execute("SELECT * FROM domains ORDER BY created_at DESC")
        domains = cursor.fetchall()
        cursor.close()
        conn.close()
    except Exception as e:
        return f"<h3>Database Connection Error</h3><p>{e}</p>"

    rows_html = ""
    for d in domains:
        status_color = "#28a745" if d['status'] == 'active' else "#dc3545"
        rows_html += f"""
        <tr style="border-bottom: 1px solid #333;">
            <td style="padding: 15px;">{d['domain']}</td>
            <td style="padding: 15px;">
                <span style="background: {status_color}; padding: 4px 10px; border-radius: 20px; font-size: 12px; font-weight: bold;">
                    {d['status'].upper()}
                </span>
            </td>
            <td style="padding: 15px;">{d['created_at']}</td>
            <td style="padding: 15px;">
                <form action="/dashboard/toggle" method="POST" style="display:inline;">
                    <input type="hidden" name="id" value="{d['id']}">
                    <button type="submit" style="background:#444; color:white; border:none; padding: 5px 10px; border-radius:4px; cursor:pointer;">Toggle Status</button>
                </form>
                <form action="/dashboard/delete" method="POST" style="display:inline; margin-left: 10px;">
                    <input type="hidden" name="id" value="{d['id']}">
                    <button type="submit" style="background:#dc3545; color:white; border:none; padding: 5px 10px; border-radius:4px; cursor:pointer;" onclick="return confirm('Are you sure?')">Delete</button>
                </form>
            </td>
        </tr>
        """

    return f"""
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>FintechWerx Dashboard</title>
        <style>
            body {{ font-family: 'Inter', sans-serif; background: #0f0f0f; color: #eee; margin: 0; padding: 40px; }}
            .container {{ max-width: 1000px; margin: 0 auto; }}
            .card {{ background: #1a1a1a; padding: 30px; border-radius: 12px; box-shadow: 0 4px 20px rgba(0,0,0,0.5); }}
            h1 {{ margin-top: 0; display: flex; justify-content: space-between; align-items: center; }}
            table {{ width: 100%; border-collapse: collapse; margin-top: 20px; }}
            th {{ text-align: left; padding: 15px; background: #222; }}
            .add-form {{ margin-bottom: 30px; background: #222; padding: 20px; border-radius: 8px; }}
            input {{ padding: 10px; border-radius: 4px; border: 1px solid #333; background: #333; color: white; width: 300px; }}
            .btn-add {{ padding: 10px 20px; background: #FFD100; border: none; border-radius: 4px; font-weight: bold; cursor: pointer; }}
            .logout {{ font-size: 14px; text-decoration: none; color: #aaa; }}
        </style>
    </head>
    <body>
        <div class="container">
            <h1>
                FintechWerx Domain Management
                <a href="/logout" class="logout">Logout</a>
            </h1>
            
            <div class="card">
                <div class="add-form">
                    <form action="/dashboard/add" method="POST">
                        <input type="text" name="domain" placeholder="example-store.myshopify.com" required>
                        <button type="submit" class="btn-add">Add Domain</button>
                    </form>
                </div>
                
                <table>
                    <thead>
                        <tr>
                            <th>Store Domain</th>
                            <th>Status</th>
                            <th>Added On</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        {rows_html}
                    </tbody>
                </table>
            </div>
        </div>
    </body>
    </html>
    """

@app.route('/dashboard/add', methods=['POST'])
def dashboard_add():
    if not session.get('logged_in'): return redirect(url_for('login'))
    domain = request.form.get('domain').strip()
    if domain:
        try:
            conn = get_db_connection()
            cursor = conn.cursor()
            cursor.execute("INSERT INTO domains (domain, status) VALUES (%s, 'active')", (domain,))
            conn.commit()
            cursor.close()
            conn.close()
        except: pass
    return redirect(url_for('dashboard'))

@app.route('/dashboard/toggle', methods=['POST'])
def dashboard_toggle():
    if not session.get('logged_in'): return redirect(url_for('login'))
    domain_id = request.form.get('id')
    try:
        conn = get_db_connection()
        cursor = conn.cursor(dictionary=True)
        cursor.execute("SELECT status FROM domains WHERE id = %s", (domain_id,))
        row = cursor.fetchone()
        new_status = 'inactive' if row['status'] == 'active' else 'active'
        cursor.execute("UPDATE domains SET status = %s WHERE id = %s", (new_status, domain_id))
        conn.commit()
        cursor.close()
        conn.close()
    except: pass
    return redirect(url_for('dashboard'))

@app.route('/dashboard/delete', methods=['POST'])
def dashboard_delete():
    if not session.get('logged_in'): return redirect(url_for('login'))
    domain_id = request.form.get('id')
    try:
        conn = get_db_connection()
        cursor = conn.cursor()
        cursor.execute("DELETE FROM domains WHERE id = %s", (domain_id,))
        conn.commit()
        cursor.close()
        conn.close()
    except: pass
    return redirect(url_for('dashboard'))


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8080)