import razorpay
from django.conf import settings
from setting.models import SiteSetting
import base64

def get_setting_value(key):
    """Fetch and decode a setting value from SiteSetting model."""
    try:
        setting = SiteSetting.objects.get(key=key)
        return base64.b64decode(setting.value.encode()).decode()
    except SiteSetting.DoesNotExist:
        return ""

# =========================
# Initialize Razorpay Client
# =========================
RAZORPAY_KEY_ID = get_setting_value("RAZORPAY_KEY_ID")
RAZORPAY_SECRET = get_setting_value("RAZORPAY_SECRET")

client = razorpay.Client(auth=(RAZORPAY_KEY_ID, RAZORPAY_SECRET))

def get_pending_orders():
    """
    Fetches the pending orders from Razorpay and returns them.
    """
    # Fetch all orders without specifying the status
    all_orders = client.order.all({
        'count': 100,  # Limit the number of orders to fetch
    })

    # Filter for only 'created' orders (pending orders)
    pending_orders = [
        {
            'id': order['id'],
            'client_id': order.get('client_id', ''),
            'amount': order['amount'] / 100,  # Convert from paise to rupees
            'status': order['status'],
            'billing_cycle': 1,  # Default, adjust as per your business logic
            'invoice_id': order.get('invoice_id', ''),
            'billing_from_date': order.get('billing_from_date', None),
            'billing_to_date': order.get('billing_to_date', None),
            'invoice_amount': order.get('invoice_amount', 0),
        }
        for order in all_orders['items']
        if order['status'] == 'created'  # Only include 'created' orders (pending orders)
    ]

    return pending_orders
