package controllers

import (
	"nearle/db"
	"nearle/domain"
	"nearle/models"
	"nearle/utils"
	"strconv"
	"strings"
	"time"

	"net/http"

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

func Createtenant(c *fiber.Ctx) error {

	var data models.Tenants
	var seq models.Ordersequences

	var result models.Tenantinfo

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

	tid := domain.Checktenantbyno(data.Primarycontact)
	if tid != 0 {

		return c.JSON(fiber.Map{
			"code":    http.StatusConflict,
			"message": "Tenant Already Exists",
			"status":  false,
		})

	}
	tx := db.DB.Begin()

	t1 := tx.Create(&data)
	if t1.Error != nil {
		utils.Error("Createtenant t1 error", "error", t1.Error)
		tx.Rollback()
	}

	seq.Tenantid = data.Tenantid

	t2 := tx.Table("ordersequences").Create(&seq)
	if t2.Error != nil {
		utils.Error("Createtenant t2 error", "error", t2.Error)
		tx.Rollback()
	}

	err := tx.Commit().Error
	if err != nil {

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

	}

	result = domain.GetTeanantById(data.Tenantid)

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

}

func CreateLocation(c *fiber.Ctx) error {

	var data models.Tenantlocations

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

	err := domain.CreateLocation(data)

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

	}

	return c.JSON(fiber.Map{
		"code":    http.StatusCreated,
		"message": "Location Successfully Created",
		"status":  true,
	})

}

func CreatetenantUser(c *fiber.Ctx) error {

	var data models.Tenants
	var result models.UserInfo

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

	tid := domain.Checktenantbyno(data.Primarycontact)
	if tid != 0 {

		return c.JSON(fiber.Map{
			"code":    http.StatusConflict,
			"message": "Tenant Already Exists",
			"status":  false,
		})

	}

	status, err := domain.CreateTenantUser(data)
	if !status {
		return c.JSON(fiber.Map{
			"code":    http.StatusCreated,
			"message": err.Error(),
			"status":  false,
		})

	} else {

		result = domain.Getuserbyno(data.Primarycontact)

	}

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

}

