package domain

import (
	"nearle/db"
	"nearle/models"
	"nearle/utils"
	"net/http"
	"strconv"
	"strings"
)

func CreateCustomer(input models.Customers) int {

	var custloc models.Customerlocations
	var tcust models.Tenantcustomers

	tx := db.DB.Begin()

	t1 := tx.Create(&input)
	if t1.Error != nil {

		utils.Error("CreateCustomer t1 error", "error", t1.Error)
		tx.Rollback()
	}

	custloc.Customerid = input.Customerid
	custloc.Address = input.Address
	custloc.Suburb = input.Suburb
	custloc.City = input.City
	custloc.State = input.State
	custloc.Postcode = input.Postcode
	custloc.Latitude = input.Latitude
	custloc.Longitude = input.Longitude
	custloc.Doorno = input.Doorno
	custloc.Landmark = input.Landmark
	custloc.Primaryaddress = 1

	t2 := tx.Table("customerlocations").Create(&custloc)
	if t2.Error != nil {

		utils.Error("CreateCustomer t2 error", "error", t2.Error)
		tx.Rollback()
	}

	tcust.Customerid = input.Customerid
	tcust.Tenantid = input.Tenantid

	t3 := tx.Table("tenantcustomers").Create(&tcust)
	if t3.Error != nil {

		utils.Error("CreateCustomer t3 error", "error", t3.Error)
		tx.Rollback()
	}

	tx.Commit()

	return input.Customerid
}

func CreateCustomerv1(input models.Customers) (int, error) {

	var tcust models.Tenantcustomers

	tx := db.DB.Begin()

	t1 := tx.Create(&input)
	if t1.Error != nil {

		utils.Error("CreateCustomerv1 t1 error", "error", t1.Error)
		tx.Rollback()
		return 0, t1.Error
	}

	tcust.Customerid = input.Customerid
	tcust.Tenantid = input.Tenantid

	t3 := tx.Table("tenantcustomers").Create(&tcust)
	if t3.Error != nil {

		utils.Error("CreateCustomerv1 t3 error", "error", t3.Error)
		tx.Rollback()
		return 0, t3.Error
	}

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

		return 0, err
	}

	return input.Customerid, nil
}

func CreateCustomerv2(input models.Customers) (*models.CustomersId, error) {

	var custloc models.Customerlocations
	var tcust models.Tenantcustomers
	var cid models.CustomersId

	tx := db.DB.Begin()

	t1 := tx.Create(&input)
	if t1.Error != nil {

		utils.Error("CreateCustomerv2 t1 error", "error", t1.Error)
		tx.Rollback()
		return nil, t1.Error
	}

	custloc.Customerid = input.Customerid
	custloc.Address = input.Address
	custloc.Suburb = input.Suburb
	custloc.City = input.City
	custloc.State = input.State
	custloc.Postcode = input.Postcode
	custloc.Latitude = input.Latitude
	custloc.Longitude = input.Longitude
	custloc.Doorno = input.Doorno
	custloc.Landmark = input.Landmark
	custloc.Primaryaddress = 1

	t2 := tx.Table("customerlocations").Create(&custloc)
	if t2.Error != nil {

		utils.Error("CreateCustomerv2 t2 error", "error", t2.Error)
		tx.Rollback()
		return nil, t2.Error
	}

	tcust.Customerid = input.Customerid
	tcust.Tenantid = input.Tenantid

	t3 := tx.Table("tenantcustomers").Create(&tcust)
	if t3.Error != nil {

		utils.Error("CreateCustomerv2 t3 error", "error", t3.Error)
		tx.Rollback()
		return nil, t3.Error
	}

	cid.Customerid = input.Customerid
	cid.Locationid = custloc.Locationid

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

		return nil, err
	}

	return &cid, nil
}

