from django.shortcuts import render
import json
from django.conf import settings
from django.shortcuts import render
from inventory.models import *
from expenses.models import *
from store.models import *
from company.models import *
from masters.models import *
from supplier.models import *
from django.db import IntegrityError, transaction
import hashlib
import os
from django.conf import settings
from datetime import datetime
from django.utils import timezone
from django.db.models import Max, F, Q,Sum
import base64
from django.shortcuts import render
from io import BytesIO
from django.conf import settings
from django.template.loader import get_template
from django.http import HttpResponse,HttpResponseRedirect,JsonResponse,FileResponse
from django.shortcuts import get_object_or_404
from django.templatetags.static import static
from xhtml2pdf import pisa
from num2words import num2words
from django.contrib.staticfiles import finders  
from common.utils import *
from django.db import connection
import openpyxl
from openpyxl.styles import Font
from django.http import HttpResponse
from django.core.files.storage import default_storage
from sales.models import *
from scheme.models import *
# *********************************************************************************************************************************


def purchase_summary(request):
    if 'user_id' in request.session:
        user_type = request.session.get('user_type')
        branch_id = request.session.get('branch_id')
        is_ho = request.session.get('is_ho')
        encoded_id = request.GET.get('id') or 0
        if encoded_id != 0:
            decoded_id = decode_base64_id(encoded_id) or 0
        else:
            decoded_id = 0
        print(decoded_id)
        if user_type == 'stores':
            company = select_row(company_table, {'id': 1})  
            category = selectList(category_table, order_by='name')
            if is_ho == 1:
                supplier = selectList(supplier_table, order_by='name' )
            else:
                supplier = selectList(supplier_table, Q(is_global=1), order_by='name' )
   
            branch = selectList(branch_table, order_by='name').exclude(id=branch_id)
            return render(request, 'purchase_summary.html', {'company': company,'category':category,'supplier':supplier,'branch':branch,'decoded_id':decoded_id})
        else:
            return HttpResponseRedirect("/")
    else:
        return HttpResponseRedirect("/")


from django.http import JsonResponse
from django.db.models import Q
from collections import defaultdict

def ajax_purchase_summary(request):
    role_id = request.session.get('role_id')
    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, 'purchase_inward', "read"
    )
    if not has_access:
        return JsonResponse({
            'message': 'permission',
            'error_message': 'You do not have permission to view purchase inward details'
        })

    supplier_id = request.POST.get('supplier_id')
    from_date = request.POST.get('from_date')
    to_date = request.POST.get('to_date')
    keyword = request.POST.get('keyword_search', '').strip()

    query = Q(
        status=1,
        branch_id=branch_id,
        current_fy=financial_year
    )

    if supplier_id:
        query &= Q(supplier_id=supplier_id)

    if from_date and to_date:
        query &= Q(pu_date__range=[from_date, to_date])

    if keyword:
        query &= Q(pu_no__icontains=keyword)

    # -------------------------
    # Parent purchase inward
    # -------------------------
    purchase_qs = list(
        selectList(purchase_inward_table, query).values()
    )

    if not purchase_qs:
        return JsonResponse({'data': []})

    pu_ids = [p['id'] for p in purchase_qs]

    # -------------------------
    # Child table – Detail fetch & Grouping
    # -------------------------
    child_qs = child_purchase_inward_table.objects.filter(
        status=1,
        is_active=1,
        tm_pu_id__in=pu_ids
    ).values(
        'tm_pu_id', 'subcategory_id', 'brand_id', 'model_id', 'variant_id', 'color_id', 'rate', 
        'imei_no', 'quantity', 'amount', 'tax_sgst', 'tax_cgst', 'discount_amount'
    )

    group_data = defaultdict(lambda: {
        'imeis': [],
        'quantity': 0,
        'amount': 0,
        'tax_sgst': 0,
        'tax_cgst': 0,
        'discount_amount': 0
    })

    for crow in child_qs:
        # Convert variant_id to int if possible for consistent grouping
        v_id = crow['variant_id']
        try: v_id = int(v_id) 
        except: pass

        key = (
            crow['tm_pu_id'], 
            crow['subcategory_id'], 
            crow['brand_id'], 
            crow['model_id'], 
            v_id, 
            crow['color_id'], 
            crow['rate']
        )
        if crow['imei_no']:
            group_data[key]['imeis'].append(crow['imei_no'])
        
        group_data[key]['quantity'] += (crow['quantity'] or 0)
        group_data[key]['amount'] += float(crow['amount'] or 0)
        group_data[key]['tax_sgst'] += float(crow['tax_sgst'] or 0)
        group_data[key]['tax_cgst'] += float(crow['tax_cgst'] or 0)
        group_data[key]['discount_amount'] += float(crow['discount_amount'] or 0)

    # -------------------------
    # Final formatting
    # -------------------------
    formatted = []
    purchase_map = {p['id']: p for p in purchase_qs}
    
    # Sort groups by parent ID for consistent display
    sorted_keys = sorted(group_data.keys(), key=lambda x: (x[0], x[1], x[2], x[3]))

    for index, key in enumerate(sorted_keys):
        vals = group_data[key]
        item = purchase_map.get(key[0], {})
        imei_str = ', '.join(vals['imeis']) if vals['imeis'] else '-'
        
        # Get SKU text from item table based on attributes
        sku_row = item_table.objects.filter(
            sub_category_id=key[1],
            brand_id=key[2],
            model_id=key[3],
            variant_id=key[4],
            color_id=key[5],
            status=1
        ).first()
        sku_val = sku_row.sku_text if sku_row and sku_row.sku_text else '-'

        formatted.append({
            'id': index + 1,
            'inward_no': item.get('pu_no') or '-',
            'inward_date': item['pu_date'].strftime('%d-%m-%Y') if item.get('pu_date') else '-',
            'supplier_no': item.get('supplier_no') or '-',
            'supplier_date': item['supplier_date'].strftime('%d-%m-%Y') if item.get('supplier_date') else '-',
            'supplier': getItemNameById(supplier_table, item['supplier_id']),
            'sku': sku_val,
            'imei': imei_str,
            'quantity': vals['quantity'],
            'rate': format_amount(key[6]),
            'discount_percent': '',
            'discount_amount': format_amount(vals['discount_amount']),
            'tax_sgst': format_amount(vals['tax_sgst']),
            'tax_cgst': format_amount(vals['tax_cgst']),
            'total_amount': format_amount(vals['amount'])
        })

    return JsonResponse({'data': formatted})
