package controllers

import (
	"nearle/domain"
	"nearle/models"
	"net/http"
	"strconv"

	"github.com/gofiber/fiber/v2"
)

func InvoiceSeqno(c *fiber.Ctx) error {

	tid, _ := strconv.Atoi(c.Query("tenantid"))

	seqno := domain.GetSequenceno(tid, "INV")

	return c.JSON(fiber.Map{
		"code":    http.StatusOK,
		"message": "Success",
		"status":  true,
		"Details": seqno,
	})

}

func CreateInvoice(c *fiber.Ctx) error {

	var data models.Tenantsales

	if err := c.BodyParser(&data); err != nil {
		return err
	}

	err := domain.CreateInvoice(data)
	if err != nil {

		return c.JSON(fiber.Map{
			"code":    http.StatusConflict,
			"message": err.Error(),
			"status":  false,
		})

	}

	return c.JSON(fiber.Map{
		"code":    http.StatusOK,
		"message": "Success",
		"status":  true,
	})

}

func GetallInvoice(c *fiber.Ctx) error {

	status, _ := strconv.Atoi(c.Query("billstatus"))
	tid, _ := strconv.Atoi(c.Query("tenantid"))

	result := domain.GetAllInvoice(status, tid)

	return c.JSON(fiber.Map{
		"code":    http.StatusOK,
		"message": "Success",
		"status":  true,
		"details": result,
	})
}

func GetInvoiceOrders(c *fiber.Ctx) error {

	fdate := c.Query("fromdate")
	tdate := c.Query("todate")
	tid, _ := strconv.Atoi(c.Query("tenantid"))

	result := domain.GetInvoiceOrders(tid, fdate, tdate)

	return c.JSON(fiber.Map{
		"code":    http.StatusOK,
		"message": "Success",
		"status":  true,
		"details": result,
	})
}

func GetInvoiceInsight(c *fiber.Ctx) error {

	tid, _ := strconv.Atoi(c.Query("tenantid"))

	result := domain.GetInvoiceInsight(tid)

	return c.JSON(fiber.Map{
		"code":    http.StatusOK,
		"message": "Success",
		"status":  true,
		"details": result,
	})
}

func UpdateInvoice(c *fiber.Ctx) error {

	var data models.Tenantsales

	if err := c.BodyParser(&data); err != nil {
		return err
	}

	err := domain.UpdateInvoice(data)

	if err != nil {

		return c.JSON(fiber.Map{
			"code":    http.StatusConflict,
			"message": err.Error(),
			"status":  false,
		})

	}

	return c.JSON(fiber.Map{
		"code":    http.StatusOK,
		"message": "Success",
		"status":  true,
	})

}

func UpdateInvoiceStatus(c *fiber.Ctx) error {

	var data models.InvoiceStatus

	if err := c.BodyParser(&data); err != nil {
		return err
	}

	err := domain.UpdateInvoiceStatus(data)

	if err != nil {

		return c.JSON(fiber.Map{
			"code":    http.StatusConflict,
			"message": err.Error(),
			"status":  false,
		})

	}

	return c.JSON(fiber.Map{
		"code":    http.StatusOK,
		"message": "Success",
		"status":  true,
	})

}