func GetTenantInfo(c *fiber.Ctx) error {

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

	data := domain.GetTeanantById(tid)

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

func GetTenantStatus(c *fiber.Ctx) error {

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

	data := domain.GetTeanantById(tid)

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

func GetTenantPricing(c *fiber.Ctx) error {

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

	data := domain.GetTeanantPricing(tid, aid)

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

func GetPricingList(c *fiber.Ctx) error {

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

	data := domain.GetPricinglist(tid)

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

func CreateStaff(c *fiber.Ctx) error {

	var data models.User

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

	err := db.DB.Table("app_users").Create(&data).Error
	if err != nil {

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

	}

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

}

func CreatePricing(c *fiber.Ctx) error {

	var data models.Tenantpricing

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

	err := db.DB.Table("tenantpricing").Create(&data).Error
	if err != nil {

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

	}

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

}

func UpdateStaff(c *fiber.Ctx) error {

	var data models.User

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

	err := db.DB.Table("app_users").Where("userid=?", data.Userid).Updates(&data).Error

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

	}

	return c.JSON(fiber.Map{
		"status":  true,
		"code":    http.StatusAccepted,
		"message": "User update successful",
	})

}

func GetStaffs(c *fiber.Ctx) error {

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

	var data []models.StaffInfo

	q1 := `SELECT a.userid,a.firstname,a.lastname,concat(a.firstname,'',a.lastname) as fullname,a.email,a.contactno,a.address,a.suburb,a.city,a.state,a.postcode,a.userfcmtoken,a.pin,a.applocationid,
	a.roleid,a.partnerid,a.tenantid,a.locationid,b.locationname
	from app_users a INNER JOIN tenantlocations b ON a.locationid=b.locationid where a.tenantid=?`

	db.DB.Raw(q1, tid).Find(&data)

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

}

func GetTenants(c *fiber.Ctx) error {

	aid, _ := strconv.Atoi(c.Query("applocationid"))
	pid, _ := strconv.Atoi(c.Query("partnerid"))
	Stat := strings.ToUpper(c.Query("status"))

	var data []models.Tenantinfo

	query := db.DB.Table("tenants as a").
		Select("a.*, b.subcategoryname").
		Joins("INNER JOIN app_subcategory b ON b.subcategoryid = a.subcategoryid")

	// 🔥 Fixed conditions (always applied)
	query = query.Where("a.tenanttype = ? AND a.approved = ?", "E", 1)

	// 🔍 Dynamic filters
	if aid != 0 {
		query = query.Where("a.applocationid = ?", aid)
	}
	if pid != 0 {
		query = query.Where("a.partnerid = ?", pid)
	}
	if Stat != "" {
		query = query.Where("UPPER(a.status) = ?", Stat)
	}

	query.Find(&data)

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

func SearchTenant(c *fiber.Ctx) error {

	status := c.Query("status")
	searchstr := c.Query("keyword")

	var data []models.Tenantinfo

	// Use query builder for safer and cleaner code
	query := db.DB.Table("tenants as a").
		Select("a.*, b.subcategoryname, c.firstname, c.lastname, concat(c.firstname,' ',c.lastname) AS accountname").
		Joins("INNER JOIN app_subcategory b on a.subcategoryid=b.subcategoryid").
		Joins("LEFT JOIN app_users c on c.userid=a.partneruserid")

	if status != "pending" {
		query = query.Where("a.approved = 1 AND lower(a.status) = ?", strings.ToLower(status))
	} else {
		query = query.Where("a.approved = 0")
	}

	if searchstr != "" {
		query = query.Where("lower(a.tenantname) like ?", strings.ToLower(searchstr)+"%")
	}

	query.Find(&data)

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

}

// func GetAllTenants(c *fiber.Ctx) error {

// 	pageno, _ := strconv.Atoi(c.Query("pageno"))
// 	pagesize, _ := strconv.Atoi(c.Query("pagesize"))
// 	status := c.Query("status")
// 	aid, _ := strconv.Atoi(c.Query("applocationid"))

// 	offset := (pageno - 1) * pagesize

// 	var data []models.Tenantinfo
// 	var q1 string

// 	if status == "active" {

// 		if aid != 0 {

// 			q1 = `SELECT a.*,b.subcategoryname, c.locationname as applocation FROM tenants a
// 				INNER JOIN app_subcategory b on a.subcategoryid=b.subcategoryid
// 				INNER JOIN app_location c on a.applocationid=c.applocationid
// 				where  a.approved=1 and a.status='Active'  and a.applocationid=` + strconv.Itoa(aid) + ` ORDER BY a.tenantid desc LIMIT ` + strconv.Itoa(pagesize) + ` OFFSET ` + strconv.Itoa(offset)

// 		} else {

// 			q1 = `SELECT a.*,b.subcategoryname, c.locationname as applocation
// 			     FROM tenants a
// 				INNER JOIN app_subcategory b on a.subcategoryid=b.subcategoryid
// 				INNER JOIN app_location c on a.applocationid=c.applocationid
// 				where  a.approved=1 and a.status='Active'  ORDER BY a.tenantid desc LIMIT ` + strconv.Itoa(pagesize) + ` OFFSET ` + strconv.Itoa(offset)

// 		}

// 	} else if status == "inactive" {

// 		if aid != 0 {

// 			q1 = `SELECT a.*,b.subcategoryname, c.locationname as applocation FROM tenants a
// 				INNER JOIN app_subcategory b on a.subcategoryid=b.subcategoryid
// 				INNER JOIN app_location c on a.applocationid=c.applocationid
// 				where a.approved=1 and a.status='InActive'  and a.applocationid=` + strconv.Itoa(aid) + ` ORDER BY a.tenantid desc LIMIT ` + strconv.Itoa(pagesize) + ` OFFSET ` + strconv.Itoa(offset)

// 		} else {

// 			q1 = `SELECT a.*,b.subcategoryname, c.locationname as applocation
// 			     FROM tenants a
// 				INNER JOIN app_subcategory b on a.subcategoryid=b.subcategoryid
// 				INNER JOIN app_location c on a.applocationid=c.applocationid
// 				where a.approved=1 and a.status='InActive'  ORDER BY a.tenantid desc LIMIT ` + strconv.Itoa(pagesize) + ` OFFSET ` + strconv.Itoa(offset)

// 		}

// 	} else if status == "pending" {

// 		if aid != 0 {

// 			q1 = `SELECT a.*,b.subcategoryname, c.locationname as applocation FROM tenants a
// 				INNER JOIN app_subcategory b on a.subcategoryid=b.subcategoryid
// 				INNER JOIN app_location c on a.applocationid=c.applocationid
// 				where a.approved=0 and  a.applocationid=` + strconv.Itoa(aid) + ` ORDER BY a.tenantid desc LIMIT ` + strconv.Itoa(pagesize) + ` OFFSET ` + strconv.Itoa(offset)

// 		} else {

// 			q1 = `SELECT a.*,b.subcategoryname, c.locationname as applocation
// 			     FROM tenants a
// 				INNER JOIN app_subcategory b on a.subcategoryid=b.subcategoryid
// 				INNER JOIN app_location c on a.applocationid=c.applocationid
// 				where a.approved=0  ORDER BY a.tenantid desc LIMIT ` + strconv.Itoa(pagesize) + ` OFFSET ` + strconv.Itoa(offset)

// 		}

// 	}

// 	// println(q1)

// 	db.DB.Raw(q1).Find(&data)

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

// }

func GetAllTenants(c *fiber.Ctx) error {

	pageno, _ := strconv.Atoi(c.Query("pageno"))
	pagesize, _ := strconv.Atoi(c.Query("pagesize"))
	status := c.Query("status")
	aid, _ := strconv.Atoi(c.Query("applocationid"))
	moduleid, _ := strconv.Atoi(c.Query("moduleid"))
	tenanttype := c.Query("tenanttype")
	keyword := c.Query("keyword")

	details := domain.Getalltenants(pageno, pagesize, aid, moduleid, status, tenanttype, keyword)
	return c.JSON(fiber.Map{
		"code":    http.StatusOK,
		"message": "Success",
		"status":  true,
		"details": details,
	})
}

func GetTenantSummary(c *fiber.Ctx) error {

	aid, _ := strconv.Atoi(c.Query("applocationid", "0"))
	moduleid, _ := strconv.Atoi(c.Query("moduleid", "0"))
	tenanttype := c.Query("tenanttype", "0")
	keyword := c.Query("keyword", "")

	type Result struct {
		Total    int64
		Active   int64
		Inactive int64
		Pending  int64
	}

	var result Result

	query := db.DB.Table("tenants").
		Select(`
			COUNT(*) AS total,
			COUNT(*) FILTER (WHERE approved = 1 AND status = 'Active') AS active,
			COUNT(*) FILTER (WHERE approved = 1 AND status = 'InActive') AS inactive,
			COUNT(*) FILTER (WHERE approved = 0) AS pending
		`)

	// Apply filters
	if aid != 0 {
		query = query.Where("applocationid = ?", aid)
	}

	if moduleid != 0 {
		query = query.Where("moduleid = ?", moduleid)
	}

	if tenanttype != "0" {
		query = query.Where("tenanttype = ?", tenanttype)
	}

	if keyword != "" {
		k := "%" + keyword + "%"
		query = query.Where("tenantname ILIKE ? OR primarycontact ILIKE ?", k, k)
	}

	// Execute single query
	err := query.Scan(&result).Error
	if err != nil {
		return c.Status(500).JSON(fiber.Map{
			"status":  false,
			"message": err.Error(),
		})
	}

	return c.JSON(fiber.Map{
		"code":    http.StatusOK,
		"message": "Summary fetched successfully",
		"status":  true,
		"summary": fiber.Map{
			"total":    result.Total,
			"active":   result.Active,
			"inactive": result.Inactive,
			"pending":  result.Pending,
		},
	})
}

func GetCloudStore(c *fiber.Ctx) error {

	pageno, _ := strconv.Atoi(c.Query("pageno"))
	pagesize, _ := strconv.Atoi(c.Query("pagesize"))
	status := c.Query("status")
	aid, _ := strconv.Atoi(c.Query("applocationid"))

	offset := (pageno - 1) * pagesize

	var data []models.Tenantinfo

	query := db.DB.Table("tenants as a").
		Select("a.*, c.locationname as applocation").
		Joins("INNER JOIN app_location c on a.applocationid=c.applocationid").
		Where("a.tenanttype = ?", "C")

	if status == "active" {
		query = query.Where("a.approved = 1 AND a.status = ?", "Active")
	} else if status == "inactive" {
		query = query.Where("a.approved = 1 AND a.status = ?", "InActive")
	} else if status == "pending" {
		query = query.Where("a.approved = 0")
	}

	if aid != 0 {
		query = query.Where("a.applocationid = ?", aid)
	}

	query.Order("a.tenantid desc").Limit(pagesize).Offset(offset).Find(&data)

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

}

func GetTenantLocations(c *fiber.Ctx) error {

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

	var data []models.Tenantlocations

	db.DB.Table("tenantlocations as a").
		Select("a.*, b.roleid").
		Joins("LEFT JOIN app_users b ON a.locationid = b.locationid AND a.tenantid = b.tenantid").
		Where("a.tenantid = ?", tid).
		Scopes(func(db *gorm.DB) *gorm.DB {
			if keyword != "" {
				k := "%" + keyword + "%"
				return db.Where("LOWER(a.locationname) LIKE ? OR LOWER(a.contactno) LIKE ?", k, k)
			}
			return db
		}).
		Find(&data)

	var result []map[string]interface{}

	for _, loc := range data {

		// ✅ Build slots in required format
		slots := []map[string]string{}

		if loc.Slot1 != "" {
			slots = append(slots, map[string]string{
				"name": "Slot 1",
				"time": loc.Slot1,
			})
		}
		if loc.Slot2 != "" {
			slots = append(slots, map[string]string{
				"name": "Slot 2",
				"time": loc.Slot2,
			})
		}
		if loc.Slot3 != "" {
			slots = append(slots, map[string]string{
				"name": "Slot 3",
				"time": loc.Slot3,
			})
		}
		if loc.Slot4 != "" {
			slots = append(slots, map[string]string{
				"name": "Slot 4",
				"time": loc.Slot4,
			})
		}
		if loc.Slot5 != "" {
			slots = append(slots, map[string]string{
				"name": "Slot 5",
				"time": loc.Slot5,
			})
		}

		m := map[string]interface{}{
			"locationid":     loc.Locationid,
			"tenantid":       loc.Tenantid,
			"applocationid":  loc.Applocationid,
			"moduleid":       loc.Moduleid,
			"locationname":   loc.Locationname,
			"email":          loc.Email,
			"contactno":      loc.Contactno,
			"latitude":       loc.Latitude,
			"longitude":      loc.Longitude,
			"address":        loc.Address,
			"suburb":         loc.Suburb,
			"city":           loc.City,
			"state":          loc.State,
			"postcode":       loc.Postcode,
			"opentime":       loc.Opentime,
			"closetime":      loc.Closetime,
			"partnerid":      loc.Partnerid,
			"deliveryradius": loc.Deliveryradius,
			"deliverymins":   loc.Deliverymins,
			"cancelsecs":     loc.Cancelsecs,
			"slots":          slots,
			"status":         loc.Status,
		}

		result = append(result, m)
	}

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

func GetTenantSlot(c *fiber.Ctx) error {

	var data models.Tenantslot

	q1 := `SELECT * FROM tenantslot`

	utils.Logger.Debugf("Query: %s", q1)

	db.DB.Raw(q1).Find(&data)

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

func GetTenantLocation(c *fiber.Ctx) error {

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

	var data models.Tenantlocations

	db.DB.Table("tenantlocations").Where("tenantid = ? AND locationid = ?", tid, lid).Find(&data)

	result := map[string]interface{}{
		"locationid":     data.Locationid,
		"tenantid":       data.Tenantid,
		"applocationid":  data.Applocationid,
		"moduleid":       data.Moduleid,
		"locationname":   data.Locationname,
		"email":          data.Email,
		"contactno":      data.Contactno,
		"latitude":       data.Latitude,
		"longitude":      data.Longitude,
		"address":        data.Address,
		"suburb":         data.Suburb,
		"city":           data.City,
		"state":          data.State,
		"postcode":       data.Postcode,
		"opentime":       data.Opentime,
		"closetime":      data.Closetime,
		"partnerid":      data.Partnerid,
		"deliveryradius": data.Deliveryradius,
		"deliverymins":   data.Deliverymins,
		"cancelsecs":     data.Cancelsecs,
		"slots": []map[string]string{
			{"slot1": data.Slot1},
			{"slot2": data.Slot2},
			{"slot3": data.Slot3},
			{"slot4": data.Slot4},
			{"slot5": data.Slot5},
		},
		"status": data.Status,
	}

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

func UpdateTenant(c *fiber.Ctx) error {

	var data models.Tenants

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

	err := domain.UpdateTenant(data)

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

	}

	return c.JSON(fiber.Map{
		"status":  true,
		"code":    http.StatusAccepted,
		"message": "Tenant update successful",
	})

}

func UpdateLocation(c *fiber.Ctx) error {

	var data models.Tenantlocations

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

	err := domain.UpdateLocation(data)

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

	}

	return c.JSON(fiber.Map{
		"status":  true,
		"code":    http.StatusAccepted,
		"message": "Location update successful",
	})

}

func Createtenantcustomer(c *fiber.Ctx) error {
	var req models.CreateTenantCustomerRequest

	if err := c.BodyParser(&req); err != nil {
		return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
			"code":    400,
			"status":  false,
			"message": "Invalid request body",
			"data":    fiber.Map{},
		})
	}

	tenantcustomers := models.TenantCustomer{
		TenantID:           req.TenantID,
		LocationID:         req.LocationID,
		CustomerID:         req.CustomerID,
		CustomerLocationID: req.CustomerLocationID,
		Status:             req.Status,
	}

	if err := db.DB.Create(&tenantcustomers).Error; err != nil {
		utils.Logger.Errorf("Error inserting tenant customer: %v", err)
		return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
			"code":    500,
			"status":  false,
			"message": "Failed to create tenant customer",
			"data":    fiber.Map{},
		})
	}

	return c.Status(fiber.StatusOK).JSON(fiber.Map{
		"code":    200,
		"status":  true,
		"message": "Tenant customer created successfully",
		"data":    tenantcustomers,
	})
}

func GetCustomerTenants(c *fiber.Ctx) error {
	customerID, err := strconv.Atoi(c.Query("customerid"))
	if err != nil || customerID == 0 {
		return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
			"code":    400,
			"message": "Invalid customerid",
			"status":  false,
			"data":    fiber.Map{},
		})
	}

	// categoryIDStr := c.Query("categoryid")
	// var categoryID int
	// if categoryIDStr != "" {
	// 	categoryID, _ = strconv.Atoi(categoryIDStr)
	// }

	data := domain.GetCustomerLocations(customerID)

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

