from django.shortcuts import render

import json
from django.conf import settings
from django.shortcuts import render
from financial_year.models import *
from common.models import *
from masters.models import *
from financial_year.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,JsonResponse,HttpResponseRedirect
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 *


#```````````````````````````````````````````````````````````**FINANCIAL YEAR**````````````````````````````````````````````````````````````````````````````````


def financial_year(request):
    if 'user_id' in request.session:
        user_type = request.session.get('user_type')
        if user_type == 'admin' or user_type == 'stores':
            cmpy = select_row(company_table, {'id': 1})  #to get the single row data
            return render(request, 'financial.html', {'company': cmpy})
        else:
            return HttpResponseRedirect("/")
    else:
        return HttpResponseRedirect("/")
    


def financial_year_view(request):  
    role_id = request.session.get('role_id')
    user_type = request.session.get('user_type')
    company_id = request.session.get('company_id')
    has_access = check_user_access(role_id, 'financial_year', "read")

    if not has_access:
        return JsonResponse({'message': 'warning', 'error_message': 'You do not have permission to view financial year details'})
    
    current_fy = None
    if company_id:
        company = select_row(company_table, {'id': company_id})
        if company:
            current_fy = company.current_fy

    data = list(selectList(financial_year_table, {'status': 1, 'id':current_fy}, order_by='year').values())

    formatted = []
    for index, item in enumerate(data):
        action_button = ''

        # Only allow activation button if not current FY
        if current_fy != item['id']:
            action_button = (
                '<button type="button" onclick="activate_year(\'{}\')" class="btn btn-warning btn-sm p-1">'
                '<i class="fas fa-power-off me-0"></i>&nbsp;Activate</button>'.format(item['id'])
            )

        formatted.append({
            'id': index + 1,
            'action': action_button,
            'year': item['year'] if item['year'] else '-', 
            'category': item['name'] if item['name'] else '-', 
            'from': format_date_month_year(item['from_date']) if item['from_date'] else '-', 
            'to': format_date_month_year(item['to_date']) if item['to_date'] else '-', 
            'fystatus': item['fy_status'] if item['fy_status'] else '-', 
        })


    return JsonResponse({'data': formatted})



def financial_add(request):
    if request.method == 'POST':
        try:
            user_id = request.session.get('user_id')           
            role_id = request.session.get('role_id')
            has_access = check_user_access(role_id, 'financial_year', "create")

            if not has_access:
                return JsonResponse({'message': 'warning', 'error_message': 'You do not have permission to create financial year details'})
            
            form = FinanceForm(request.POST, request.FILES)
            if form.is_valid():
                category = form.save(commit=False)
                
                from_date = request.POST.get('from_date')
                to_date = request.POST.get('to_date')
                fy_status = request.POST.get('year_status', 'Active')
                migration_status = request.POST.get('migrations')
                name = request.POST.get('name')

                # Check for existing records
                if financial_year_table.objects.filter(name=name, status=1).exists():
                    return JsonResponse({'message': 'exception', 'error': 'Name already exists'}, status=409)
                
                if financial_year_table.objects.filter(from_date=from_date, to_date=to_date).exists():
                    return JsonResponse({'message': 'exception', 'error': 'Date already exists'}, status=409)

                # Set other attributes
                category.year = request.POST.get('year')
                category.name = name
                category.from_date = from_date
                category.to_date = to_date
                category.fy_status = fy_status if fy_status else 'Active'
                category.status = 1
                category.migration_status = migration_status if migration_status else 'pending'
                category.is_active = 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()
                return JsonResponse({'message': 'success'})
            else:
                errors = form.errors.as_json()
                return JsonResponse({'message': 'form_error', 'errors': errors}, status=400)

        except Exception as e:
            # Log the exception here if needed
            return JsonResponse({'message': 'exception', 'error': str(e)}, status=500)



def financial_edit(request):
    if request.method == "POST":
        data = financial_year_table.objects.filter(id=request.POST.get('id'))    
    return JsonResponse(data.values()[0])




def financial_update(request):
    if request.method == "POST":
        try:
            category_id = request.POST.get('id')
            category = financial_year_table.objects.get(id=category_id)
            role_id = request.session.get('role_id')
            has_access, error_message = check_user_access(role_id, 'financial_year', "update")

            if not has_access:
                return JsonResponse({'message': 'warning', 'error_message': 'You do not have permission to update financial year details'})
            
            form = FinanceForm(request.POST, request.FILES, instance=category)
            if form.is_valid():
                updated_category = form.save(commit=False)
                year = request.POST.get('year')
                name = request.POST.get('name')
                from_date = request.POST.get('from_date')
                to_date = request.POST.get('to_date')
                year_status = request.POST.get('year_status')
                is_active = request.POST.get('is_active')

                updated_category.name = name            
                updated_category.from_date = from_date            
                updated_category.to_date = to_date            
                updated_category.fy_status = year_status            
                updated_category.is_active = is_active            
                updated_category.year = year
                updated_category.updated_by = request.session.get('user_id')
                updated_category.updated_on = format_datetime(timezone.now())
                updated_category.save()
                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 financial_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, 'financial_year', "delete")

        if not has_access:
            return JsonResponse({'message': 'warning', 'error_message': 'You do not have permission to delete financial year details'})   
        
        try:
            updated = financial_year_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'})
 


 
 
from django.views.decorators.csrf import csrf_exempt
from django.http import JsonResponse

@csrf_exempt
def activate_financial_year(request):
    if request.method == 'POST':
        user_id = request.session.get('user_id')
        company_id = request.session.get('company_id')
        new_fyf_id = request.POST.get('fyf_id')
        

        if not new_fyf_id:
            return JsonResponse({'status': 'error', 'message': 'No FYF ID provided'}, status=400)

        company = company_table.objects.filter(id=company_id).first()
        if company:
            company.current_fy = new_fyf_id
            company.save()

            try:
                fyf_obj = financial_year_table.objects.get(id=new_fyf_id)
                fyf_name = fyf_obj.name
                fyf_obj.is_current = 1
                fyf_obj.save()
                request.session['fyf'] = fyf_name

                if fyf_name and '-' in fyf_name:
                    fyf_start, fyf_end = fyf_name.split('-')
                    request.session['fyf_start'] = fyf_start.strip()
                    request.session['fyf_end'] = fyf_end.strip()

                financial_year_table.objects.exclude(id=new_fyf_id).update(is_current=0)

            except financial_year_table.DoesNotExist:
                pass

            return JsonResponse({'status': 'success', 'message': 'Financial year activated successfully'})

        else:
            return JsonResponse({'status': 'error', 'message': 'Company not found'}, status=400)

    return JsonResponse({'status': 'error', 'message': 'Invalid request method'}, status=405)
