from django.shortcuts import render
from django.http import JsonResponse
from django.db.models import Q
from inventory.models import *
from sales.models import *
from material.models import *
from stock.models import *
from masters.models import *
from common.utils import selectList, getItemNameById, format_amount, calculate_financial_year, check_user_access, format_date_month_year, select_row
from store.models import *
from scheme.models import *
from django.http import HttpResponseRedirect
from supplier.models import *

# ***************************************************************************************************************************

def reversed_imei_report(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 is_ho == 1:
            branches = branch_table.objects.filter(status=1).order_by('name')
        else:
            branches = branch_table.objects.filter(status=1, id=branch_id).order_by('name')

        suppliers = supplier_table.objects.filter(status=1).order_by('name')

        return render(request, 'reversed_imei_report.html', {'branches': branches, 'suppliers': suppliers})
    else:
        return HttpResponseRedirect("/")

def ajax_reversed_imei_report(request):
    role_id = request.session.get('role_id')
    branch_id = request.session.get('branch_id')
    is_ho = request.session.get('is_ho')
    fyf_name = request.session.get('fyf')
    financial_year = calculate_financial_year(fyf_name)
    
    # Check for specific report permission or general purchase return report permission
    has_access, _ = check_user_access(role_id, 'reversed_imei_report', "read")
    if not has_access:
        has_access, _ = check_user_access(role_id, 'purchase_return_report', "read")
        
    if not has_access:
        return JsonResponse({'message': 'permission', 'error_message': 'You do not have permission to view this report'})

    # Get filter parameters
    from_date = request.POST.get('from_date')
    to_date = request.POST.get('to_date')
    selected_branch_id = request.POST.get('branch_id')
    selected_supplier_id = request.POST.get('supplier_id')
    selected_status = request.POST.get('pr_status')

    # Query tm_purchase_return for filters
    tm_query = Q(status=1)
    if is_ho == 0 or is_ho == '0':
        tm_query &= Q(branch_id=branch_id)
    elif selected_branch_id:
        tm_query &= Q(branch_id=selected_branch_id)
    
    if selected_supplier_id:
        tm_query &= Q(supplier_id=selected_supplier_id)
    
    if selected_status:
        tm_query &= Q(pr_status=selected_status)
    else:
        # If no status selected, default to reversed or check all? 
        # Requirement says "reversed imei report" but "status in filter"
        # I'll default to all if nothing selected, but UI might default to reversed
        pass
    
    if from_date and to_date:
        tm_query &= Q(pr_date__range=[from_date, to_date])

    tm_returns = purchase_return_table.objects.filter(tm_query).values('id', 'branch_id', 'supplier_id', 'pr_date', 'pr_no', 'pr_status')
    tm_return_ids = [tm['id'] for tm in tm_returns]
    tm_map = {tm['id']: tm for tm in tm_returns}

    if not tm_return_ids:
        return JsonResponse({'data': []})

    # Query tx_purchase_return
    child_items = child_purchase_return_table.objects.filter(
        status=1,
        tm_return_id__in=tm_return_ids
    ).values(
        'tm_return_id', 'subcategory_id', 'brand_id', 'model_id', 'variant_id', 'color_id',
        'imei_no', 'rate', 'tax_amount', 'amount', 'tax_cgst', 'tax_sgst', 'tax_igst', 'inward_id'
    )

    formatted_data = []
    for idx, item in enumerate(child_items):
        tm_data = tm_map.get(item['tm_return_id'], {})
        purchase = select_row(purchase_inward_table, {'id': item['inward_id']})
        
        status_badges = {
            'pending': '<span class="badge text-bg-info">Pending</span>',
            'approved': '<span class="badge text-bg-success">Approved</span>',
            'reversed': '<span class="badge text-bg-danger">Reversed</span>'
        }
        
        status_val = tm_data.get('pr_status', '').lower()
        status_html = status_badges.get(status_val, f'<span class="badge text-bg-secondary">{status_val.capitalize()}</span>')
        
        formatted_data.append({
            'sl_no': idx + 1,
            'inward_date': format_date_month_year(purchase.pu_date) if purchase else '-',
            'inward_no': (
                f"<a href='javascript:void(0);' class='invoice-link text-primary fw-semibold' "
                f"onclick='purchase_data({purchase.id})'>{purchase.pu_no}</a>"
            ) if purchase else '-',
            'date': format_date_month_year(tm_data.get('pr_date')),
            'return_no': (
                f"<a href='javascript:void(0);' class='invoice-link text-primary fw-semibold' "
                f"onclick='purchase_return_data({tm_data.get('id')})'>{tm_data.get('pr_no')}</a>"
            ),
            'branch': getItemNameById(branch_table, tm_data.get('branch_id')),
            'supplier': getItemNameById(supplier_table, tm_data.get('supplier_id')),
            'subcategory': 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']),
            'imei': item['imei_no'] if item['imei_no'] else '-',
            'rate': format_amount(item['rate']),
            'tax_amount': format_amount(item['tax_amount']),
            'tax_cgst': format_amount(item['tax_cgst']),
            'tax_sgst': format_amount(item['tax_sgst']),
            'tax_igst': format_amount(item['tax_igst']),
            'amount': format_amount(item['amount']),
            'status': status_html
        })

    return JsonResponse({'data': formatted_data})
