Upgrade and revise: import os
import json
import tkinter as tk
from tkinter import ttk, filedialog, messagebox
from jinja2 import Template

# Define template contents for various files
BOT_PY_TEMPLATE = Template("""
import logging
from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import (
    Updater,
    CommandHandler,
    MessageHandler,
    Filters,
    CallbackContext,
    CallbackQueryHandler
)
from database import Session, User, Product, Cart, Order
from scraper import scrape_yaga_store
from payments import create_payfast_payment, create_yoco_payment
import json
import requests
import threading
import time

# Configure logging
logging.basicConfig(
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    level=logging.INFO
)
logger = logging.getLogger(__name__)

# Initialize Rasa endpoint
RASA_ENDPOINT = '{{ rasa_endpoint }}'

def start(update: Update, context: CallbackContext):
    user = update.message.from_user
    session_db = Session()
    db_user = session_db.query(User).filter_by(telegram_id=str(user.id)).first()
    if not db_user:
        db_user = User(telegram_id=str(user.id))
        session_db.add(db_user)
        session_db.commit()
    session_db.close()
    update.message.reply_text(
        "Welcome to our store! How can I assist you today? Type /help to see available commands."
    )

def help_command(update: Update, context: CallbackContext):
    help_text = (
        "/start - Start interacting with the bot\n"
        "/products - View available products\n"
        "/cart - View your cart\n"
        "/checkout - Proceed to checkout\n"
        "/help - Show this help message"
    )
    update.message.reply_text(help_text)

def products(update: Update, context: CallbackContext):
    session_db = Session()
    products = session_db.query(Product).all()
    session_db.close()
    for product in products:
        keyboard = [
            [InlineKeyboardButton("Add to Cart", callback_data=f"add_{{{{ product.id }}}}")]
        ]
        reply_markup = InlineKeyboardMarkup(keyboard)
        update.message.reply_photo(
            photo=product.image_url,
            caption=f"*{{{{ product.name }}}}*\n{{{{ product.description }}}}\nPrice: R{{{{ product.price }}}}",
            parse_mode='Markdown',
            reply_markup=reply_markup
        )

def button(update: Update, context: CallbackContext):
    query = update.callback_query
    query.answer()
    data = query.data
    user = query.from_user
    session_db = Session()
    db_user = session_db.query(User).filter_by(telegram_id=str(user.id)).first()
    cart = session_db.query(Cart).filter_by(user_id=db_user.id).first()
    if not cart:
        cart = Cart(user_id=db_user.id, items=json.dumps({}))
        session_db.add(cart)
    cart_items = json.loads(cart.items)
    
    if data.startswith("add_"):
        product_id = int(data.split("_")[1])
        cart_items[str(product_id)] = cart_items.get(str(product_id), 0) + 1
        query.edit_message_text(text="Item added to your cart.")
    elif data.startswith("remove_"):
        product_id = int(data.split("_")[1])
        if str(product_id) in cart_items:
            del cart_items[str(product_id)]
            query.edit_message_text(text="Item removed from your cart.")
    elif data == "checkout":
        if not cart_items:
            query.edit_message_text(text="Your cart is empty.")
            session_db.close()
            return
        total = 0
        item_description = ""
        for pid, qty in cart_items.items():
            product = session_db.query(Product).filter_by(id=int(pid)).first()
            if product:
                total += product.price * qty
                item_description += f"{product.name} x{qty}, "
        payment_link = ""
        order = Order(
            user_id=db_user.id,
            items=json.dumps(cart_items),
            total=total,
            payment_status=False
        )
        session_db.add(order)
        session_db.commit()
        if "{{ payment_gateway }}" == "PayFast":
            payment_link = create_payfast_payment(order_id=str(order.id), amount=total, item_description=item_description)
        elif "{{ payment_gateway }}" == "Yoco":
            payment_link = create_yoco_payment(order_id=str(order.id), amount=total, item_description=item_description)
        query.edit_message_text(text=f"Please complete your payment here: {payment_link}")
    cart.items = json.dumps(cart_items)
    session_db.commit()
    session_db.close()

def view_cart(update: Update, context: CallbackContext):
    user = update.message.from_user
    session_db = Session()
    db_user = session_db.query(User).filter_by(telegram_id=str(user.id)).first()
    cart = session_db.query(Cart).filter_by(user_id=db_user.id).first()
    if not cart or not cart.items:
        update.message.reply_text("Your cart is empty.")
        session_db.close()
        return
    cart_items = json.loads(cart.items)
    message = "Your Cart:\n"
    total = 0
    for product_id, quantity in cart_items.items():
        product = session_db.query(Product).filter_by(id=int(product_id)).first()
        if product:
            message += f"{product.name} x{quantity} - R{product.price * quantity}\n"
            total += product.price * quantity
    message += f"\nTotal: R{total}"
    keyboard = [
        [InlineKeyboardButton("Checkout", callback_data="checkout")]
    ]
    reply_markup = InlineKeyboardMarkup(keyboard)
    update.message.reply_text(message, reply_markup=reply_markup)
    session_db.close()

def checkout(update: Update, context: CallbackContext):
    query = update.callback_query
    query.answer()
    user = query.from_user
    session_db = Session()
    db_user = session_db.query(User).filter_by(telegram_id=str(user.id)).first()
    cart = session_db.query(Cart).filter_by(user_id=db_user.id).first()
    if not cart or not cart.items:
        query.edit_message_text(text="Your cart is empty.")
        session_db.close()
        return
    cart_items = json.loads(cart.items)
    total = 0
    item_description = ""
    for product_id, quantity in cart_items.items():
        product = session_db.query(Product).filter_by(id=int(product_id)).first()
        if product:
            total += product.price * quantity
            item_description += f"{product.name} x{quantity}, "
    payment_link = ""
    order = Order(
        user_id=db_user.id,
        items=json.dumps(cart_items),
        total=total,
        payment_status=False
    )
    session_db.add(order)
    session_db.commit()
    if "{{ payment_gateway }}" == "PayFast":
        payment_link = create_payfast_payment(order_id=str(order.id), amount=total, item_description=item_description)
    elif "{{ payment_gateway }}" == "Yoco":
        payment_link = create_yoco_payment(order_id=str(order.id), amount=total, item_description=item_description)
    query.edit_message_text(text=f"Please complete your payment here: {payment_link}")
    session_db.close()

def handle_message(update: Update, context: CallbackContext):
    user_message = update.message.text
    # Send message to Rasa for NLP processing
    response = requests.post(RASA_ENDPOINT, json={"message": user_message})
    if response.status_code == 200:
        data = response.json()
        if data:
            bot_reply = data[0].get('text', "I'm not sure how to respond to that.")
            update.message.reply_text(bot_reply)
        else:
            update.message.reply_text("I'm not sure how to respond to that.")
    else:
        update.message.reply_text("Sorry, I'm having trouble understanding you right now.")

def broadcast_promotion(context: CallbackContext):
    session_db = Session()
    users = session_db.query(User).all()
    for user in users:
        try:
            context.bot.send_message(chat_id=user.telegram_id, text="Check out our latest discounts!")
        except Exception as e:
            logger.error(f"Error sending message to {user.telegram_id}: {{e}}")
    session_db.close()

def main():
    # Replace '{{ telegram_token }}' with your actual token
    updater = Updater("{{ telegram_token }}", use_context=True)
    dispatcher = updater.dispatcher

    # Handlers
    dispatcher.add_handler(CommandHandler("start", start))
    dispatcher.add_handler(CommandHandler("help", help_command))
    dispatcher.add_handler(CommandHandler("products", products))
    dispatcher.add_handler(CommandHandler("cart", view_cart))
    dispatcher.add_handler(CallbackQueryHandler(button))
    dispatcher.add_handler(MessageHandler(Filters.text & ~Filters.command, handle_message))

    # Start the Bot
    updater.start_polling()

    # Start scraping periodically (e.g., every 6 hours)
    def periodic_scrape():
        while True:
            scrape_yaga_store()
            time.sleep(6 * 60 * 60)  # 6 hours

    scrape_thread = threading.Thread(target=periodic_scrape, daemon=True)
    scrape_thread.start()

    # Schedule a daily promotion at 9 AM
    from datetime import time as dt_time
    job_queue = updater.job_queue
    job_queue.run_daily(
        broadcast_promotion,
        time=dt_time(hour=9, minute=0, second=0)
    )

    updater.idle()

if __name__ == '__main__':
    main()
""")

