from django.shortcuts import render
import json
from decimal import Decimal

from django.conf import settings
from django.shortcuts import render
from expenses.models import *
from supplier.models import *
from masters.models import *
from supplier.forms import *
from masters.forms import *
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
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 ledger.views import create_ledger_master_and_opening_balance
from django.db import transaction


# ````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````


def store_supplier(request):
    if 'user_id' in request.session:
        user_type = request.session.get('user_type')
        if user_type == 'stores':
            branch_id = request.session.get('branch_id')
            brand = selectList(brand_table, order_by='name')
            branch = selectList(branch_table,{'is_ho':1}, order_by='name')
            category = selectList(category_table, order_by='name')
            employee = selectList(employee_table, {'branch_id':branch_id}, order_by='name')           
            return render(request, 'supplier.html', {'brand': brand,'category':category,'employee':employee,'branch':branch})
        else:
            return HttpResponseRedirect("/")
    else:
        return HttpResponseRedirect("/")
    


def supplier_view(request):  
    role_id = request.session.get('role_id')
    has_access, error_message = check_user_access(role_id, 'supplier', "read")

    if not has_access:
        return JsonResponse({'message': 'permission', 'error_message': 'You do not have permission to read supplier details'})
    
    branch_id = request.POST.get('branch_id')
    data = list(selectList(supplier_table).values())
    brand_id = request.POST.get('brand_id') or 0

    def build_brand_names(brand_id_value):
        if not brand_id_value:
            return '-'
        brand_ids = [bid.strip() for bid in str(brand_id_value).split(',') if bid.strip()]
        if not brand_ids:
            return '-'
        names = [getItemNameById(brand_table, bid) for bid in brand_ids]
        names = [name for name in names if name]
        return ', '.join(names) if names else '-'


    formatted = [
        {
            'id': index + 1,
            'action': '<button type="button" onclick="edit_data(\'{}\')" class="btn btn-outline-success btn-xs p-1"><i class="fas fa-edit"></i></button> \
                      <button type="button" onclick="delete_data(\'{}\')" class="btn btn-outline-danger btn-xs p-1"> <i class="fas fa-trash-alt"></i></button>'.format(item['id'], item['id']), 
            'store': getItemNameById(branch_table, item['branch_id'])  if item['branch_id'] else '-',             
            'name': item['name'] if item['name'] else '-', 
            'email': item['email'] if item['email'] else '-', 
            'phone': item['phone'] if item['phone'] else '-', 
            'mobile': item['mobile'] if item['mobile'] else '-', 
            'person': item['contact_person_name'] if item['contact_person_name'] else '-', 
            'city': item['city'] if item['city'] else '-', 
            'statecode': item['statecode'] if item['statecode'] else '-', 
            'gstin': item['gstin'] if item['gstin'] else '-', 
            'credit_days': item['credit_days'] if item['credit_days'] else '-', 
            'cin_number': item['cin_number'] if item['cin_number'] else '-', 
            'brands': build_brand_names(item.get('brand_id')),
            'global': '<span class="badge text-bg-success">Yes</span>' if item['is_global'] else '<span class="badge text-bg-danger">No</span>',
            'status': '<span class="badge text-bg-success">Active</span>' if item['is_active'] else '<span class="badge text-bg-danger">Inactive</span>' 
        } 
        for index, item in enumerate(data)
    ]
    return JsonResponse({'data': formatted})