func UpdateCustomerv2(input models.Customers) (int, error) {

	var custloc models.Customerlocations
	var tcust models.Tenantcustomers
	var data models.CustomersId

	tx := db.DB.Begin()

	t1 := tx.Where("customerid=?", input.Customerid).Updates(&input)
	if t1.Error != nil {

		utils.Error("UpdateCustomerv2 t1 error", "error", t1.Error)
		tx.Rollback()
		return 0, t1.Error
	}

	custloc.Customerid = input.Customerid
	custloc.Address = input.Address
	custloc.Suburb = input.Suburb
	custloc.City = input.City
	custloc.State = input.State
	custloc.Postcode = input.Postcode
	custloc.Latitude = input.Latitude
	custloc.Longitude = input.Longitude
	custloc.Doorno = input.Doorno
	custloc.Landmark = input.Landmark
	custloc.Primaryaddress = 1

	custlocid, err := CheckLocation(input.Customerid)
	if err != nil {

		tx.Rollback()
		return 0, err
	}

	if custlocid != 0 {

		utils.Logger.Infof("entering location update: %d", custlocid)

		custloc.Locationid = custlocid

		t2 := tx.Table("customerlocations").Where("locationid=?", custlocid).Updates(&custloc)
		if t2.Error != nil {

			utils.Error("UpdateCustomerv2 t2 update error", "error", t2.Error)
			tx.Rollback()
			return 0, t2.Error
		}

	} else {

		utils.Logger.Infof("entering location create for customer: %d", input.Customerid)

		t2 := tx.Table("customerlocations").Create(&custloc)
		if t2.Error != nil {

			utils.Error("UpdateCustomerv2 t2 create error", "error", t2.Error)
			tx.Rollback()
			return 0, t2.Error
		}

	}

	cid := CheckTenantCustomer(input.Customerid, input.Tenantid)

	if cid == 0 {

		tcust.Customerid = input.Customerid
		tcust.Tenantid = input.Tenantid

		t3 := tx.Table("tenantcustomers").Create(&tcust)
		if t3.Error != nil {

			utils.Error("UpdateCustomerv2 t3 error", "error", t3.Error)
			tx.Rollback()
			return 0, t3.Error
		}

	}

	data.Locationid = custloc.Locationid

	utils.Logger.Infof("customerid for the customer is %d", input.Customerid)
	utils.Logger.Infof("The created Location for the customer is %d", data.Locationid)
	utils.Logger.Infof("the Location for the customer is %d", custloc.Locationid)

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

		return 0, err
	}

	return data.Locationid, nil
}

func UpdateCustomerv1(input models.Customers) error {

	var tcust models.Tenantcustomers

	tx := db.DB.Begin()

	t1 := tx.Where("customerid=?", input.Customerid).Updates(&input)
	if t1.Error != nil {

		utils.Error("UpdateCustomerv1 t1 error", "error", t1.Error)
		tx.Rollback()
		return t1.Error
	}

	cid := CheckTenantCustomer(input.Customerid, input.Tenantid)
	if cid == 0 {

		tcust.Customerid = input.Customerid
		tcust.Tenantid = input.Tenantid

		t3 := tx.Table("tenantcustomers").Create(&tcust)
		if t3.Error != nil {

			utils.Error("UpdateCustomerv1 t3 error", "error", t3.Error)
			tx.Rollback()
			return t3.Error
		}

	}

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

		return err
	}

	return nil
}

func CreateTenantCustomer(input models.Customers) int {
	var tcust models.Tenantcustomers

	tcust.Customerid = input.Customerid
	tcust.Tenantid = input.Tenantid

	tx := db.DB.Begin()

	t3 := tx.Table("tenantcustomers").Create(&tcust)
	if t3.Error != nil {

		utils.Error("CreateTenantCustomer t3 error", "error", t3.Error)
		tx.Rollback()
	}

	tx.Commit()

	return input.Customerid

}

func UpdateCustomer(input models.Customers) models.Result {

	var custloc models.Customerlocations

	var result models.Result

	tx := db.DB.Begin()

	t1 := tx.Where("customerid=?", input.Customerid).Updates(&input)
	if t1.Error != nil {

		utils.Error("UpdateCustomer t1 error", "error", t1.Error)
		tx.Rollback()
	}

	custloc.Customerid = input.Customerid
	custloc.Address = input.Address
	custloc.Suburb = input.Suburb
	custloc.City = input.City
	custloc.State = input.State
	custloc.Postcode = input.Postcode
	custloc.Latitude = input.Latitude
	custloc.Longitude = input.Longitude
	custloc.Doorno = input.Doorno
	custloc.Landmark = input.Landmark

	t2 := tx.Table("customerlocations").Where("customerid=? and primaryaddress=?", input.Customerid, 1).Updates(&custloc)
	if t2.Error != nil {

		utils.Error("UpdateCustomer t2 error", "error", t2.Error)
		tx.Rollback()
	}

	err := tx.Commit().Error
	if err != nil {
		result.Code = http.StatusConflict
		result.Status = false
		result.Message = "Update Customer Failed"
		return result
	}

	result.Code = http.StatusAccepted
	result.Status = true
	result.Message = "Customer customer successful"

	return result
}