DATABASE_PY_TEMPLATE = Template("""
from sqlalchemy import create_engine, Column, Integer, String, Float, Boolean, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, relationship

Base = declarative_base()

class Product(Base):
    __tablename__ = 'products'
    id = Column(Integer, primary_key=True)
    name = Column(String)
    description = Column(String)
    price = Column(Float)
    stock = Column(Integer)
    image_url = Column(String)

class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    telegram_id = Column(String, unique=True)
    cart = relationship("Cart", back_populates="user")

class Cart(Base):
    __tablename__ = 'carts'
    id = Column(Integer, primary_key=True)
    user_id = Column(Integer, ForeignKey('users.id'))
    items = Column(String)  # JSON string of product IDs and quantities
    user = relationship("User", back_populates="cart")

class Order(Base):
    __tablename__ = 'orders'
    id = Column(Integer, primary_key=True)
    user_id = Column(Integer, ForeignKey('users.id'))
    items = Column(String)  # JSON string
    total = Column(Float)
    payment_status = Column(Boolean, default=False)

engine = create_engine('sqlite:///telegram_bot.db')
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
""")

SCRAPER_PY_TEMPLATE = Template("""
import requests
from bs4 import BeautifulSoup
from database import Session, Product
import logging

logger = logging.getLogger(__name__)

def scrape_yaga_store():
    session = Session()
    url = '{{ yaga_store_url }}'  # Replace with your Yaga store URL
    try:
        response = requests.get(url)
        response.raise_for_status()
        soup = BeautifulSoup(response.text, 'html.parser')

        # Example scraping logic - adjust selectors based on your store's HTML structure
        products = soup.find_all('div', class_='product-item')
        for prod in products:
            name = prod.find('h2').text.strip()
            description = prod.find('p', class_='description').text.strip()
            price = float(prod.find('span', class_='price').text.strip().replace('$', ''))
            stock = int(prod.find('span', class_='stock').text.strip())
            image_url = prod.find('img')['src']

            existing_product = session.query(Product).filter_by(name=name).first()
            if not existing_product:
                product = Product(
                    name=name,
                    description=description,
                    price=price,
                    stock=stock,
                    image_url=image_url
                )
                session.add(product)
        session.commit()
    except Exception as e:
        logger.error(f"Error scraping Yaga store: {{e}}")
    finally:
        session.close()

if __name__ == "__main__":
    scrape_yaga_store()
""")