def supplier_add(request):
    if request.method == 'POST':
        try:
            with transaction.atomic():
                user_id = request.session.get('user_id')           
                company_id = request.session.get('company_id')           
                role_id = request.session.get('role_id')
                fyf_name = request.session.get('fyf')
                financial_year = calculate_financial_year(fyf_name)

                has_access, error_message = check_user_access(role_id, 'supplier', "create")

                if not has_access:
                    return JsonResponse({'message': 'permission', 'error_message': 'You do not have permission to create Supplier details'})
                
                form = supplierform(request.POST, request.FILES)
                if form.is_valid():
                    category = form.save(commit=False)
                    name = request.POST.get('name')
                    email = request.POST.get('email')
                    phone = request.POST.get('phone')
                    mobile = request.POST.get('mobile')
                    person = request.POST.get('person')
                    cp_phone = request.POST.get('cp_phone')
                    city = request.POST.get('city')
                    state = request.POST.get('state')
                    pincode = request.POST.get('pincode')
                    address = request.POST.get('address')
                    remarks = request.POST.get('remarks')
                    is_global = request.POST.get('is_global') or 0
                    cin_number = request.POST.get('cin_number') or 0
                    gstin = request.POST.get('gstin') or 0
                    credit_days = request.POST.get('credit_days') or 0
                    statecode = request.POST.get('statecode') or 0
                    receivable = request.POST.get('receivable') or 0
                    payable = request.POST.get('payable') or 0
                    brand_id = request.POST.getlist('brand_id') or [] 
                    brand_id = ','.join(brand_id)



                    category.company_id = company_id
                    category.name = name
                    category.brand_id = brand_id
                    category.is_global = is_global
                    category.cin_number = cin_number
                    category.gstin = gstin
                    category.credit_days = credit_days
                    category.statecode = statecode
                    category.email = email
                    category.branch_id = 0
                    category.address_line1 = address
                    category.address_line2 = ''
                    category.city = city
                    category.state = state
                    category.pincode = pincode
                    category.phone = phone
                    category.mobile = mobile
                    category.contact_person_name = person
                    category.contact_person_phone = cp_phone
                    category.receivable = receivable
                    category.payable = payable
                    category.remarks = remarks
                    category.is_active = 1
                    category.status = 1
                    category.created_by = user_id
                    category.updated_by = user_id
                    category.created_on = format_datetime(timezone.now())
                    category.updated_on = format_datetime(timezone.now())
                    category.save()

                    ho_branch = branch_table.objects.filter(is_ho=1).first()
                    ho_branch_id = ho_branch.id if ho_branch else 0

                    if Decimal(str(payable)) != 0 or Decimal(str(receivable)) != 0:
                        create_ledger_master_and_opening_balance(
                            current_fy=financial_year,
                            branch_id=ho_branch_id,
                            master_id=category.id,
                            master_name=category.name,
                            ledger_type="supplier",
                            ledger_mode="supplier",
                            payable=payable,
                            receivable=receivable,
                            created_by=user_id,
                            updated_by=user_id,
                        )

                    customer = supplier_opening_table()
                    customer.company_id = company_id
                    customer.current_fy = financial_year
                    customer.supplier_id = category.id
                    customer.is_migrated = 0
                    customer.year = timezone.now().year
                    customer.date = format_date(timezone.now())
                    customer.time = format_time(timezone.now())
                    customer.credit = 0
                    customer.debit = 0
                    customer.is_active = 1
                    customer.status = 1
                    customer.created_by = 1
                    customer.updated_by = 1
                    customer.created_on =timezone.now()
                    customer.updated_on = timezone.now()
                    customer.save()
                    return JsonResponse({'message': 'success'})
                else:
                    errors = form.errors.as_json()
                    return JsonResponse({'message': 'form_error', 'errors': errors}, status=400)

        except Exception as e:
            return JsonResponse({'message': 'exception', 'error': str(e)}, status=500)



def supplier_edit(request):
    if request.method == "POST":
        data = supplier_table.objects.filter(id=request.POST.get('id'))    
    return JsonResponse(data.values()[0])



