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 supplier.models import *
from material.models import *
from stock.models import *
from scheme.models import *

def slabwise_report(request):
    if 'user_id' in request.session:
        user_type = request.session.get('user_type')
        branch_id = request.session.get('branch_id')
        role_id = request.session.get('role_id')      
        branch = selectList(branch_table, order_by='name')
        customers = selectList(customer_table, order_by='name')
        subcategory = selectList(sub_category_table, order_by='name')
        brands = selectList(brand_table, order_by='name')
        models = selectList(model_table, order_by='name')
        variants = selectList(variant_table, order_by='name')
        colors = selectList(color_table, order_by='name')
        
        return render(request, 'slabwise_report.html', {
            'customers': customers,
            'subcategory': subcategory,
            'brands': brands,
            'models': models,
            'variants': variants,
            'colors': colors,
            'branch': branch,
        })
    else:
        return HttpResponseRedirect("/")
    


def ajax_slabwise_report(request):
    role_id = request.session.get('role_id')
    is_ho = request.session.get('is_ho')
    fyf_name = request.session.get('fyf')
    financial_year = calculate_financial_year(fyf_name)

    has_access, error_message = check_user_access(role_id, 'sales_tax_report', "read")
    if not has_access:
        return JsonResponse({
            'message': 'permission',
            'error_message': 'You do not have permission to view sales tax report details'
        })

    branch_id = request.POST.get('branch_id')

    from_date = request.POST.get('from_date')
    to_date = request.POST.get('to_date')

    # -----------------------------
    # 1️⃣ Sales Filter
    # -----------------------------
    # 1️⃣ Sales Filter
    # -----------------------------
    query = Q(status=1, current_fy=financial_year)

    if from_date and to_date:
        query &= Q(inv_date__range=[from_date, to_date])

    if branch_id:
        query &= Q(branch_id=branch_id)

    sales_ids = sales_order_table.objects.filter(query).values_list('id', flat=True)

    # 2️⃣ Fetch Child Sales Records
    # -----------------------------
    child_sales = child_sales_order_table.objects.filter(tm_sales_id__in=sales_ids, status=1).order_by('-id')

    # 3️⃣ Master Data Cache for efficiency
    # -----------------------------
    branches = {b.id: b.name for b in branch_table.objects.all()}
    subcategories = {s.id: s.name for s in sub_category_table.objects.all()}
    brands = {b.id: b.name for b in brand_table.objects.all()}
    models = {m.id: m.name for m in model_table.objects.all()}
    variants = {v.id: v.name for v in variant_table.objects.all()}
    colors = {c.id: c.name for c in color_table.objects.all()}

    formatted = []
    for i, row in enumerate(child_sales):
        # Fetch SKU text from item table
        item = item_table.objects.filter(
            sub_category_id=row.subcategory_id,
            brand_id=row.brand_id,
            model_id=row.model_id,
            variant_id=row.variant_id,
            color_id=row.color_id,
            status=1
        ).first()

        sku_text = item.sku_text if item else ''

        formatted.append({
            'id': i + 1,
            'branch': branches.get(row.branch_id, ''),
            'sku': sku_text,
            'subcategory': subcategories.get(row.subcategory_id, ''),
            'brand': brands.get(row.brand_id, ''),
            'model': models.get(row.model_id, ''),
            'variant': variants.get(row.variant_id, ''),
            'color': colors.get(row.color_id, ''),
            'sales_qty': row.quantity,
            'amount_per_pcs': float(row.amount) / row.quantity if row.quantity > 0 else 0,
            'scheme': float(row.special_amount) if row.special_amount else 0,
        })

    return JsonResponse({'data': formatted})


