
import os
import re

file_path = 'core/views.py'

with open(file_path, 'r') as f:
    content = f.read()

# Implement add_payment_method_ajax
# It currently looks like:
# @login_required
# def add_payment_method_ajax(request):
#     return JsonResponse({'success': True})

new_add_payment_method = """@csrf_exempt
@login_required
def add_payment_method_ajax(request):
    if request.method != 'POST':
        return JsonResponse({'success': False, 'error': 'Invalid method'})
    try:
        data = json.loads(request.body)
        pm = PaymentMethod.objects.create(
            name_en=data.get('name_en'),
            name_ar=data.get('name_ar'),
            is_active=data.get('is_active', True)
        )
        return JsonResponse({
            'success': True,
            'id': pm.id,
            'name_en': pm.name_en,
            'name_ar': pm.name_ar
        })
    except Exception as e:
        return JsonResponse({'success': False, 'error': str(e)})"""

content = re.sub(
    r'@login_required\s+def add_payment_method_ajax\(request\):\s+return JsonResponse\({\s*["']success["']: True\s*}\)',
    new_add_payment_method,
    content
)

# Implement create_purchase_api
new_create_purchase = """@csrf_exempt
@login_required
def create_purchase_api(request):
    if request.method != 'POST':
        return JsonResponse({'success': False, 'error': 'Invalid request'})
    try:
        data = json.loads(request.body)
        with transaction.atomic():
            purchase = Purchase.objects.create(
                supplier_id=data.get('supplier_id') or None,
                total_amount=data.get('total_amount', 0),
                paid_amount=data.get('paid_amount', 0),
                created_by=request.user,
                status='paid' if data.get('payment_type') == 'cash' else 'partial'
            )
            for item in data.get('items', []):
                PurchaseItem.objects.create(
                    purchase=purchase,
                    product_id=item['id'],
                    quantity=item['quantity'],
                    cost_price=item['cost'],
                    line_total=float(item['quantity']) * float(item['cost'])
                )
                # Increase Stock
                Product.objects.filter(pk=item['id']).update(stock_quantity=F('stock_quantity') + item['quantity'])
            
            # Payment
            if purchase.paid_amount > 0:
                PurchasePayment.objects.create(
                    purchase=purchase,
                    amount=purchase.paid_amount,
                    payment_method_id=data.get('payment_method_id'),
                    created_by=request.user
                )
                
            purchase.update_balance()

        return JsonResponse({'success': True, 'purchase_id': purchase.id})
    except Exception as e:
        logger.error(f"Error creating purchase: {e}")
        return JsonResponse({'success': False, 'error': str(e)})"""

content = re.sub(
    r'@csrf_exempt\s+@login_required\s+def create_purchase_api\(request\):\s+return JsonResponse\({\s*["']success["']: True\s*}\)',
    new_create_purchase,
    content
)


# Implement add_customer_ajax
new_add_customer = """@csrf_exempt
@login_required
def add_customer_ajax(request):
    if request.method != 'POST':
        return JsonResponse({'success': False})
    try:
        data = json.loads(request.body)
        Customer.objects.create(name=data.get('name'), phone=data.get('phone', ''))
        return JsonResponse({'success': True})
    except Exception as e:
        return JsonResponse({'success': False, 'error': str(e)})"""

content = re.sub(
    r'@login_required\s+def add_customer_ajax\(request\):\s+return JsonResponse\({\s*["']success["']: True\s*}\)',
    new_add_customer,
    content
)

# Implement add_supplier_ajax
new_add_supplier = """@csrf_exempt
@login_required
def add_supplier_ajax(request):
    if request.method != 'POST':
        return JsonResponse({'success': False})
    try:
        data = json.loads(request.body)
        Supplier.objects.create(name=data.get('name'), phone=data.get('phone', ''))
        return JsonResponse({'success': True})
    except Exception as e:
        return JsonResponse({'success': False, 'error': str(e)})"""

content = re.sub(
    r'@login_required\s+def add_supplier_ajax\(request\):\s+return JsonResponse\({\s*["']success["']: True\s*}\)',
    new_add_supplier,
    content
)

with open(file_path, 'w') as f:
    f.write(content)

print("Patched core/views.py successfully.")