PAYMENTS_PY_TEMPLATE = Template("""
import requests

{% if payment_gateway == 'PayFast' %}
PAYFAST_MERCHANT_ID = '{{ payfast_merchant_id }}'
PAYFAST_RETURN_URL = '{{ payfast_return_url }}'
PAYFAST_NOTIFY_URL = '{{ payfast_notify_url }}'
PAYFAST_CANCEL_URL = '{{ payfast_cancel_url }}'
PAYFAST_SECRET_KEY = '{{ payfast_secret_key }}'  # Needed for validating notifications

def create_payfast_payment(order_id, amount, item_description):
    data = {{
        'merchant_id': PAYFAST_MERCHANT_ID,
        'return_url': PAYFAST_RETURN_URL,
        'cancel_url': PAYFAST_CANCEL_URL,
        'notify_url': PAYFAST_NOTIFY_URL,
        'm_payment_id': order_id,
        'amount': amount,
        'item_name': item_description,
        'currency': 'ZAR'
    }}
    payment_url = 'https://www.payfast.co.za/eng/process?' + '&'.join([f"{{k}}={{v}}" for k, v in data.items()])
    return payment_url

def validate_payfast_notification(params):
    # Implement validation logic based on PayFast's documentation
    pass

{% elif payment_gateway == 'Yoco' %}
YOCO_API_KEY = '{{ yoco_api_key }}'
YOCO_RETURN_URL = '{{ yoco_return_url }}'

def create_yoco_payment(order_id, amount, item_description):
    # Implement Yoco payment link creation
    payment_link = f"https://checkout.yoco.com/pay?client_id={{ YOCO_API_KEY }}&order_id={{ order_id }}&amount={{ amount }}&description={{ item_description }}"
    return payment_link

def validate_yoco_notification(params):
    # Implement validation logic based on Yoco's documentation
    pass

{% endif %}
""")

REQUIREMENTS_TXT = """
python-telegram-bot==13.14
beautifulsoup4
requests
sqlalchemy
jinja2
"""

PROCFILE_TEMPLATE = Template("""
worker: python bot.py
""")

BUILD_SCRIPT_TEMPLATE = Template("""
#!/bin/bash

# Install dependencies
pip install -r requirements.txt

# Run Rasa server (assuming Rasa is installed)
rasa run --enable-api --model models/
""")