func CreateTenantLocation(c *fiber.Ctx) error {

	var data models.Tenantlocations

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

	err := domain.CreateTenantLocation(data)

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

	}

	return c.JSON(fiber.Map{
		"code":    http.StatusCreated,
		"message": "Tenant Location Successfully Created",
		"status":  true,
	})

}

func UpdateTenantLocation(c *fiber.Ctx) error {

	var data models.Tenantlocations

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

	err := domain.UpdateTenantLocation(data)

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

	}

	return c.JSON(fiber.Map{
		"status":  true,
		"code":    http.StatusAccepted,
		"message": "Tenant Location update successful",
	})

}

func GetLocationSummary(c *fiber.Ctx) error {
	tenantID, err := strconv.Atoi(c.Query("tenantid"))
	if err != nil || tenantID <= 0 {
		return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
			"code":    400,
			"status":  false,
			"message": "Invalid tenantid",
		})
	}

	summary := domain.FetchLocationSummary(tenantID)

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

func GetTenantStaffSummary(c *fiber.Ctx) error {
	tenantID, err := strconv.Atoi(c.Query("tenantid"))
	if err != nil || tenantID == 0 {
		return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
			"code":    400,
			"status":  false,
			"message": "Invalid tenantid",
			"details": fiber.Map{},
		})
	}

	summary := domain.FetchTenantStaffSummary(tenantID)

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

