from django.shortcuts import render, redirect
from django.views import View
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib import messages
from django.contrib.messages import get_messages
from .models import GlobalSetting
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import permissions


class GlobalSettingsView(LoginRequiredMixin, View):
	def get(self, request):
		# Clear any unrelated messages (consume existing messages so previous success messages
		# from other pages don't show here). We'll re-add a controlled success message below
		# when requested via the updated flag.
		list(get_messages(request))

		# Fetch or create the singleton GlobalSetting record
		settings_obj, _ = GlobalSetting.objects.get_or_create(pk=1)

		# If we were redirected after save, show a single success message
		if request.GET.get('updated'):
			messages.success(request, 'Global settings updated.')

		context = {
			'cgst': settings_obj.cgst,
			'sgst': settings_obj.sgst,
			'platform_charges': settings_obj.platform_charges,
			'additional_charges': settings_obj.additional_charges,
			'time_slots': settings_obj.time_slots or [],
			'distance_charges': settings_obj.distance_charges or [],
			'hours' : range(1, 13),
			'minutes': range(0, 60),
		}
		return render(request, 'pages/global-settings/global_settings.html', context)

	def post(self, request):
		# Collect posted values and echo them back in the template for testing/demo.
		cgst = request.POST.get('cgst', '')
		sgst = request.POST.get('sgst', '')
		platform_charges = request.POST.get('platform_charges', '')
		additional_charges = request.POST.get('additional_charges', '')
		# time_slots is submitted as multiple values (time_slots[])
		time_slots = request.POST.getlist('time_slots[]')

		# Persist the settings to the singleton record
		settings_obj, _ = GlobalSetting.objects.get_or_create(pk=1)
		try:
			settings_obj.cgst = float(cgst) if cgst != '' else 0
		except ValueError:
			settings_obj.cgst = 0
		try:
			settings_obj.sgst = float(sgst) if sgst != '' else 0
		except ValueError:
			settings_obj.sgst = 0
		try:
			settings_obj.platform_charges = float(platform_charges) if platform_charges != '' else 0
		except ValueError:
			settings_obj.platform_charges = 0
		try:
			settings_obj.additional_charges = float(additional_charges) if additional_charges != '' else 0
		except ValueError:
			settings_obj.additional_charges = 0

		# time_slots is a list of strings
		settings_obj.time_slots = time_slots
		# distance charges: we expect two parallel lists distance_ranges[] and distance_charges[]
		distance_ranges = request.POST.getlist('distance_ranges[]')
		distance_charges_vals = request.POST.getlist('distance_charges[]')
		distance_list = []
		if distance_ranges and distance_charges_vals:
			# zip safely up to the shortest
			for r, c in zip(distance_ranges, distance_charges_vals):
				if r.strip() == '':
					continue
				try:
					charge_val = float(c) if c != '' else 0
				except ValueError:
					charge_val = 0
				distance_list.append({'range': r, 'charge': charge_val})
		settings_obj.distance_charges = distance_list
		settings_obj.save()

		# Redirect (PRG) to avoid repost and to show a single success message
		return redirect(request.path + '?updated=1')

