from django.shortcuts import render
from django.db.models import Q
from django.http import HttpResponseRedirect, JsonResponse
from sales.models import *
from company.models import *
from masters.models import *
from common.utils import *
from inventory.models import *
from material.models import *
from stock.models import *

def exchange_report(request):
    if 'user_id' in request.session:
        branch_id = request.session.get('branch_id')
        branch = selectList(branch_table, order_by='name')
        customers = selectList(customer_table, order_by='name')
        
        return render(request, 'exchange_report.html', {
            'customers': customers,
            'branch': branch,
        })
    else:
        return HttpResponseRedirect("/")

def ajax_exchange_report(request):
    role_id = request.session.get('role_id')
    is_ho = request.session.get('is_ho')
    branch_id = request.session.get('branch_id')
    fyf_name = request.session.get('fyf')
    financial_year = calculate_financial_year(fyf_name)

    has_access, error_message = check_user_access(role_id, 'exchange_report', "read")
    if not has_access:
        return JsonResponse({
            'message': 'permission',
            'error_message': 'You do not have permission to view this report'
        })

    from_date = request.POST.get('from_date')
    to_date = request.POST.get('to_date')
    branch_id_post = request.POST.get('branch_id')
    customer_id = request.POST.get('customer_id')

    # 1. Filter Transactions for EXCHANGe
    tx_q = Q(status=1, is_active=1, current_fy=financial_year, payment_type='exchange')
    
    if not is_ho:
        tx_q &= Q(branch_id=branch_id)
    if branch_id_post:
        tx_q &= Q(branch_id=branch_id_post)
    if from_date and to_date:
        tx_q &= Q(date__range=[from_date, to_date])
    
    # Get all exchange transactions
    ex_transactions = transaction_table.objects.filter(tx_q).values(
        'tm_sales_id', 'reference_no', 'amount', 'exchange_claim', 'date'
    )

    if not ex_transactions:
        return JsonResponse({'data': []})

    tm_sales_ids = [t['tm_sales_id'] for t in ex_transactions if t['tm_sales_id']]
    
    # 2. Get TM Sales details
    tm_sales = sales_order_table.objects.filter(id__in=tm_sales_ids, status=1).values(
        'id', 'inv_no', 'inv_date', 'customer_name', 'total_amount', 'branch_id'
    )
    tm_map = {s['id']: s for s in tm_sales}

    # 3. Get TX Sales details (the item sold)
    tx_sales = child_sales_order_table.objects.filter(tm_sales_id__in=tm_sales_ids, status=1).values(
        'tm_sales_id', 'imei_no', 'subcategory_id', 'brand_id', 'model_id', 'variant_id', 'color_id', 
        'amount', 'tax_cgst', 'tax_sgst'
    )
    
    # Group TX sales by TM ID because one invoice might have multiple items
    tx_map = {}
    for tx in tx_sales:
        if tx['tm_sales_id'] not in tx_map:
            tx_map[tx['tm_sales_id']] = []
        tx_map[tx['tm_sales_id']].append(tx)

    formatted = []
    counter = 1

    for ex in ex_transactions:
        tm = tm_map.get(ex['tm_sales_id'])
        if not tm:
            continue
            
        # Get items for this invoice
        inv_items = tx_map.get(ex['tm_sales_id'], [])
        
        for item in inv_items:
            # Get names for master data
            subcat = getItemNameById(sub_category_table, item['subcategory_id'])
            brand = getItemNameById(brand_table, item['brand_id'])
            model = getItemNameById(model_table, item['model_id'])
            variant = getItemNameById(variant_table, item['variant_id'])
            color = getItemNameById(color_table, item['color_id'])
            
            formatted.append({
                'id': counter,
                'branch_name': getItemNameById(branch_table, tm['branch_id']),
                'inv_no': tm['inv_no'],
                'inv_date': tm['inv_date'].strftime('%d-%m-%Y'),
                'customer_name': tm['customer_name'],
                'total_bill': f"{tm['total_amount']:.2f}",
                'qty': 1,
                'imei': item['imei_no'],
                'subcategory': subcat,
                'brand': brand,
                'model': model,
                'variant': variant,
                'color': color,
                'amount': f"{item['amount']:.2f}",
                'cgst': f"{item['tax_cgst']:.2f}",
                'sgst': f"{item['tax_sgst']:.2f}",
                'exchange_details': ex['reference_no'], # Old IMEI
                'exchange_amt': f"{ex['amount']:.2f}",
            })
            counter += 1

    return JsonResponse({'data': formatted})