func GetCustomer(cid int, cno string) models.CustomerInfo {

	var data models.CustomerInfo

	var q1 string
	if cid != 0 {

		// q1 = `select a.customerid,a.authmode,a.configid,a.deviceid,a.devicetype,a.customertoken,a.firstname,a.lastname,
		// a.contactno,a.email,a.profileimage,a.address,a.suburb,a.city,a.state,a.landmark,a.doorno,a.postcode,
		// a.latitude,a.longitude,a.applocationid,a.status from customers a where a.customerid= ` + strconv.Itoa(cid)

		q1 = `SELECT a.customerid,a.firstname,a.lastname,a.contactno,a.email, a.profileimage, a.dialcode, a.deviceid, a.devicetype, a.authmode, a.configid, a.customertoken, a.intro, a.gender, a.dob,
		b.locationid as deliverylocationid,b.address,b.suburb,b.city,b.state,b.landmark,b.doorno,b.postcode,
		b.latitude,b.longitude,a.applocationid,c.locationid as tenantlocationid, c.tenantid, a.status,d.qrmode,d.latitude as selectedlatitude, d.longitude as selectedlongitude, d.radius, d.applocationid, e.allocationid
		from customers a 
		INNER JOIN customerlocations b ON a.customerid=b.customerid
		INNER JOIN tenantcustomers c ON a.customerid=c.customerid 
		LEFT JOIN app_location d ON a.applocationid=d.applocationid
		LEFT JOIN tenants e ON e.tenantid=c.tenantid
		WHERE b.primaryaddress=1 and a.customerid= ` + strconv.Itoa(cid) + ` order by customerid desc`

	} else {

		q1 = `SELECT a.customerid,a.firstname,a.lastname,a.contactno,a.email,a.profileimage, a.dialcode, a.deviceid, a.devicetype, a.authmode, a.configid, a.customertoken, a.intro,a.gender, a.dob,
		b.locationid as deliverylocationid,b.address,b.suburb,b.city,b.state,b.landmark,b.doorno,b.postcode,
		b.latitude,b.longitude,a.applocationid,c.locationid as tenantlocationid, c.tenantid, a.status, d.qrmode, d.latitude as selectedlatitude, d.longitude as selectedlongitude,d.radius, d.applocationid, e.allocationid
		from customers a 
		INNER JOIN customerlocations b ON a.customerid=b.customerid
		INNER JOIN tenantcustomers c ON a.customerid=c.customerid 
		LEFT JOIN app_location d ON a.applocationid=d.applocationid
		LEFT JOIN tenants e ON e.tenantid=c.tenantid
		WHERE b.primaryaddress=1 and a.contactno= '` + cno + `' order by customerid desc`

	}

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

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

	return data
}

