from django.shortcuts import render
import json
from django.conf import settings
from django.shortcuts import render
from sales.models import *
from expenses.models import *
from store.models import *
from masters.models import *
from stock.models import *
from material.models import *

from collections import defaultdict
from sales.forms 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
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.views.decorators.csrf import csrf_exempt
from supplier.models import *
from django.db import connection
from customer.models import *
from django.db import transaction as db_transaction
from scheme.models import *

# *******************************************************************************************



def invoice_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')
        if user_type == 'stores':
            branch = selectList(branch_table, order_by='name').exclude(id=branch_id)
            if is_ho == 1:
                supplier = selectList(supplier_table, order_by='name' )
            else:
                supplier = selectList(supplier_table, Q(is_global=1) , order_by='name' )

            return render(request, 'invoice_summary.html',{'supplier':supplier,'branch':branch})
        else:
            return HttpResponseRedirect("/")
    else:
        return HttpResponseRedirect("/")
    



def ajax_invoice_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)
    keyword         = request.POST.get('keyword_search', '').strip()
    search_type     = request.POST.get('search_type')
    from_date       = request.POST.get('from_date')
    to_date         = request.POST.get('to_date')
    store_id        = request.POST.get('store_id')

    has_access, error_message = check_user_access(role_id, 'sales', "read")    
    if not has_access:
        return JsonResponse({'message': 'permission', 'error_message': 'You do not have permission to view sales orders.'})

    query = Q(status=1, branch_id=branch_id, current_fy=financial_year)

    if from_date and to_date:
        query &= Q(inv_date__range=[from_date, to_date])
    if store_id:
        query &= Q(store_id=store_id)
    if keyword:
        if search_type == 'name': query &= Q(customer_name__icontains=keyword)
        elif search_type == 'phone': query &= Q(phone__icontains=keyword)
        elif search_type == 'sales_no': query &= Q(inv_no__icontains=keyword)
   
    purchase_qs = sales_order_table.objects.filter(query).values(
        'id', 'inv_no', 'inv_date', 'time',
        'customer_id', 'customer_name', 'customer_phone', 'customer_type'
    )
    purchase_ids = [p['id'] for p in purchase_qs]
    if not purchase_ids:
        return JsonResponse({'data': []})
    
    purchase_map = {p['id']: p for p in purchase_qs}
    item_qs = item_table.objects.filter(
        status=1,
        is_active=1
    ).values(
        'sub_category_id',
        'brand_id',
        'model_id',
        'variant_id',
        'color_id',
        'sku_text'
    )

    item_map = {
        (
            i['sub_category_id'],
            i['brand_id'],
            i['model_id'],
            i['variant_id'],
            i['color_id'],
        ): i['sku_text']
        for i in item_qs
    }


    child_qs = child_sales_order_table.objects.filter(
        status=1,
        branch_id=branch_id,
        current_fy=financial_year,
        tm_sales_id__in=purchase_ids
    ).values()
    
   
    formatted = []
    for index, item in enumerate(child_qs):
        purchase = purchase_map.get(item['tm_sales_id'], {})
        sku_key = (
            item.get('subcategory_id'),
            item.get('brand_id'),
            item.get('model_id'),
            item.get('variant_id'),
            item.get('color_id'),
        )
        formatted.append({
            'id': index + 1,
            'inv_no'     : purchase.get('inv_no', '-'), 
            'date'      : format_date_month_year(purchase.get('inv_date')) if purchase.get('inv_date') else '-', 
            'customer'  : purchase.get('customer_name', '-'), 
            'phone'     : purchase.get('customer_phone', '-'), 
            'customer_type'     : purchase.get('customer_type', '-'), 
            'sku'     : item_map.get(sku_key, '-'), 
            'imei'     : item.get('imei_no', '-'), 
            'quantity'  : item.get('quantity', 0), 
            'rate'     : item.get('rate', 0.00), 
            'discount_percent'     : item.get('discount_percent', 0.00), 
            'discount_amount'     : item.get('discount_amount', 0.00), 
            'amount': item.get('amount', 0.00),
            
            
        })

    return JsonResponse({'data': formatted})
