from django.shortcuts import render, HttpResponseRedirect
from django.http import JsonResponse
from django.db.models import Q
from inventory.models import *
from masters.models import *
from stock.models import *
from sales.models import *
from material.models import *
from supplier.models import *
from common.utils import *
from store.models import branch_table

def ho_stock_report(request):
    if 'user_id' in request.session:
        # Fetching master data for filters
        supplier = selectList(supplier_table, {'is_global': 1}, order_by='name')
        category = selectList(category_table)
        sub_category = selectList(sub_category_table)
        brand = selectList(brand_table)
        return render(request, 'ho_stock.html', {
            'supplier': supplier,
            'category': category,
            'sub_category': sub_category,
            'brand': brand
        })
    else:
        return HttpResponseRedirect("/")

def ajax_ho_stock_summary(request):
    from reports.report_utils import get_imei_stock_summary_data
    
    # 1. Gather Filters
    filters = {
        'subcategory': request.POST.get('subcategory'),
        'brand_id': request.POST.get('brand_id'),
        'model_id': request.POST.get('model_id'),
        'variant_id': request.POST.get('variant_id'),
        'color_id': request.POST.get('color_id'),
        'stock': request.POST.get('stock_type'),
    }

    # 2. Find all HO Branches and aggregate their stock
    ho_branches = branch_table.objects.filter(is_ho=1, is_active=1)
    if not ho_branches.exists():
        return JsonResponse({'data': [], 'message': 'No HO Branches found'})
    
    combined_data = []
    global_counter = 1

    for ho_branch in ho_branches:
        # Call as is_ho=0 to force strict filtering for this specific HO branch id
        _, branch_formatted = get_imei_stock_summary_data(
            branch_id=ho_branch.id,
            is_ho=0,
            filters=filters,
            include_schemes=False
        )
        
        # Add to combined list
        for item in branch_formatted:
            # Map report_utils keys to ho_stock template keys
            item['id'] = global_counter
            item['branch_name'] = item.get('branch')
            item['sub_category'] = item.get('sub_category')
            item['imei_no'] = item.get('imei')
            
            # Additional keys required by HO Stock template
            item['supplier_name'] = '-'
            item['supplier_gst'] = '-'
            item['supplier_balance'] = '0.00'
            
            combined_data.append(item)
            global_counter += 1

    return JsonResponse({'data': combined_data})