func GetTenantCustomers(tid, lid, aid, pageno, pagesize int, keyword string) []models.CustomerInfo {

	var data []models.CustomerInfo
	offset := (pageno - 1) * pagesize

	var q1 string
	var args []interface{}

	
	if lid != 0 {

		q1 = `
		SELECT a.customerid,a.firstname,a.lastname,a.contactno,
			a.email,b.locationid AS deliverylocationid,b.address,b.suburb,b.city,b.state,b.landmark,b.doorno,b.postcode,b.latitude,b.longitude,a.applocationid,c.tenantid,
			c.locationid AS tenantlocationid,a.status,1 AS quantity,0.0 AS collectionamt
		FROM customers a
		LEFT JOIN customerlocations b ON a.customerid = b.customerid
		INNER JOIN tenantcustomers c ON a.customerid = c.customerid
		WHERE c.locationid = ? AND c.tenantid = ?
		`

		args = append(args, lid, tid)

		if aid != 0 {
			q1 += ` AND a.applocationid = ?`
			args = append(args, aid)
		}

		if keyword != "" {
			search := "%" + keyword + "%"
			q1 += ` AND (a.firstname LIKE ? OR a.contactno LIKE ? OR b.suburb LIKE ?)`
			args = append(args, search, search, search)
		}

		q1 += ` ORDER BY a.customerid DESC LIMIT ? OFFSET ?`
		args = append(args, pagesize, offset)

	} else {

		
		q1 = `
		SELECT a.customerid, a.firstname, a.lastname, a.contactno, a.email, a.address, a.suburb, a.city, a.state, a.landmark, a.doorno, a.postcode, a.latitude, 
		a.longitude, a.applocationid, c.tenantid, c.locationid AS tenantlocationid, a.status, 1 AS quantity, 0.0 AS collectionamt 
		FROM customers a 
		INNER JOIN tenantcustomers c ON a.customerid = c.customerid WHERE c.tenantid = ? `


		args = append(args, tid)

		if aid != 0 {
			q1 += ` AND a.applocationid = ?`
			args = append(args, aid)
		}

		if keyword != "" {
			search := "%" + strings.ToLower(keyword) + "%"
			q1 += ` AND (LOWER(a.firstname) LIKE ? OR LOWER(a.contactno) LIKE ? OR LOWER(a.suburb) LIKE ?)`
			args = append(args, search, search, search)
		}

		q1 += ` ORDER BY a.customerid DESC LIMIT ? OFFSET ?`
		args = append(args, pagesize, offset)
	}

	// 🔹 Execute query
	db.DB.Raw(q1, args...).Scan(&data)

	return data
}




func GetCustomerbytenant(tid, lid int) []models.CustomerInfo {

	var data []models.CustomerInfo

	var q1 string

	if lid != 0 {

		q1 = `SELECT a.customerid,a.firstname,a.lastname,a.contactno,a.email,
		b.locationid as deliverylocationid,b.address,b.suburb,b.city,b.state,b.landmark,b.doorno,b.postcode,
		b.latitude,b.longitude,a.applocationid,c.locationid as tenantlocationid,a.status 
		from customers a 
		INNER JOIN customerlocations b ON a.customerid=b.customerid
		INNER JOIN tenantcustomers c ON a.customerid=c.customerid 
		WHERE c.locationid > 0 and c.tenantid=? order by customerid desc`

	} else {

		q1 = `SELECT a.customerid,a.firstname,a.lastname,a.contactno,a.email,
		b.locationid as deliverylocationid,b.address,b.suburb,b.city,b.state,b.landmark,b.doorno,b.postcode,
		b.latitude,b.longitude,a.applocationid,c.locationid as tenantlocationid,a.status 
		from customers a 
		INNER JOIN customerlocations b ON a.customerid=b.customerid
		INNER JOIN tenantcustomers c ON a.customerid=c.customerid 
		WHERE  c.tenantid=? and c.locationid = 0 order by customerid desc`

		//and c.locationid = 0

	}

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

	return data
}

func GetallCustomers(aid, pageno, pagesize int, keyword string) []models.CustomerInfo {
	var data []models.CustomerInfo
	offset := (pageno - 1) * pagesize

	var q1 string

	baseQuery := `SELECT a.customerid,a.firstname,a.lastname,a.contactno,a.email,
		b.locationid as deliverylocationid,b.address,b.suburb,b.city,b.state,b.landmark,b.doorno,b.postcode,
		b.latitude,b.longitude,a.applocationid,a.status,b.primaryaddress 
		FROM customers a 
		INNER JOIN customerlocations b ON a.customerid=b.customerid
		WHERE b.primaryaddress=1`

	// filter by applocationid
	if aid != 0 {
		baseQuery += " AND a.applocationid=" + strconv.Itoa(aid)
	}

	// keyword search filter (case-insensitive)
	if keyword != "" {
		like := "'%" + strings.ToLower(keyword) + "%'"
		baseQuery += " AND (LOWER(a.firstname) LIKE " + like +
			" OR LOWER(a.lastname) LIKE " + like +
			" OR LOWER(a.contactno) LIKE " + like + ")"
	}

	// order + pagination
	q1 = baseQuery + " ORDER BY a.customerid DESC LIMIT " + strconv.Itoa(pagesize) + " OFFSET " + strconv.Itoa(offset)

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

	return data
}