func GetTenantRiderSummary(c *fiber.Ctx) error {
	tenantID, err := strconv.Atoi(c.Query("tenantid"))
	if err != nil || tenantID == 0 {
		return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
			"code":    400,
			"status":  false,
			"message": "Invalid tenantid",
			"details": fiber.Map{},
		})
	}

	summary := domain.FetchTenantRiderSummary(tenantID)

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

func CreateTenantRequest(c *fiber.Ctx) error {
	var request models.TenantRequest

	if err := c.BodyParser(&request); err != nil {
		return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
			"code":    400,
			"message": "Invalid request body",
			"status":  false,
		})
	}

	// Set timestamps if not already set
	request.Requestdate = time.Now()
	request.Created = time.Now()
	request.Updated = time.Now()

	// Insert into tenantrequests table
	if err := db.DB.Table("tenantrequests").Create(&request).Error; err != nil {
		return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
			"code":    500,
			"message": "Failed to create tenant request",
			"status":  false,
		})
	}

	return c.Status(fiber.StatusCreated).JSON(fiber.Map{
		"code":    201,
		"message": "Tenant request created successfully",
		"status":  true,
		"data":    request,
	})
}

func GetTenantRequests(c *fiber.Ctx) error {
	tenantIDStr := c.Query("tenantid")
	pageNoStr := c.Query("pageno", "1")
	pageSizeStr := c.Query("pagesize", "10")

	pageNo, _ := strconv.Atoi(pageNoStr)
	pageSize, _ := strconv.Atoi(pageSizeStr)

	if pageNo < 1 {
		pageNo = 1
	}
	if pageSize < 1 {
		pageSize = 10
	}
	offset := (pageNo - 1) * pageSize

	var requests []models.TenantRequest
	query := db.DB.Table("tenantrequests")

	// Optional filter by tenantid
	if tenantIDStr != "" {
		tenantID, err := strconv.Atoi(tenantIDStr)
		if err != nil {
			return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
				"code":    400,
				"message": "Invalid tenantid",
				"status":  false,
			})
		}
		if tenantID != 0 {
			query = query.Where("tenantid = ?", tenantID)
		}
	}

	var total int64
	query.Count(&total)

	if err := query.Order("created desc").Offset(offset).Limit(pageSize).Find(&requests).Error; err != nil {
		return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
			"code":    500,
			"message": "Failed to fetch tenant requests",
			"status":  false,
		})
	}

	return c.Status(fiber.StatusOK).JSON(fiber.Map{
		"code":    200,
		"message": "Tenant requests fetched successfully",
		"status":  true,
		"data":    requests,
	})
}