README_TEMPLATE = Template("""
# Telegram Store Bot

This Telegram bot allows you to sell products, handle customer inquiries, process payments, and execute marketing strategies directly within Telegram.

## Features

- Product Listings
- Cart Management
- Payment Integration (PayFast/Yoco)
- Customer Inquiries with NLP
- Marketing Automation

## Setup Instructions

1. **Install Dependencies**

    ```bash
    pip install -r requirements.txt
    ```

2. **Run the Bot**

    ```bash
    python bot.py
    ```

3. **Run Rasa Server**

    Ensure Rasa is installed and run:

    ```bash
    rasa run --enable-api --model models/
    ```

## Deployment

For deploying the bot to Heroku or any other cloud service, follow the respective platform's deployment guide.

## License

MIT License
""")

# Function to create directories and files
def create_project(project_path, config):
    try:
        # Create project directory
        os.makedirs(project_path, exist_ok=True)
        
        # Create subdirectories
        subdirs = ['nlp']
        for subdir in subdirs:
            os.makedirs(os.path.join(project_path, subdir), exist_ok=True)
        
        # Create bot.py
        with open(os.path.join(project_path, 'bot.py'), 'w') as f:
            f.write(BOT_PY_TEMPLATE.render(
                telegram_token=config['telegram_token'],
                payment_gateway=config['payment_gateway'],
                rasa_endpoint=config['rasa_endpoint']
            ))
        
        # Create database.py
        with open(os.path.join(project_path, 'database.py'), 'w') as f:
            f.write(DATABASE_PY_TEMPLATE.render())
        
        # Create scraper.py
        with open(os.path.join(project_path, 'scraper.py'), 'w') as f:
            f.write(SCRAPER_PY_TEMPLATE.render(
                yaga_store_url=config['yaga_store_url']
            ))
        
        # Create payments.py
        with open(os.path.join(project_path, 'payments.py'), 'w') as f:
            f.write(PAYMENTS_PY_TEMPLATE.render(
                payment_gateway=config['payment_gateway'],
                payfast_merchant_id=config.get('payfast_merchant_id', ''),
                payfast_return_url=config.get('payfast_return_url', ''),
                payfast_notify_url=config.get('payfast_notify_url', ''),
                payfast_cancel_url=config.get('payfast_cancel_url', ''),
                payfast_secret_key=config.get('payfast_secret_key', ''),
                yoco_api_key=config.get('yoco_api_key', ''),
                yoco_return_url=config.get('yoco_return_url', '')
            ))
        
        # Create requirements.txt
        with open(os.path.join(project_path, 'requirements.txt'), 'w') as f:
            f.write(REQUIREMENTS_TXT)
        
        # Create Procfile
        with open(os.path.join(project_path, 'Procfile'), 'w') as f:
            f.write(PROCFILE_TEMPLATE.render())
        
        # Create build.sh
        with open(os.path.join(project_path, 'build.sh'), 'w') as f:
            f.write(BUILD_SCRIPT_TEMPLATE.render())
        
        # Create README.md
        with open(os.path.join(project_path, 'README.md'), 'w') as f:
            f.write(README_TEMPLATE.render())
        
        # Create nlp configuration files (if necessary)
        nlp_dir = os.path.join(project_path, 'nlp')
        if not os.path.exists(os.path.join(nlp_dir, 'config.yml')):
            with open(os.path.join(nlp_dir, 'config.yml'), 'w') as f:
                f.write("")  # Placeholder
        if not os.path.exists(os.path.join(nlp_dir, 'domain.yml')):
            with open(os.path.join(nlp_dir, 'domain.yml'), 'w') as f:
                f.write("")  # Placeholder
        if not os.path.exists(os.path.join(nlp_dir, 'nlu.yml')):
            with open(os.path.join(nlp_dir, 'nlu.yml'), 'w') as f:
                f.write("")  # Placeholder
        if not os.path.exists(os.path.join(nlp_dir, 'stories.yml')):
            with open(os.path.join(nlp_dir, 'stories.yml'), 'w') as f:
                f.write("")  # Placeholder
        
        return True, "Project created successfully."
    except Exception as e:
        return False, str(e)