func SearchCustomer(str string, tid int) []models.CustomerInfo {

	var data []models.CustomerInfo

	var q1 string

	if tid != 0 {

		q1 = `SELECT a.customerid,a.firstname,a.lastname,a.contactno,a.email,
		a.address,a.suburb,a.city,a.state,a.landmark,a.doorno,a.postcode,
		a.latitude,a.longitude,a.applocationid,c.locationid as tenantlocationid,a.status 
		from customers a 
		INNER JOIN tenantcustomers c ON a.customerid=c.customerid 
		WHERE c.tenantid=` + strconv.Itoa(tid) + ` and lower(a.firstname) like '` + strings.ToLower(str) + `%' or contactno like '` + strings.ToLower(str) + `%'`

	} else {

		// q1 = `SELECT a.customerid,a.firstname,a.lastname,a.contactno,a.email,
		// b.locationid as deliverylocationid,b.address,b.suburb,b.city,b.state,b.landmark,b.doorno,b.postcode,
		// b.latitude,b.longitude,a.applocationid,a.status,c.locationid as tenantlocationid
		// from customers a
		// INNER JOIN customerlocations b ON a.customerid=b.customerid
		// INNER JOIN tenantcustomers c ON a.customerid=c.customerid
		// WHERE lower(a.firstname) like '` + strings.ToLower(str) + `%' or contactno like '` + strings.ToLower(str) + `%'`

		q1 = `SELECT a.customerid,a.firstname,a.lastname,a.contactno,a.email,
		a.address,a.suburb,a.city,a.state,a.landmark,a.doorno,a.postcode,
		a.latitude,a.longitude,a.applocationid,c.locationid as tenantlocationid,a.status 
		from customers a 
		INNER JOIN tenantcustomers c ON a.customerid=c.customerid 
		WHERE lower(a.firstname) like '` + strings.ToLower(str) + `%' or contactno like '` + strings.ToLower(str) + `%'`

	}


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

	return data
}

func GetCustomerbyApplocation(aid int) []models.CustomerInfo {

	var data []models.CustomerInfo

	var q1 string
	if aid != 0 {

		q1 = `SELECT a.customerid,a.firstname,a.lastname,a.contactno,a.email,
		b.locationid as deliverylocationid,b.address,b.suburb,b.city,b.state,b.landmark,b.doorno,b.postcode,
		b.latitude,b.longitude,a.applocationid,a.status 
		from customers a 
		INNER JOIN customerlocations b ON a.customerid=b.customerid
		INNER JOIN tenantcustomers c ON a.customerid=c.customerid 
		WHERE b.primaryaddress=1 and a.applocationid=? order by customerid desc`

	}

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

	return data
}

func CheckCustomer(contactno string) int {

	var data models.Customers

	q1 := `select a.customerid,a.authmode,a.configid,a.deviceid,a.devicetype,a.customertoken,a.firstname,a.lastname,
		a.contactno,a.email,a.profileimage,a.address,a.suburb,a.city,a.state,a.landmark,a.doorno,a.postcode,
		a.latitude,a.longitude,a.status from customers a where a.contactno= '` + contactno + `'`

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

	return data.Customerid
}

func CheckLocation(cid int) (int, error) {

	var data int

	q1 := `select a.locationid from customerlocations a where a.customerid= ` + strconv.Itoa(cid)

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

	return data, nil
}

func CheckTenantCustomer(cid, tid int) int {

	var data models.Customers

	q1 := `select a.customerid from tenantcustomers a where a.customerid=` + strconv.Itoa(cid) + ` and a.tenantid=` + strconv.Itoa(tid)

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

	return data.Customerid
}

func CreateCustomerLocation(input models.Customerlocations) int {

	err := db.DB.Create(&input).Error

	if err != nil {

		return 0

	}

	return input.Customerid
}

func GetCustomerLocation(cid int) models.CustomerLocationResult {
	var result models.CustomerLocationResult
	var data []models.Customerlocations
	var q1 string

	if cid != 0 {
		q1 = `SELECT a.locationid, a.customerid, a.address, a.suburb, a.city, a.state, a.landmark, a.doorno, a.postcode,
		      a.latitude, a.longitude, a.defaultaddress, a.primaryaddress, a.status
		      FROM customerlocations a WHERE a.customerid = ` + strconv.Itoa(cid)
	}

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

	result.Code = http.StatusOK
	result.Status = true
	result.Message = "Successful"
	result.Details = data
	return result
}