func CreateTenantPromotion(c *fiber.Ctx) error {
	var data models.Tenantpromotions

	// Parse body (Locationid comes as []string)
	if err := c.BodyParser(&data); err != nil {
		return c.Status(http.StatusBadRequest).JSON(fiber.Map{
			"status":  false,
			"code":    http.StatusBadRequest,
			"message": "Invalid JSON body",
		})
	}

	if len(data.Locationid) > 0 {
		data.LocationidStr = strings.Join(data.Locationid, ",")
	}

	// Save to DB
	if err := domain.CreateTenantPromotion(&data); err != nil {
		return c.Status(http.StatusInternalServerError).JSON(fiber.Map{
			"status":  false,
			"code":    http.StatusInternalServerError,
			"message": err.Error(),
		})
	}

	return c.Status(http.StatusCreated).JSON(fiber.Map{
		"status":  true,
		"code":    http.StatusCreated,
		"message": "Promotion created successfully",
		"data":    data,
	})
}

func GetTenantPromotions(c *fiber.Ctx) error {

	tid, _ := strconv.Atoi(c.Query("tenantid"))
	lid := c.Query("locationid") // user sends single location id

	data := domain.GetTenantPromotions(tid, lid)

	return c.JSON(fiber.Map{
		"status":  true,
		"code":    200,
		"message": "Success",
		"details": data,
	})
}
