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 *
from wholesale.models import *
# *********************************************************************************************************************************


def collection(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':
            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, 'collect/details.html', {'company': company,'category':category,'supplier':supplier,'branch':branch})
        else:
            return HttpResponseRedirect("/")
    else:
        return HttpResponseRedirect("/")



def collection_add(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')
        fyf_name = request.session.get('fyf')
        financial_year = calculate_financial_year(fyf_name)
        if user_type == 'stores':
            company = select_row(company_table, {'id': 1})  
            category = selectList(category_table, order_by='name')
            if is_ho == 1:
                bank = selectList(bank_table, {'is_default':0}, order_by='name')
                supplier = selectList(supplier_table, order_by='name' )
            else:
                supplier = selectList(supplier_table, Q(is_global=1), order_by='name' )   
                bank = selectList(bank_table, order_by='name')
            branch = selectList(branch_table, order_by='name').exclude(id=branch_id)
            finance = selectList(finance_table, order_by='name')
            claim_no = generate_serial_number(model= tm_collection_table,number_field ='collection_no',financial_year_field ='current_fy',financial_year = financial_year,branch_id= branch_id,prefix="")
            return render(request, 'collect/add.html', {'company': company,'category':category,'supplier':supplier,'branch':branch,'finance':finance,'bank':bank,'claim_no':claim_no})
        else:
            return HttpResponseRedirect("/")
    else:
        return HttpResponseRedirect("/")


def collection_edit(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':
            encoded_id = request.GET.get('id')
            decoded_id = decode_base64_id(encoded_id)
            if not decoded_id:
                return HttpResponse("ID parameter is missing")
            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' )
                bank = selectList(bank_table, {'is_default':0}, order_by='name')
            else:
                supplier = selectList(supplier_table, Q(is_global=1), order_by='name' )  
                bank = selectList(bank_table, {'is_default':1}, order_by='name')

            branch = selectList(branch_table, order_by='name').exclude(id=branch_id)
            finance = selectList(finance_table, order_by='name')
            collect = select_row(tm_collection_table, {'id': decoded_id})
            
            return render(request, 'collect/edit.html', {'company': company,'category':category,'supplier':supplier,'branch':branch,'finance':finance,'bank':bank,'collect':collect}) 
        else:
            return HttpResponseRedirect("/")
    else:
        return HttpResponseRedirect("/")
    
from django.http import JsonResponse
from django.db.models import Q
from decimal import Decimal
from django.db.models import Q
from django.http import JsonResponse
from django.db.models import Q
from decimal import Decimal

def load_collection_details(request):
    from_date = request.POST.get('from_date')
    to_date = request.POST.get('to_date')
    finance_id = request.POST.get('finance_id')
    f_type = request.POST.get('f_type')
    claim_status_filter = request.POST.get('claim_status')
    if claim_status_filter:
        try:
            claim_status_filter = json.loads(claim_status_filter)
        except:
            claim_status_filter = [claim_status_filter] if claim_status_filter else []

    sales_status_filter = request.POST.get('sales_status') # NEW: Status filter (Approved/Pending/Rejected)
    mode = request.POST.get('mode')
    tm_collect_id = request.POST.get('tm_collect_id')
    branch_id = request.session.get('branch_id')

    if not (from_date and to_date and f_type):
        return JsonResponse({'data': []})

    # 🔹 Get all transactions first
    all_tx = transaction_table.objects.filter(
        date__range=[from_date, to_date],
        status=1
    )

    if claim_status_filter:
        # If multiple statuses are provided, filter by any of them across relevant fields
        all_tx = all_tx.filter(
            Q(collect_status__in=claim_status_filter) | 
            Q(charge_status__in=claim_status_filter) | 
            Q(exchange_status__in=claim_status_filter)
        )

    # 🔹 Fetch Default Bank IDs (to exclude them)
    default_bank_ids = set(bank_table.objects.filter(is_default=1, status=1).values_list('id', flat=True))

    existing_tx_ids = set()
    if mode == 'edit' and tm_collect_id:
        existing_tx_ids = set(
            x.transaction_id for x in tx_collection_table.objects.filter(
                tm_collection_id=tm_collect_id,
                is_active=1
            )
        )

    data = []

    for tx in all_tx:
        master = sales_order_table.objects.filter(
            id=tx.tm_sales_id,
            status=1
        ).first()
        if not master:
            continue

        total_tx_amount = Decimal(tx.amount or 0)
        is_checked = 1 if tx.id in existing_tx_ids else 0
        remaining_balance = total_tx_amount if is_checked else total_tx_amount - Decimal(tx.collect_amount or 0)

        # -----------------
        # 🔹 MAIN TRANSACTION ROW
        # -----------------
        # Only include if transaction type matches the view AND finance_id matches (if provided)
        include_tx = False

        if f_type == 'finance' and tx.payment_type == 'finance':
            if finance_id:
                include_tx = (tx.finance_id == int(finance_id))
            else:
                include_tx = True
                
        elif f_type == 'card' and tx.payment_type == 'card':
            if finance_id:
                include_tx = (tx.card_id == int(finance_id))
            else:
                include_tx = True
                
        elif f_type == 'bank' and tx.payment_type == 'bank':
            if tx.bank_id in default_bank_ids:
                include_tx = False
            elif finance_id:
                include_tx = (tx.bank_id == int(finance_id))
            else:
                include_tx = True
        
        elif f_type == 'exchange' and tx.payment_type == 'exchange':
            if tx.branch_id == branch_id:
                include_tx = True   

        if include_tx:
            # 🔹 Filter by Status if provided
            current_status = tx.exchange_status if f_type == 'exchange' else tx.collect_status
            if claim_status_filter and current_status not in claim_status_filter:
                include_tx = False

        if include_tx:
            # Filter by Sales Order Status (Approval Workflow)
            if sales_status_filter and master.sales_status != sales_status_filter:
                include_tx = False

        if include_tx:
            if f_type == 'bank':
                finance_pk = tx.bank_id
                base_name = bank_table.objects.filter(id=tx.bank_id).first()
                base_name = base_name.name if base_name else "-"
                bank_name = base_name  # For bank type, bank_name is same as base_name
            elif f_type == 'card':
                finance_pk = tx.card_id

                base_name = finance_table.objects.filter(id=tx.card_id).first()
                base_name = base_name.name if base_name else "-"
                bank_obj = bank_table.objects.filter(id=tx.bank_id).first() if tx.bank_id else None
                bank_name = bank_obj.name if bank_obj else "-"
            elif f_type == 'exchange':
                finance_pk = 0
                base_name = tx.reference_no if tx.reference_no else "Exchange"
                bank_name = "-"
            else:
                finance_pk = tx.finance_id
                base_name = finance_table.objects.filter(id=tx.finance_id).first()
                base_name = base_name.name if base_name else "-"
                bank_obj = bank_table.objects.filter(id=tx.bank_id).first() if tx.bank_id else None
                bank_name = bank_obj.name if bank_obj else "-"

            data.append({
                "id": tx.id,
                "sales_id": tx.tm_sales_id,
                "transaction_id": tx.id,
                "inv_date": master.inv_date.strftime("%Y-%m-%d"),
                "inv_no": master.inv_no,
                "customer_name": master.customer_name,
                "customer_phone": master.customer_phone,
                "customer_type": master.customer_type,
                "total_amount": master.total_amount,
                "total_paid": master.total_paid,
                "branch_name": getItemNameById(branch_table, master.branch_id),
                "type": f_type.title(),
                "finance_id": finance_pk,
                "finance_name": base_name,
                "bank_name": bank_name,  # Added bank name
                "amount": remaining_balance,
                "cashback": tx.cashback,
                "receipt": total_tx_amount,
                "claim_status": format_badge(
                    tx.exchange_status if f_type == 'exchange' else tx.collect_status,
                    mapping={
                        'pending': 'badge text-bg-info',
                        'claimed': 'badge text-bg-success',
                        'partial': 'badge text-bg-warning',
                        'rejected': 'badge text-bg-danger',
                        'complete': 'badge text-bg-success'
                    },
                    label_mapping={
                        'pending': 'Pending',
                        'claimed': 'Claimed',
                        'partial': 'Partial',
                        'rejected': 'Rejected',
                        'complete': 'Complete'
                    }
                ),
                "is_collect": tx.is_collect,
                "is_checked": is_checked,
                "charges": tx.charges,
                "sales_status": master.sales_status if master.sales_status else 'approved',  # Default to 'approved' for backward compatibility
                "rejected_remarks": master.rejected_remarks if master.rejected_remarks else '',
                "branch_id": master.branch_id,
                "row_type": "transaction",
                "raw_claim_status": tx.exchange_status if f_type == 'exchange' else tx.collect_status,
            })
        # -----------------
        if should_show_charge(tx, f_type, finance_id, branch_id):
            # 🔹 Filter by Sales Order Status (Approval Workflow)
            if sales_status_filter and master.sales_status != sales_status_filter:
                continue

            # 🔹 Filter Default Bank Charges
            if tx.charge_mode == 'bank' and tx.charge_bank_id in default_bank_ids:
                continue

            # 🔹 Filter Charge by Status if provided
            if claim_status_filter and tx.charge_status not in claim_status_filter:
                continue

            total_charge_amount = Decimal(tx.charges or 0)
            balance_charge = total_charge_amount - Decimal(tx.charge_amount_collect or 0)

            # Determine if this charge is already collected in this collection
            charge_is_checked = 0
            if mode == 'edit' and tm_collect_id:
                # Check in tx_collection_table for charges (if you store charges separately)
                charge_is_checked = 1 if tx_collection_table.objects.filter(
                    tm_collection_id=tm_collect_id,
                    transaction_id=tx.id,
                    is_active=1,
                    row_type='charge'  # assuming you save row_type='charge' for charge rows
                ).exists() else 0

            # Bank view collects bank-mode charges
            if f_type == 'bank':
                bank = bank_table.objects.filter(id=tx.charge_bank_id).first()
                charge_name = bank.name if bank else "Unknown Bank"
                charge_type_label = "Bank"
                finance_amount = tx.amount
                charge_bank_id = tx.charge_bank_id
                if tx.payment_type == 'finance':
                    tx_name = getItemNameById(finance_table, tx.finance_id)
                if tx.payment_type == 'card':
                    tx_name = getItemNameById(finance_table, tx.card_id)

            elif tx.payment_type == 'card':
                card = finance_table.objects.filter(id=tx.card_id).first()
                charge_name = card.name if card else "Unknown Card"
                charge_type_label = "Card Charge"
                charge_bank_id = tx.card_id
                finance_amount = tx.amount
                tx_name = getItemNameById(finance_table, tx.card_id)
            else:
                finance = finance_table.objects.filter(id=tx.finance_id).first()
                charge_name = finance.name if finance else "Unknown Finance"
                charge_type_label = "Finance Charge"
                charge_bank_id = tx.finance_id
                finance_amount = tx.amount
                tx_name = getItemNameById(finance_table, tx.finance_id)

            data.append({
                "id": f"{tx.id}_charge",
                "sales_id": tx.tm_sales_id,
                "transaction_id": tx.id,
                "inv_date": master.inv_date.strftime("%Y-%m-%d"),
                "inv_no": master.inv_no,
                "customer_name": master.customer_name,
                "customer_phone": master.customer_phone,
                "customer_type": master.customer_type,
                "total_amount": master.total_amount,
                "total_paid": master.total_paid,
                "branch_name": getItemNameById(branch_table, master.branch_id),
                "type": charge_type_label,
                "finance_id": charge_bank_id,
                "finance_name": f"{charge_name} (Charges)",
                "amount": total_charge_amount,  # Remaining balance for this charge
                "receipt": balance_charge,
                "claim_status": format_badge(
                    tx.charge_status,
                    mapping={
                        'pending': 'badge text-bg-info',
                        'claimed': 'badge text-bg-success',
                        'partial': 'badge text-bg-warning',
                        'rejected': 'badge text-bg-danger'
                    },
                    label_mapping={
                        'pending': 'Pending',
                        'claimed': 'Claimed',
                        'partial': 'Partial',
                        'rejected': 'Rejected'
                    }
                ),
                "is_collect": 1 if tx.charge_status == 'claimed' else 0,  # Charge collection is independent from main transaction
                "total_paid": master.total_paid,
                "is_checked": charge_is_checked,  # ✅ Checked based on collection table
                "sales_status": master.sales_status if master.sales_status else 'approved',  # Default to 'approved' for backward compatibility
                "rejected_remarks": master.rejected_remarks if master.rejected_remarks else '',
                "branch_id": master.branch_id,
                "finance_amount": finance_amount,
                "charge_amount": tx.charges,
                "base_name": tx_name,
                "p_type": tx.payment_type,
                "row_type": "charge",
                "raw_claim_status": tx.charge_status,
            })

    # 🔹 Process Wholesale Transactions (Finance)
    if f_type == 'finance':
        wholesale_qs = wholesale_sales_order_table.objects.filter(
            inv_date__range=[from_date, to_date],
            status=1,
            finance_amount__gt=0
        )
        if claim_status_filter:
            wholesale_qs = wholesale_qs.filter(collect_status__in=claim_status_filter)
        
        for w_tx in wholesale_qs:
            customer_id = w_tx.customer_id
            customer = select_row(customer_table, {'id':customer_id})
            include_w = False
            if finance_id:
                include_w = (w_tx.finance_id == int(finance_id))
            else:
                include_w = True
            
            if include_w:
                w_finance_amt = Decimal(str(w_tx.finance_amount or 0))
                w_collected_amt = Decimal(str(w_tx.collected_amount or 0))
                
                is_checked_w = 0
                if mode == 'edit' and tm_collect_id:
                    is_checked_w = 1 if tx_collection_table.objects.filter(
                        tm_collection_id=tm_collect_id,
                        transaction_id=w_tx.id,
                        is_active=1,
                        row_type='wholesale_finance'
                    ).exists() else 0
                
                remaining_w = w_finance_amt if is_checked_w else w_finance_amt - w_collected_amt
                
                # If not editing and no balance, skip
                if not is_checked_w and remaining_w <= 0:
                    continue

                data.append({
                    "id": f"w_{w_tx.id}",
                    "sales_id": w_tx.id, # Using order ID as sales_id
                    "transaction_id": w_tx.id,
                    "inv_date": w_tx.inv_date.strftime("%Y-%m-%d"),
                    "inv_no": w_tx.inv_no,
                    "customer_name": customer.name,
                    "customer_phone": customer.phone,
                    "customer_type": customer.customer_type,
                    "total_amount": w_tx.total_amount,
                    "total_paid": w_tx.total_paid,
                    "branch_name": "Wholesale",
                    "type": "Wholesale Finance",
                    "finance_id": w_tx.finance_id,
                    "finance_name": getItemNameById(finance_table, w_tx.finance_id) if w_tx.finance_id else "Wholesale Finance",
                    "bank_name": "-",
                    "amount": remaining_w,
                    "cashback": 0,
                    "receipt": w_tx.finance_amount,
                    "claim_status": format_badge(
                        w_tx.collect_status,
                        mapping={
                            'pending': 'badge text-bg-info',
                            'claimed': 'badge text-bg-success',
                            'partial': 'badge text-bg-warning',
                            'rejected': 'badge text-bg-danger',
                            'complete': 'badge text-bg-success'
                        },
                        label_mapping={
                            'pending': 'Pending',
                            'claimed': 'Claimed',
                            'partial': 'Partial',
                            'rejected': 'Rejected',
                            'complete': 'Complete'
                        }
                    ),
                    "is_collect": 1 if w_tx.collect_status in ['claimed', 'complete'] else 0,
                    "is_checked": is_checked_w,
                    "charges": w_tx.charges,
                    "sales_status": w_tx.sales_status if w_tx.sales_status else 'approved',
                    "rejected_remarks": w_tx.rejected_remarks if hasattr(w_tx, 'rejected_remarks') else '',
                    "branch_id": 0, # Wholesale orders don't have branch_id currently
                    "row_type": "wholesale_finance",
                    "raw_claim_status": w_tx.collect_status,
                })

    return JsonResponse({'data': data})

def should_show_charge(tx, f_type, finance_id, session_branch_id):
    """
    Determines if a charge associated with a transaction (finance/card) should be displayed
    based on the current filter view (f_type), the specific filter ID (finance_id),
    and the branch restriction.
    """
    # 🔹 Restriction: Only show charges for the current branch
    if tx.branch_id != session_branch_id:
        return False

    if tx.payment_type not in ['finance', 'card']:
        return False

    if (tx.charges or 0) <= 0:
        return False

    # 🔹 CASE 1: BANK view (Filtering charges deposited into a specific bank)
    if f_type == 'bank' and tx.charge_mode == 'bank':
        if finance_id:
            return int(tx.charge_bank_id) == int(finance_id)
        return True

    # 🔹 CASE 2: FINANCE/CARD view (Filtering charges by original transaction type)
    if f_type == tx.payment_type:
        # If a specific finance provider/card is filtered
        if finance_id:
            if tx.payment_type == 'finance' and tx.finance_id != int(finance_id):
                return False
            if tx.payment_type == 'card' and tx.card_id != int(finance_id):
                return False
        return True

    return False



from claim_collect_upgrade.models import *
from django.db import transaction as db_transaction
from decimal import Decimal
from decimal import Decimal
from django.db.models import F
from django.http import JsonResponse
import json
def add_collection(request):
    if request.method != 'POST':
        return JsonResponse({'message': 'Invalid request'}, status=400)

    role_id = request.session.get('role_id')
    has_access, error_message = check_user_access(role_id, 'collection', "create")
    if not has_access:
        return JsonResponse({
            'message': 'permission',
            'error_message': 'You do not have permission to add the collection'
        })

    try:
        # ───────────────────── Session & Request Data ─────────────────────
        company_id     = request.session.get('company_id')
        branch_id      = request.session.get('branch_id')
        user_id        = request.session.get('user_id')
        fyf_name       = request.session.get('fyf')
        financial_year = calculate_financial_year(fyf_name)

        from_date    = request.POST.get('from_date')
        to_date      = request.POST.get('to_date')
        receipt_no   = request.POST.get('receipt_no') or None
        receipt_date = request.POST.get('receipt_date') or None
        finance_id   = request.POST.get('finance_id') or 0
        bank_id      = request.POST.get('bank_id') or 0
        f_type       = request.POST.get('f_type') or 'finance'

        total_selected_amt = Decimal(str(request.POST.get('total_amount') or 0))
        actual_receipt_amt = Decimal(str(request.POST.get('debit_note') or 0))
        remarks = request.POST.get('description')

        now = timezone.localtime(timezone.now())

        items = json.loads(request.POST.get('items') or '[]')
        if not items:
            return JsonResponse({'message': 'warning', 'error_message': 'No items added'})

        # ───────────────────── Generate Collection No ─────────────────────
        inv_no = generate_serial_number(
            model=tm_collection_table,
            number_field='collection_no',
            financial_year_field='current_fy',
            financial_year=financial_year,
            branch_id=branch_id,
            prefix=""
        )

        print(f"[COLLECTION] Creating collection {inv_no} | "
              f"Total={total_selected_amt} Receipt={actual_receipt_amt}")

        with db_transaction.atomic():

            main = tm_collection_table.objects.create(
                company_id=company_id,
                branch_id=branch_id,
                current_fy=financial_year,
                finance_id=finance_id,
                bank_id=bank_id,
                f_type=f_type,
                collection_no=inv_no,
                date=now.date(),
                time=now.time(),
                from_date=from_date,
                to_date=to_date,
                receipt_no=receipt_no,
                receipt_date=receipt_date,
                total_amount=total_selected_amt,
                receipt=actual_receipt_amt,
                remarks=remarks,
                created_on=now,
                updated_on=now,
                created_by=user_id,
                employee_id=user_id,
                updated_by=user_id,
                status=1,
                is_active=1,
            )

            distribution_ratio = Decimal('0.00')
            if total_selected_amt > 0:
                distribution_ratio = actual_receipt_amt / total_selected_amt

            print(f"[COLLECTION] Distribution ratio: {distribution_ratio}")

            # ───────────────────── Item Loop ─────────────────────
            for idx, item in enumerate(items, start=1):

                original_item_amt = Decimal(str(item.get('amount') or 0))
                item_share = (original_item_amt * distribution_ratio).quantize(Decimal('0.01'))

                print(f"[ITEM {idx}] TX={item.get('transaction_id')} "
                      f"RowType={item.get('row_type')} "
                      f"Original={original_item_amt} Share={item_share}")

                tx_collection_table.objects.create(
                    company_id=company_id,
                    current_fy=financial_year,
                    tm_collection_id=main.id,
                    branch_id=branch_id,
                    sales_id=item['sales_id'],
                    supply_branch_id=item['branch_id'],
                    inv_no=item['price_no'],
                    inv_date=item['inv_date'],
                    f_type=item['f_type'],
                    finance_id=item['finance_id'],
                    row_type=item['row_type'],
                    amount=item_share,
                    transaction_id=item['transaction_id'],
                    created_on=now,
                    updated_on=now,
                    created_by=user_id,
                    updated_by=user_id,
                    status=1,
                    is_active=1
                )

                transaction_id = item.get('transaction_id')
                if not transaction_id:
                    continue

                target_tx = transaction_table.objects.filter(id=transaction_id).first()
                if not target_tx:
                    print(f"[WARN] Transaction {transaction_id} not found")
                    continue

                # ───────────── Regular Transaction ─────────────
                if item['row_type'] == 'transaction':

                    already_collected = Decimal(str(target_tx.collect_amount or 0))
                    full_target_amt   = Decimal(str(target_tx.amount or 0))
                    new_total         = already_collected + item_share

                    if new_total >= full_target_amt:
                        status_text = 'claimed'
                        is_collect  = 1
                    elif new_total > 0:
                        status_text = 'partial'
                        is_collect  = 0
                    else:
                        status_text = 'pending'
                        is_collect  = 0

                    updates = {
                        'collect_amount': new_total,
                        'collect_status': status_text,
                        'is_collect': is_collect,
                        'collected_on': now,
                        'updated_on': now,
                        'updated_by': user_id
                    }

                    # 🔁 Exchange handling
                    if target_tx.payment_type == 'exchange':
                        actual_share = item_share if item_share > 0 else full_target_amt
                        prev_exchange = Decimal(str(target_tx.exchange_claim or 0))
                        new_exchange  = prev_exchange + actual_share

                        updates['collect_amount']  = full_target_amt
                        updates['collect_status']  = 'claimed'
                        updates['is_collect']      = 1
                        updates['exchange_claim']  = new_exchange
                        updates['exchange_status'] = 'claimed'

                        print(f"[EXCHANGE] TX={transaction_id} "
                              f"Prev={prev_exchange} Added={actual_share} New={new_exchange}")

                    transaction_table.objects.filter(id=transaction_id).update(**updates)

                    print(f"[TX UPDATE] TX={transaction_id} "
                          f"Collected {already_collected} → {new_total} / {full_target_amt} "
                          f"Status={status_text}")

                # ───────────── Charge Collection ─────────────
                elif item['row_type'] == 'charge':

                    already_charge = Decimal(str(target_tx.charge_amount_collect or 0))
                    full_charge    = Decimal(str(target_tx.charges or 0))
                    new_charge     = already_charge + item_share

                    if new_charge >= full_charge:
                        status_text = 'claimed'
                    elif new_charge > 0:
                        status_text = 'partial'
                    else:
                        status_text = 'pending'

                    transaction_table.objects.filter(id=transaction_id).update(
                        charge_amount_collect=new_charge,
                        charge_status=status_text,
                        charge_collect_on=now,
                        updated_on=now,
                        updated_by=user_id
                    )

                    print(f"[CHARGE UPDATE] TX={transaction_id} "
                          f"Collected {already_charge} → {new_charge} / {full_charge} "
                          f"Status={status_text}")

                # ───────────── Wholesale Finance Collection ─────────────
                elif item['row_type'] == 'wholesale_finance':
                    w_tx = wholesale_sales_order_table.objects.filter(id=transaction_id).first()
                    if w_tx:
                        already_collected = Decimal(str(w_tx.collected_amount or 0))
                        full_amt = Decimal(str(w_tx.finance_amount or 0))
                        new_total = already_collected + item_share

                        if new_total >= full_amt:
                            status_text = 'claimed'
                            is_coll = 1
                        elif new_total > 0:
                            status_text = 'partial'
                            is_coll = 0
                        else:
                            status_text = 'pending'
                            is_coll = 0

                        wholesale_sales_order_table.objects.filter(id=transaction_id).update(
                            collected_amount=new_total,
                            collect_status=status_text,
                            is_collected=is_coll,
                            collected_on=now,
                            collected_by=user_id,
                            updated_on=now,
                            updated_by=user_id
                        )
                        print(f"[WHOLESALE UPDATE] TX={transaction_id} "
                              f"Collected {already_collected} → {new_total} / {full_amt} "
                              f"Status={status_text}")

        print(f"[COLLECTION SUCCESS] Collection {inv_no} saved successfully")
        return JsonResponse({'message': 'success'})

    except Exception as e:
        print(f"[CRITICAL ERROR][COLLECTION] {str(e)}")
        return JsonResponse({'message': 'exception', 'error': str(e)}, status=500)


def ajax_collection_view(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)
    from_date       = request.POST.get('from_date')
    to_date         = request.POST.get('to_date')

    has_access, error_message = check_user_access(role_id, 'collection', "read")    
    if not has_access:
        return JsonResponse({
            'message': 'permission', 
            'error_message': 'You do not have permission to view the collection details'
        })

    # 🔹 Build query
    query = Q(status=1, branch_id=branch_id, current_fy=financial_year)
    if from_date and to_date:
        query &= Q(date__range=[from_date, to_date])

    data = list(selectList(tm_collection_table, query).values())

    formatted = []
    for index, item in enumerate(data):
        # 🔹 Finance / Bank name logic
        if item.get('f_type') == 'bank':
            name = getItemNameById(bank_table, item.get('finance_id')) if item.get('finance_id') else '-'
        else:
            # Use finance_table for finance/card
            name = getItemNameById(finance_table, item.get('finance_id')) if item.get('finance_id') else '-'

        formatted.append({
            'id': index + 1,
            'action': (
                '<div class="d-flex gap-1 justify-content-center align-items-center">'
                '<button type="button" onclick="edit_data(\'{}\')" '
                'class="btn btn-outline-success btn-xs p-1" title="Edit">'
                '<i class="fas fa-edit"></i></button>'
                '<button type="button" onclick="delete_data(\'{}\')" '
                'class="btn btn-outline-danger btn-xs p-1" title="Delete">'
                '<i class="fas fa-trash-alt"></i></button>'
                '</div>'
            ).format(item['id'], item['id']),
            'receipt_no': item.get('receipt_no') or '-', 
            'receipt_date': format_date_month_year(item.get('receipt_date')) if item.get('receipt_date') else '-', 
            'total_amount': format_amount(item.get('total_amount')) if item.get('total_amount') else '-', 
            'debit': format_amount(item.get('receipt')) if item.get('receipt') else '-', 
            'remarks': item.get('remarks') or '-',    
            'f_type': item.get('f_type', '-').title(),
            'finance_card': name,
            'status': (
                '<span class="badge text-bg-success">Active</span>' 
                if item.get('is_active') else 
                '<span class="badge text-bg-danger">Inactive</span>'
            )
        })

    return JsonResponse({'data': formatted})


from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt

@csrf_exempt
def ajax_load_finance(request):
    if request.method != 'POST':
        return JsonResponse({'status': 'error', 'message': 'Invalid request'})

    f_type = request.POST.get('f_type')

    if not f_type:
        return JsonResponse({'status': 'error', 'message': 'Missing type'})

    if f_type == 'bank':
        is_ho = request.session.get('is_ho')
        branch_id = request.session.get('branch_id')
        
        if is_ho == 1:
            # HO: Show only non-default banks
            qs = bank_table.objects.filter(
                is_active=1,
                status=1,
                is_default=0
            ).order_by('name')
        else:
            # Branch: Show only the default bank linked to this branch
            branch = branch_table.objects.filter(id=branch_id).first()
            if branch and branch.bank_id:
                qs = bank_table.objects.filter(
                    id=branch.bank_id,
                    is_active=1,
                    status=1,
                    is_default=1
                ).order_by('name')
            else:
                qs = bank_table.objects.none()

        data = list(qs.values('id', 'name'))

    # 🔥 FINANCE / CARD / WALLET etc
    else:
        qs = finance_table.objects.filter(
            f_type=f_type,
            is_active=1,
            status=1
        ).order_by('name')

        data = list(qs.values('id', 'name'))

    return JsonResponse({
        'status': 'success',
        'data': data
    })

def update_collection(request):
    if request.method != 'POST':
        return JsonResponse({'message': 'Invalid request'}, status=400)

    role_id = request.session.get('role_id')
    tm_collect_id = request.POST.get('tm_collect_id') or None

    has_access, error_message = check_user_access(role_id, 'collection', "create")    
    if not has_access:
        return JsonResponse({'message': 'permission', 'error_message': 'You do not have permission to add the collection'})

    try:
        # ---------------------------
        # 1. Session & Request Data
        # ---------------------------
        company_id = request.session.get('company_id')
        branch_id = request.session.get('branch_id')
        user_id = request.session.get('user_id')
        fyf_name = request.session.get('fyf')
        financial_year = calculate_financial_year(fyf_name)

        receipt_no = request.POST.get('receipt_no') or None
        bank_id = request.POST.get('bank_id') or 0
        receipt_date = request.POST.get('receipt_date') or None
        total_selected_amt = Decimal(str(request.POST.get('total_amount') or 0.00))
        actual_receipt_amt = Decimal(str(request.POST.get('debit_note') or 0.00))
        remarks = request.POST.get('description')
        now = timezone.localtime(timezone.now())

        items = json.loads(request.POST.get('items') or '[]')
        if not items:
            return JsonResponse({'message': 'warning', 'error_message': 'No items added'})

        parent = select_row(tm_collection_table, {'id': tm_collect_id})

        # ---------------------------
        # 2. EDIT MODE → revert previous amounts
        # ---------------------------
        if tm_collect_id:
            old_items = tx_collection_table.objects.filter(tm_collection_id=tm_collect_id, is_active=1)
            for old_item in old_items:
                tx = transaction_table.objects.filter(id=old_item.transaction_id).first()
                if tx:
                    if old_item.row_type == 'transaction':
                        # revert previous transaction collection
                        new_collect = Decimal(str(tx.collect_amount or 0)) - Decimal(str(old_item.amount or 0))
                        full_amount = Decimal(str(tx.amount or 0))
                        if new_collect >= full_amount:
                            status_text = 'claimed'
                            is_collect_flag = 1
                        elif new_collect > 0:
                            status_text = 'partial'
                            is_collect_flag = 0
                        else:
                            status_text = 'pending'
                            is_collect_flag = 0

                        # 🔹 Exchange Specific Revert
                        if tx.payment_type == 'exchange':
                            new_ex_claim = Decimal(str(tx.exchange_claim or 0)) - Decimal(str(old_item.amount or 0))
                            # "No partial concept"
                            ex_status = 'complete' if new_ex_claim > 0 else 'pending'
                            
                            tx.exchange_claim = new_ex_claim
                            tx.exchange_status = ex_status
                            print(ex_status, tx.payment_type, new_ex_claim, old_item.amount)    

                            # Revert Child Sales Item (Exchange)
                            if tx.reference_no:
                                child_items = child_sales_order_table.objects.filter(
                                    tm_sales_id=tx.tm_sales_id,
                                    imei_no=tx.reference_no,
                                    is_active=1
                                )
                                for child in child_items:
                                    child.claim_amount = Decimal(str(child.claim_amount or 0)) - Decimal(str(old_item.amount or 0))
                                    child.save()

                        tx.collect_amount = new_collect
                        tx.collect_status = status_text
                        tx.is_collect = is_collect_flag

                    elif old_item.row_type == 'charge':
                        # revert previous charge collection
                        new_charge_collect = Decimal(str(tx.charge_amount_collect or 0)) - Decimal(str(old_item.amount or 0))
                        full_charge_amt = Decimal(str(tx.charges or 0))
                        if new_charge_collect >= full_charge_amt:
                            charge_status_text = 'claimed'
                        elif new_charge_collect > 0:
                            charge_status_text = 'partial'
                        else:
                            charge_status_text = 'pending'

                        tx.charge_amount_collect = new_charge_collect
                        tx.charge_status = charge_status_text

                    elif old_item.row_type == 'wholesale_finance':
                        # revert previous wholesale finance collection
                        w_tx = wholesale_sales_order_table.objects.filter(id=old_item.transaction_id).first()
                        if w_tx:
                            new_collect = Decimal(str(w_tx.collected_amount or 0)) - Decimal(str(old_item.amount or 0))
                            full_amount = Decimal(str(w_tx.finance_amount or 0))
                            
                            if new_collect >= full_amount:
                                status_text = 'claimed'
                                is_coll = 1
                            elif new_collect > 0:
                                status_text = 'partial'
                                is_coll = 0
                            else:
                                status_text = 'pending'
                                is_coll = 0
                            
                            w_tx.collected_amount = new_collect
                            w_tx.collect_status = status_text
                            w_tx.is_collected = is_coll
                            w_tx.updated_on = now
                            w_tx.updated_by = user_id
                            w_tx.save()

                    tx.updated_on = now
                    tx.updated_by = user_id
                    tx.save()

            # Mark old collection items inactive
            tx_collection_table.objects.filter(tm_collection_id=tm_collect_id).update(status=0, is_active=0)

        # ---------------------------
        # 3. Distribute new amounts
        # ---------------------------
        distribution_ratio = Decimal('0.00')
        if total_selected_amt > 0:
            distribution_ratio = actual_receipt_amt / total_selected_amt

        for item in items:
            original_item_amt = Decimal(str(item.get('amount') or 0))
            item_share = (original_item_amt * distribution_ratio).quantize(Decimal('0.01'))

            # 3a. Create new collection record
            tx_collection_table.objects.create(
                company_id=company_id,
                current_fy=financial_year,
                tm_collection_id=tm_collect_id,
                branch_id=branch_id,
                sales_id=item['sales_id'],
                supply_branch_id=item['branch_id'],
                inv_no=item['price_no'],
                inv_date=item['inv_date'],
                f_type=item['f_type'],
                finance_id=item['finance_id'],
                amount=item_share,
                transaction_id=item['transaction_id'],
                row_type=item['row_type'],
                created_on=now,
                updated_on=now,
                created_by=user_id,
                updated_by=user_id,
                status=1,
                is_active=1
            )

            # 3b. Update transaction_table safely
            transaction_id = item.get('transaction_id')
            if transaction_id:
                target_tx = transaction_table.objects.filter(id=transaction_id).first()
                if not target_tx:
                    continue

                if item['row_type'] == 'transaction':
                    # Regular transaction collection
                    new_total_collected = Decimal(str(target_tx.collect_amount or 0)) + item_share
                    full_target_amt = Decimal(str(target_tx.amount or 0))

                    if new_total_collected >= full_target_amt:
                        status_text = 'claimed'
                        is_collect_flag = 1
                    elif new_total_collected > 0:
                        status_text = 'partial'
                        is_collect_flag = 0
                    else:
                        status_text = 'pending'
                        is_collect_flag = 0

                    target_tx.collect_amount = new_total_collected
                    target_tx.collect_status = status_text
                    target_tx.is_collect = is_collect_flag
                    target_tx.collected_on = now
                    
                    # 🔹 Exchange Specific Update
                    if target_tx.payment_type == 'exchange':
                        new_exchange_claim = Decimal(str(target_tx.exchange_claim or 0)) + item_share
                        # "No partial concept, once add it was claimed"
                        ex_status = 'claimed' if new_exchange_claim > 0 else 'pending'
                        
                        target_tx.exchange_claim = new_exchange_claim
                        target_tx.exchange_status = ex_status

                        # Update Child Sales Item (Exchange)
                        if target_tx.reference_no:
                            child_items = child_sales_order_table.objects.filter(
                                tm_sales_id=target_tx.tm_sales_id,
                                imei_no=target_tx.reference_no,
                                is_active=1
                            )
                            for child in child_items:
                                child.claim_amount = Decimal(str(child.claim_amount or 0)) + item_share
                                child.updated_on = now
                                child.updated_by = user_id
                                child.save()

                    target_tx.updated_on = now
                    target_tx.updated_by = user_id
                    target_tx.save()

                elif item['row_type'] == 'charge':
                    # Charge collection
                    new_charge_collected = Decimal(str(target_tx.charge_amount_collect or 0)) + item_share
                    full_charge_amt = Decimal(str(target_tx.charges or 0))

                    if new_charge_collected >= full_charge_amt:
                        charge_status_text = 'claimed'
                    elif new_charge_collected > 0:
                        charge_status_text = 'partial'
                    else:
                        charge_status_text = 'pending'

                    target_tx.charge_amount_collect = new_charge_collected
                    target_tx.charge_status = charge_status_text
                    target_tx.charge_collect_on = now
                    target_tx.updated_on = now
                    target_tx.updated_by = user_id
                    target_tx.save()

                elif item['row_type'] == 'wholesale_finance':
                    # Wholesale Finance collection update
                    w_tx = wholesale_sales_order_table.objects.filter(id=transaction_id).first()
                    if w_tx:
                        new_total_collected = Decimal(str(w_tx.collected_amount or 0)) + item_share
                        full_amt = Decimal(str(w_tx.finance_amount or 0))

                        if new_total_collected >= full_amt:
                            status_text = 'claimed'
                            is_coll = 1
                        elif new_total_collected > 0:
                            status_text = 'partial'
                            is_coll = 0
                        else:
                            status_text = 'pending'
                            is_coll = 0

                        w_tx.collected_amount = new_total_collected
                        w_tx.collect_status = status_text
                        w_tx.is_collected = is_coll
                        w_tx.collected_on = now
                        w_tx.collected_by = user_id
                        w_tx.updated_on = now
                        w_tx.updated_by = user_id
                        w_tx.save()

                print(f"DEBUG: TX {transaction_id} [{item['row_type']}] -> Added: {item_share}")

        # ---------------------------
        # 4. Update parent collection
        # ---------------------------
        if parent:
            parent.receipt_date = receipt_date
            parent.total_amount = total_selected_amt
            parent.receipt = actual_receipt_amt
            parent.remarks = remarks
            parent.updated_on = now
            parent.updated_by = user_id
            parent.bank_id = bank_id
            parent.save()

        return JsonResponse({'message': 'success'})

    except Exception as e:
        print(f"CRITICAL ERROR: {str(e)}")
        return JsonResponse({'message': 'exception', 'error': str(e)}, status=500)

# *********************************************************************************************************************************
# 🔹 APPROVAL WORKFLOW ENDPOINTS
# *********************************************************************************************************************************

def ajax_pending_sales_approvals(request):
    """Fetch sales orders with pending approval status for off-canvas cards."""
    branch_id = request.session.get('branch_id')
    fyf_name = request.session.get('fyf')
    financial_year = calculate_financial_year(fyf_name)

    # Filter sales orders where sales_status is 'pending'
    orders = sales_order_table.objects.filter(
        
        current_fy=financial_year,
        status=1,
        is_active=1,
        sales_status='pending'
    ).order_by('-created_on')

    formatted = []
    for order in orders:
        formatted.append({
            'id': order.id,
            'branch_name': getItemNameById(branch_table, order.branch_id),
            'outward_no': order.inv_no, # Using inv_no as reference
            'outward_date': order.inv_date.strftime("%d-%m-%Y") if order.inv_date else '-',
            'total_qty': order.total_quantity,
            'total_amount': format_amount(order.total_amount),
            'status': order.sales_status.title() if order.sales_status else 'Pending'
        })

    return JsonResponse({'data': formatted})


def get_sales_transaction_items(request):
    """Fetch all details for a specific sales order modal including header, items, and payments."""
    po_id = request.POST.get('po_id')
    branch_id = request.session.get('branch_id')

    # 1. Fetch Header Details (Sales Order Master)
    master = sales_order_table.objects.filter(id=po_id, status=1).first()
    header_info = {
        'inv_no': master.inv_no if master else '-',
        'inv_date': master.inv_date.strftime("%d-%m-%Y") if master and master.inv_date else '-',
        'customer_name': master.customer_name if master else '-',
        'customer_phone': master.customer_phone if master else '-',
        'total_amount': format_amount(master.total_amount) if master else '0.00',
        'branch_name': getItemNameById(branch_table, master.branch_id) if master else '-'
    }

    # 2. Fetch Payment Transactions
    transactions = transaction_table.objects.filter(
        tm_sales_id=po_id,
        # branch_id=branch_id,
        status=1
    )
    
    pay_details = []
    for tx in transactions:
        # Resolve payment source name
        source_name = "-"
        bank_name = "-"
        
        if tx.payment_type == 'bank':
             source_name = getItemNameById(bank_table, tx.bank_id)
             bank_name = source_name  # For bank type, bank_name is the same
        elif tx.payment_type == 'card':
             source_name = getItemNameById(finance_table, tx.card_id)
             # Get associated bank for card
             if tx.bank_id:
                 bank_name = getItemNameById(bank_table, tx.bank_id)
        elif tx.payment_type == 'finance':
             source_name = getItemNameById(finance_table, tx.finance_id)
             # Get associated bank for finance
             if tx.bank_id:
                 bank_name = getItemNameById(bank_table, tx.bank_id)
        elif tx.payment_type == 'exchange':
             source_name = tx.reference_no if tx.reference_no else 'Exchange'

        pay_details.append({
            'payment_type': tx.payment_type.title(),
            'source': source_name,
            'bank_name': bank_name,
            'amount': format_amount(tx.amount),
            'charges': format_amount(tx.charges) if tx.charges else '0.00',
            'cashback': format_amount(tx.cashback) if tx.cashback else '0.00',
            'charge_mode': tx.charge_mode if hasattr(tx, 'charge_mode') and tx.charge_mode else '-',
            'reference': tx.reference_no or '-',
            'date': tx.date.strftime("%d-%m-%Y") if tx.date else '-'
        })

    # 3. Fetch Product Items
    child_items = child_sales_order_table.objects.filter(
        tm_sales_id=po_id,
        status=1
    )
    
    item_details = []
    for item in child_items:
        item_details.append({
            '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 or '-',
            'rate': format_amount(item.rate),
            'quantity': item.quantity,
            'amount': format_amount(item.amount)
        })

    return JsonResponse({
        'header': header_info,
        'transactions': pay_details,
        'items': item_details
    })


def approve_sales_order(request):
    """Update sales order status to 'approved'."""
    order_id = request.POST.get('id')
    user_id = request.session.get('user_id')
    now = timezone.now()

    try:
        sales_order_table.objects.filter(id=order_id).update(
            sales_status='approved',
            updated_on=now,
            updated_by=user_id
        )
        return JsonResponse({'status': 'success', 'message': 'Sales order approved successfully.'})
    except Exception as e:
        return JsonResponse({'status': 'error', 'message': str(e)})


def reject_sales_order(request):
    """Update sales order status to 'rejected' with reason."""
    order_id = request.POST.get('id')
    remarks = request.POST.get('remarks')
    user_id = request.session.get('user_id')
    now             = timezone.localtime(timezone.now())

    try:
        with db_transaction.atomic():
            # 1. Update Sales Order
            sales_order_table.objects.filter(id=order_id).update(
                sales_status='rejected',
                rejected_remarks=remarks,
                rejected_on=now,
                rejected_by=user_id,
                updated_on=now,
                updated_by=user_id
            )

            # 2. Update all related transactions and their statuses
            transaction_table.objects.filter(tm_sales_id=order_id).update(
                collect_status='rejected',
                charge_status='rejected',
                exchange_status='rejected',
                updated_on=now,
                updated_by=user_id
            )

            # 3. Update child sales items (for claim/upgrade rejection if needed)
            child_sales_order_table.objects.filter(tm_sales_id=order_id).update(
                upgrade_status='rejected',
                upgrade_rejected_on=now,
                upgrade_rejected_by=user_id,
                upgrade_rejected_remarks=remarks,
                updated_on=now,
                updated_by=user_id
            )

        return JsonResponse({'status': 'success', 'message': 'Sales order rejected successfully.'})

    except Exception as e:
        return JsonResponse({'status': 'error', 'message': str(e)})


# ==========================================
# EXCHANGE COLLECTION WRAPPERS
# ==========================================

from django.shortcuts import render, HttpResponseRedirect

def exchange_collection(request):
    """Renders the Exchange Collection list view."""
    if "user_id" in request.session:
        user_type = request.session.get("user_type")
        if user_type == "stores":
            # Reusing the structure but pointing to new template
            return render(request, "exchange_collection/details.html")
        else:
            return HttpResponseRedirect("/")
    else:
        return HttpResponseRedirect("/")

def exchange_collection_add(request):
    """Renders the Exchange Collection Add view."""
    if "user_id" in request.session:
        user_type = request.session.get("user_type")
        if user_type == "stores":
            branch_id = request.session.get('branch_id')
            fyf_name = request.session.get('fyf')
            financial_year = calculate_financial_year(fyf_name)
            is_ho = request.session.get('is_ho')
            
            # Generate new collection number
            claim_no = generate_serial_number(
                model=tm_collection_table,
                number_field='collection_no',
                financial_year_field='current_fy',
                financial_year=financial_year,
                branch_id=branch_id,
                prefix=""
            )
            
            # Banks for receipt
            if is_ho == 1:
                bank = bank_table.objects.filter(is_default=0, status=1).order_by('name')
            else:
                bank = bank_table.objects.filter(is_default=1, status=1).order_by('name')
            
            return render(request, "exchange_collection/add.html", {
                "claim_no": claim_no,
                "bank": bank
            })
        else:
            return HttpResponseRedirect("/")
    else:
        return HttpResponseRedirect("/")

def exchange_collection_edit(request):
    """Renders the Exchange Collection Edit view."""
    if "user_id" in request.session:
        user_type = request.session.get("user_type")
        is_ho = request.session.get('is_ho')
        if user_type == "stores":
            branch_id = request.session.get('branch_id')
            
            try:
                k = request.GET.get('id')
                if not k:
                    return HttpResponseRedirect("/exchange-collection")
                id_ = base64.b64decode(k).decode('utf-8')
            except:
                return HttpResponseRedirect("/exchange-collection")

            collect_obj = get_object_or_404(tm_collection_table, id=id_)
            if is_ho == 1:
                bank = bank_table.objects.filter(is_default=0, status=1).order_by('name')
            else:
                bank = bank_table.objects.filter(is_default=1, status=1).order_by('name')

            # Prepare context compatible with template logic
            collect_data = {
                "id": collect_obj.id,
                "receipt_no": collect_obj.receipt_no if collect_obj.receipt_no else "",
                "receipt_date": collect_obj.receipt_date.strftime("%Y-%m-%d") if collect_obj.receipt_date else "",
                "bank_id": collect_obj.bank_id,
                "total_amount": collect_obj.total_amount,
                "receipt": collect_obj.receipt,
                # Enforce exchange type so edit screen knows what to load
                "f_type": "exchange", 
                "finance_id": 0
            }
            
            return render(request, "exchange_collection/edit.html", {
                "collect": collect_data,
                "bank": bank
            })
        else:
            return HttpResponseRedirect("/")
    else:
        return HttpResponseRedirect("/")