# GUI Setup
class SetupGUI:
    def __init__(self, root):
        self.root = root
        self.root.title("Telegram Bot Setup Wizard")
        self.root.geometry("600x700")
        
        # Create a notebook
        self.notebook = ttk.Notebook(self.root)
        self.notebook.pack(pady=10, expand=True)
        
        # Tabs
        self.tab_credentials = ttk.Frame(self.notebook)
        self.tab_payment = ttk.Frame(self.notebook)
        self.tab_misc = ttk.Frame(self.notebook)
        
        self.notebook.add(self.tab_credentials, text="Bot & Store Credentials")
        self.notebook.add(self.tab_payment, text="Payment Gateway")
        self.notebook.add(self.tab_misc, text="Miscellaneous")
        
        # ------- Tab 1: Bot & Store Credentials -------
        self.create_tab_credentials()

        # ------- Tab 2: Payment Gateway -------
        self.create_tab_payment()

        # ------- Tab 3: Miscellaneous -------
        self.create_tab_misc()

        # ------- Submit Button -------
        self.submit_button = ttk.Button(self.root, text="Generate Project", command=self.generate_project)
        self.submit_button.pack(pady=20)

    def create_tab_credentials(self):
        frame = self.tab_credentials

        # Telegram Bot Token
        ttk.Label(frame, text="Telegram Bot Token:").pack(pady=5, anchor='w', padx=10)
        self.telegram_token_entry = ttk.Entry(frame, width=50)
        self.telegram_token_entry.pack(pady=5, padx=10)

        # Yaga Store URL
        ttk.Label(frame, text="Yaga Store URL:").pack(pady=5, anchor='w', padx=10)
        self.yaga_store_url_entry = ttk.Entry(frame, width=50)
        self.yaga_store_url_entry.pack(pady=5, padx=10)

        # Rasa Endpoint
        ttk.Label(frame, text="Rasa Endpoint (e.g., http://localhost:5005/webhooks/rest/webhook):").pack(pady=5, anchor='w', padx=10)
        self.rasa_endpoint_entry = ttk.Entry(frame, width=50)
        self.rasa_endpoint_entry.pack(pady=5, padx=10)

    def create_tab_payment(self):
        frame = self.tab_payment

        # Payment Gateway Selection
        ttk.Label(frame, text="Select Payment Gateway:").pack(pady=5, anchor='w', padx=10)
        self.payment_gateway = tk.StringVar()
        self.payment_gateway.set("PayFast")
        gateways = ["PayFast", "Yoco"]
        self.gateway_dropdown = ttk.OptionMenu(frame, self.payment_gateway, gateways[0], *gateways, command=self.toggle_payment_fields)
        self.gateway_dropdown.pack(pady=5, padx=10)

        # PayFast Fields
        self.payfast_frame = ttk.LabelFrame(frame, text="PayFast Configuration")
        self.payfast_frame.pack(pady=10, padx=10, fill="x")

        ttk.Label(self.payfast_frame, text="Merchant ID:").pack(pady=5, anchor='w', padx=10)
        self.payfast_merchant_id_entry = ttk.Entry(self.payfast_frame, width=50)
        self.payfast_merchant_id_entry.pack(pady=5, padx=10)

        ttk.Label(self.payfast_frame, text="Return URL:").pack(pady=5, anchor='w', padx=10)
        self.payfast_return_url_entry = ttk.Entry(self.payfast_frame, width=50)
        self.payfast_return_url_entry.pack(pady=5, padx=10)

        ttk.Label(self.payfast_frame, text="Notify URL:").pack(pady=5, anchor='w', padx=10)
        self.payfast_notify_url_entry = ttk.Entry(self.payfast_frame, width=50)
        self.payfast_notify_url_entry.pack(pady=5, padx=10)

        ttk.Label(self.payfast_frame, text="Cancel URL:").pack(pady=5, anchor='w', padx=10)
        self.payfast_cancel_url_entry = ttk.Entry(self.payfast_frame, width=50)
        self.payfast_cancel_url_entry.pack(pady=5, padx=10)

        ttk.Label(self.payfast_frame, text="Secret Key:").pack(pady=5, anchor='w', padx=10)
        self.payfast_secret_key_entry = ttk.Entry(self.payfast_frame, width=50, show="*")
        self.payfast_secret_key_entry.pack(pady=5, padx=10)

        # Yoco Fields
        self.yoco_frame = ttk.LabelFrame(frame, text="Yoco Configuration")
        # Initially hidden
        self.yoco_frame.pack(pady=10, padx=10, fill="x")
        self.yoco_frame.pack_forget()

        ttk.Label(self.yoco_frame, text="API Key:").pack(pady=5, anchor='w', padx=10)
        self.yoco_api_key_entry = ttk.Entry(self.yoco_frame, width=50)
        self.yoco_api_key_entry.pack(pady=5, padx=10)

        ttk.Label(self.yoco_frame, text="Return URL:").pack(pady=5, anchor='w', padx=10)
        self.yoco_return_url_entry = ttk.Entry(self.yoco_frame, width=50)
        self.yoco_return_url_entry.pack(pady=5, padx=10)

    def toggle_payment_fields(self, selected_gateway):
        if selected_gateway == "PayFast":
            self.yoco_frame.pack_forget()
            self.payfast_frame.pack(pady=10, padx=10, fill="x")
        elif selected_gateway == "Yoco":
            self.payfast_frame.pack_forget()
            self.yoco_frame.pack(pady=10, padx=10, fill="x")

    def create_tab_misc(self):
        frame = self.tab_misc

        # Project Name
        ttk.Label(frame, text="Project Name:").pack(pady=5, anchor='w', padx=10)
        self.project_name_entry = ttk.Entry(frame, width=50)
        self.project_name_entry.pack(pady=5, padx=10)
        self.project_name_entry.insert(0, "telegram_bot")

        # Project Directory
        ttk.Label(frame, text="Project Directory:").pack(pady=5, anchor='w', padx=10)
        self.project_dir_entry = ttk.Entry(frame, width=50)
        self.project_dir_entry.pack(pady=5, padx=10)
        self.project_dir_entry.insert(0, os.path.join(os.getcwd(), "telegram_bot"))

        browse_button = ttk.Button(frame, text="Browse", command=self.browse_directory)
        browse_button.pack(pady=5, padx=10)

    def browse_directory(self):
        directory = filedialog.askdirectory()
        if directory:
            self.project_dir_entry.delete(0, tk.END)
            self.project_dir_entry.insert(0, directory)

    def generate_project(self):
        # Collect all inputs
        telegram_token = self.telegram_token_entry.get().strip()
        yaga_store_url = self.yaga_store_url_entry.get().strip()
        rasa_endpoint = self.rasa_endpoint_entry.get().strip()
        payment_gateway = self.payment_gateway.get()
        project_name = self.project_name_entry.get().strip()
        project_dir = self.project_dir_entry.get().strip()

        if not telegram_token or not yaga_store_url or not rasa_endpoint or not project_name or not project_dir:
            messagebox.showerror("Error", "Please fill in all required fields.")
            return

        config = {
            'telegram_token': telegram_token,
            'yaga_store_url': yaga_store_url,
            'rasa_endpoint': rasa_endpoint,
            'payment_gateway': payment_gateway,
            'payfast_merchant_id': self.payfast_merchant_id_entry.get().strip(),
            'payfast_return_url': self.payfast_return_url_entry.get().strip(),
            'payfast_notify_url': self.payfast_notify_url_entry.get().strip(),
            'payfast_cancel_url': self.payfast_cancel_url_entry.get().strip(),
            'payfast_secret_key': self.payfast_secret_key_entry.get().strip(),
            'yoco_api_key': self.yoco_api_key_entry.get().strip(),
            'yoco_return_url': self.yoco_return_url_entry.get().strip()
        }

        # Validate payment fields based on gateway
        if payment_gateway == "PayFast":
            required_payfast = ['payfast_merchant_id', 'payfast_return_url', 'payfast_notify_url', 'payfast_cancel_url', 'payfast_secret_key']
            for field in required_payfast:
                if not config[field]:
                    messagebox.showerror("Error", f"Please fill in the PayFast field: {field.replace('_', ' ').title()}")
                    return
        elif payment_gateway == "Yoco":
            required_yoco = ['yoco_api_key', 'yoco_return_url']
            for field in required_yoco:
                if not config[field]:
                    messagebox.showerror("Error", f"Please fill in the Yoco field: {field.replace('_', ' ').title()}")
                    return

        # Confirm project creation
        confirm = messagebox.askyesno("Confirm", f"Create project '{project_name}' at:\n{project_dir}?")
        if not confirm:
            return

        # Create project
        success, message = create_project(project_dir, config)
        if success:
            messagebox.showinfo("Success", message)
            # Optionally, open the project directory
            if messagebox.askyesno("Open Directory", "Do you want to open the project directory?"):
                os.startfile(project_dir) if os.name == 'nt' else os.system(f'open "{project_dir}"')
        else:
            messagebox.showerror("Error", f"Failed to create project:\n{message}")

# Main execution
if __name__ == "__main__":
    # Ensure Jinja2 is installed
    try:
        import jinja2
    except ImportError:
        print("Jinja2 is not installed. Installing now...")
        os.system("pip install jinja2")

    root = tk.Tk()
    app = SetupGUI(root)
    root.mainloop()