def supplier_update(request):
    if request.method == "POST":
        try:
            with transaction.atomic():
                category_id = request.POST.get('id')
                category = supplier_table.objects.get(id=category_id)
                form = supplierform(request.POST, request.FILES, instance=category)
                role_id = request.session.get('role_id')
                has_access, error_message = check_user_access(role_id, 'supplier', "update")

                if not has_access:
                    return JsonResponse({'message': 'permission', 'error_message': 'You do not have permission to update supplier details'})
                
                if form.is_valid():
                    updated_category = form.save(commit=False)
                    name = request.POST.get('name')
                    email = request.POST.get('email')
                    phone = request.POST.get('phone')
                    mobile = request.POST.get('mobile')
                    person = request.POST.get('person')
                    cp_phone = request.POST.get('cp_phone')
                    city = request.POST.get('city')
                    state = request.POST.get('state')
                    pincode = request.POST.get('pincode')
                    address = request.POST.get('address')
                    remarks = request.POST.get('remarks')
                    is_active = request.POST.get('is_active')
                    is_global = request.POST.get('is_global') or 0
                    cin = request.POST.get('cin_number') or 0
                    gstin = request.POST.get('gstin') or 0  
                    credit_days = request.POST.get('credit_days') or 0
                    statecode = request.POST.get('statecode') or 0
                    receivable = request.POST.get('receivable') or 0
                    payable = request.POST.get('payable') or 0
                    brand_id = request.POST.getlist('brand_id') or []
                    brand_id = ','.join(brand_id)



                    updated_category.name = name
                    updated_category.brand_id = brand_id
                    updated_category.receivable = receivable
                    updated_category.payable = payable
                    updated_category.cin_number = cin
                    updated_category.gstin = gstin
                    updated_category.credit_days = credit_days
                    updated_category.statecode = statecode
                    updated_category.is_global = is_global
                    updated_category.email = email
                    updated_category.address_line1 = address
                    updated_category.address_line2 = ''
                    updated_category.city = city
                    updated_category.state = state
                    updated_category.pincode = pincode
                    updated_category.phone = phone
                    updated_category.mobile = mobile
                    updated_category.contact_person_name = person
                    updated_category.contact_person_phone = cp_phone
                    updated_category.remarks = remarks        
                    updated_category.is_active = is_active            
                    updated_category.updated_by = request.session.get('user_id')
                    updated_category.updated_on = format_datetime(timezone.now())
                    updated_category.save()

                    fyf_name = request.session.get('fyf')
                    financial_year = calculate_financial_year(fyf_name)

                    ho_branch = branch_table.objects.filter(is_ho=1).first()
                    ho_branch_id = ho_branch.id if ho_branch else 0

                    if Decimal(str(payable)) != 0 or Decimal(str(receivable)) != 0:
                        create_ledger_master_and_opening_balance(
                            current_fy=financial_year,
                            branch_id=ho_branch_id,
                            master_id=category_id,
                            master_name=updated_category.name,
                            ledger_type="supplier",
                            ledger_mode="supplier",
                            payable=payable,
                            receivable=receivable,
                            created_by=request.session.get('user_id'),
                            updated_by=request.session.get('user_id'),
                            update=True
                        )

                    return JsonResponse({'message': 'success'})
                else:
                    errors = form.errors.as_json()
                    return JsonResponse({'message': 'error', 'errors': errors})
        except Exception as e:
            return JsonResponse({'message': 'exception', 'error': str(e)})



def supplier_delete(request):
    if request.method == 'POST':
        data_id = request.POST.get('id')   
        role_id = request.session.get('role_id')
        has_access, error_message = check_user_access(role_id, 'supplier', "delete")

        if not has_access:
            return JsonResponse({'message': 'permission', 'error_message': 'You do not have permission to delete supplier details'}) 
           
        try:
            updated = supplier_table.objects.filter(id=data_id).update(status=0)
            if updated:
                return JsonResponse({'message': 'yes'})
            else:
                return JsonResponse({'message': 'no such data'})
        except Exception as e:
            return JsonResponse({'message': 'exception', 'error': str(e)})

    return JsonResponse({'message': 'Invalid request method'})



# adjust import as needed

def check_supplier_name(request):
    name = request.GET.get('name')
    item_id = request.GET.get('id')
    store_id = request.GET.get('store_id')

    if name and store_id:
        query = selectList(supplier_table, {'name':name,'branch_id':store_id})

        if item_id:
            query = query.exclude(id=item_id)

        if query.exists():
            return JsonResponse({'exists': True})

    return JsonResponse({'exists': False})


