package main

import (
	"context"
	"crypto/tls"
	"encoding/base64"
	"encoding/json"
	"encoding/xml"
	"fmt"
	"gocron"
	"gorilla/mux"
	"log"
	"net/http"
	"net/url"
	"ssp/ad"
	"ssp/clickClient"
	"ssp/kafkaClient"
	"ssp/clickConnect"
	"ssp/constants"
	"ssp/customapi"
	"ssp/logger"
	"ssp/redisClient"
	"ssp/validate"
	"ssp/vastxmlstructs"
	"strconv"
	"time"
	"github.com/ClickHouse/ch-go"
	"github.com/ClickHouse/ch-go/proto"
	"io"
	"os"
	"strings"
	"github.com/gofrs/uuid"
	"regexp"

	"ssp/extrafunc"
	"sync"

	"crypto/sha1"
    "encoding/hex"
)
//import "github.com/go-co-op/gocron/v2"


var redisclient = redisClient.Initialize()

var DbTrack = constants.DbTrack

var APIStatus = constants.APIStatus
var APIURL = constants.APIURL
var APIKey = constants.APIKey

func LogResponseNew(data []byte, logName string, label string) {
	filePath := fmt.Sprintf(
		"/home/ubuntu/go/ssp/go-ssp-qa/log/%s.log",
		logName,
	)

	file, err := os.OpenFile(
		filePath,
		os.O_CREATE|os.O_WRONLY|os.O_APPEND,
		0666,
	)
	if err != nil {
		log.Println("Log open error:", err)
		return
	}
	defer file.Close()

	logger := log.New(file, "", log.LstdFlags)
	logger.Println(label, string(data))
}

func LogResponseAll(data string, logName string, label string) {
	filePath := fmt.Sprintf(
		"/home/ubuntu/go/ssp/go-ssp-qa/log/%s.log",
		logName,
	)

	file, err := os.OpenFile(
		filePath,
		os.O_CREATE|os.O_WRONLY|os.O_APPEND,
		0666,
	)
	if err != nil {
		log.Println("Log open error:", err)
		return
	}
	defer file.Close()

	logger := log.New(file, "", log.LstdFlags)
	logger.Println(label, data)
}


// Home Function
func home(w http.ResponseWriter, r *http.Request) {

	html := `<html>
				<title>Golang SSP API</title>    
				<body>
					<h1>` + `Golang SSP API` + `</h1>
				</body>
			</html>`
	w.Write([]byte(fmt.Sprintf(html)))
}

// Home Function
func validataion(w http.ResponseWriter, r *http.Request) {
	html := `loaderio-d853366ab91d80480a5c055b09649ec3`
	w.Write([]byte(fmt.Sprintf(html)))
}

func healthval(w http.ResponseWriter, r *http.Request) {
	 w.WriteHeader(http.StatusOK)
	    w.Write([]byte("Success"))
}

// Function for calculating request elapsed time
func elapsed(what string) func() {
	start := time.Now()
	return func() {
		log.Printf("%s took %v\n", what, time.Since(start))
	}
}

// Struct matching your JSON
type HBTrackingtest struct {
    DateTime   string  `json:"date_time"`
    ZoneID     uint32  `json:"zoneid"`
    HBBidder   string  `json:"hb_bidder"`
    HBSource   string  `json:"hb_source"`
    HBMedia    string  `json:"hb_media"`
    HBSize     string  `json:"hb_size"`
    HBWonBid   float64 `json:"hb_wonbid"`
    Impression uint32  `json:"impression"`
    Country    string  `json:"country"`
    Currency   string  `json:"currency"`
    Click      uint32  `json:"click"`
    Adtype     string  `json:"adtype"`
    Request    uint64  `json:"request"`
    Response   uint64  `json:"response"`
}

func HBEvent(w http.ResponseWriter, r *http.Request) {

	hb_source := r.URL.Query().Get("source")
	currency := r.URL.Query().Get("currency")
	adtype := r.URL.Query().Get("type")

	hb_bidder := r.URL.Query().Get("b")
	hb_size := r.URL.Query().Get("s")
	hb_media := r.URL.Query().Get("f")

	zoneid := r.URL.Query().Get("zoneid")
	zone_id, _ := strconv.Atoi(zoneid)

	request, _ := strconv.Atoi(r.URL.Query().Get("req"))
	response, _ := strconv.Atoi(r.URL.Query().Get("res"))
	click, _ := strconv.Atoi(r.URL.Query().Get("click"))
	impression, _ := strconv.Atoi(r.URL.Query().Get("imp"))

	country :="USD"
	bid := r.URL.Query().Get("bid")
	hb_wonbid := StringToFloat(bid, 64)

	if DbTrack == "clickhouse" {
		clickClient.TrackHB(adtype, uint32(zone_id), hb_bidder, hb_source, hb_media, hb_size, hb_wonbid, country, currency, uint32(impression), uint32(click), uint64(request),uint64(response))
	} else if DbTrack == "kafka" {
		kafkaClient.TrackHB(adtype, uint32(zone_id), hb_bidder, hb_source, hb_media, hb_size, hb_wonbid, country, currency, uint32(impression), uint32(click), uint64(request),uint64(response))
	} else {
		clickClient.TrackHB(adtype, uint32(zone_id), hb_bidder, hb_source, hb_media, hb_size, hb_wonbid, country, currency, uint32(impression), uint32(click), uint64(request),uint64(response))
	}		
}

/*********************** ADX Start *************************/

func hashString(s string) string {
    h := sha1.New()
    h.Write([]byte(s))
    return hex.EncodeToString(h.Sum(nil))
}


func IntPtr(i int) *int {
    return &i
}

func unserializeDSPs(input string) ([]int, error) {
    re := regexp.MustCompile(`s:\d+:"(\d+)"`)
    matches := re.FindAllStringSubmatch(input, -1)

    dsps := make([]int, 0, len(matches))
    for _, m := range matches {
        id, err := strconv.Atoi(m[1])
        if err != nil {
            return nil, err
        }
        dsps = append(dsps, id)
    }

    return dsps, nil
}

type HeaderLog struct {
	RequestID string              `json:"request_id"`
	URL       string              `json:"url,omitempty"`
	Method    string              `json:"method,omitempty"`
	Headers   map[string][]string `json:"headers"`
}

func processRequestadx(w http.ResponseWriter, r *http.Request) {

	/*now := time.Now()
	millis := now.UnixNano() / int64(time.Millisecond)
	fmt.Println("processRequest starting time", millis)*/

	w.Header().Set("Content-Type", "application/json")

	sspName := r.URL.Query().Get("id")

	admin := 0
	sspId := 0

	sspDetails, err := extrafunc.ADXSSPDetail(sspName)
	if err == nil {
		sspId = sspDetails.ID
		admin = sspDetails.AdminMargin
	}

	if err != nil {
	    fmt.Println("ADXSSPDetail failed:", err)
	}

	if sspDetails == nil {
	    fmt.Println("ADXSSPDetail returned nil")
	}

  	dspIDs, err := unserializeDSPs(sspDetails.LinkedDSP)

    body, err := io.ReadAll(r.Body)
    if err != nil {
        http.Error(w, "cannot read body", http.StatusBadRequest)
        return
    }
    defer r.Body.Close()
    Rawbody := string(body)

    fileName1 := "SSPRawRequest_" + strconv.Itoa(sspId)
	LogResponseAll(string(body), fileName1, "RawRequest:")
    //fmt.Println("\nBODY =", string(body))

    var fullReq map[string]interface{}
    if err := json.Unmarshal(body, &fullReq); err != nil {
        http.Error(w, "invalid JSON", http.StatusBadRequest)
        return
    }

    //prettyJSON, _ := json.MarshalIndent(fullReq, "", "  ")
	//fmt.Println(string(prettyJSON))

    requestID := ""
	if id, ok := fullReq["id"].(string); ok {
		requestID = id
	}
	defer elapsed("Request " + requestID)()

	sspLog := HeaderLog{
		RequestID: requestID,
		URL:       r.URL.String(),
		Method:    r.Method,
		Headers:   r.Header,
	}

	b, _ := json.Marshal(sspLog)
	logger.Log.Println("SSP_REQUEST =", string(b))

    u1 := uuid.Must(uuid.NewV4())
	request_Id := u1.String()

	if APIStatus == 1 {

	    var deviceIP, deviceUA string
		var ifa, dpidsha1, dpidmd5, didsha1, didmd5 string

		if deviceObj, ok := fullReq["device"].(map[string]interface{}); ok {

		    if ip, ok := deviceObj["ip"].(string); ok {
		        deviceIP = ip
		    }

		    if ua, ok := deviceObj["ua"].(string); ok {
		        deviceUA = ua
		    }

		    if v, ok := deviceObj["ifa"].(string); ok {
		        ifa = v
		    }

		    if v, ok := deviceObj["dpidsha1"].(string); ok {
	        dpidsha1 = v
		    }

		    if v, ok := deviceObj["dpidmd5"].(string); ok {
		        dpidmd5 = v
		    }

		    if v, ok := deviceObj["didsha1"].(string); ok {
		        didsha1 = v
		    }

		    if v, ok := deviceObj["didmd5"].(string); ok {
		        didmd5 = v
		    }
		}

		var finaldevice string

		if ifa != "" {
		    finaldevice = ifa
		} else if dpidsha1 != "" {
		    finaldevice = dpidsha1
		} else if dpidmd5 != "" {
		    finaldevice = dpidmd5
		} else if didsha1 != "" {
		    finaldevice = didsha1
		} else if didmd5 != "" {
		    finaldevice = didmd5
		} else {
		    finaldevice = ""
		}

		minified, _ := json.Marshal(fullReq)
		prob := CheckFraud(deviceIP, finaldevice, deviceUA)
		raw_request := string(minified)

		if prob > 0.6 {
		    Track_Fraud(sspId, prob, raw_request)
		    w.WriteHeader(http.StatusNoContent)
        	return
		} else {
		    //fmt.Println("✅ Clean Traffic")
		}
	}


	var  banner_type string

    if impList, ok := fullReq["imp"].([]interface{}); ok {

        for i, impObj := range impList {

            impMap, ok := impObj.(map[string]interface{})
            if !ok {
                continue
            }

			if _, exists := impMap["banner"]; exists {
				banner_type = "banner"
			} else if _, exists := impMap["video"]; exists {
				banner_type = "video"
			} else if _, exists := impMap["audio"]; exists {
				banner_type = "audio"
			} else if _, exists := impMap["native"]; exists {
				banner_type = "native"
			}

            oldBF, ok := impMap["bidfloor"].(float64)
            if ok {
                margin := oldBF * float64(admin) / 100
                newBF := oldBF + margin
                //fmt.Println("Old Bidfloor:", oldBF, "New Bidfloor:", newBF)
                impMap["bidfloor"] = newBF
            }
            impList[i] = impMap
        }
        fullReq["imp"] = impList
    }

    updatedJSON, err := json.Marshal(fullReq)
    if err != nil {
        http.Error(w, "failed to marshal JSON", http.StatusInternalServerError)
        return
    }

    //fileName2 := "SSPBidRequest_" + strconv.Itoa(sspId)
	//LogResponseAll(string(updatedJSON), fileName2, "BidRequest:")
    //fmt.Println("\nUPDATED JSON =", string(updatedJSON))

    //logger.Log.Println("SSPReq", fullReq)

    RequestArray := &customapi.CustomRequest{}
    if err := json.Unmarshal(updatedJSON, RequestArray); err != nil {
        http.Error(w, "invalid JSON for CustomRequest", http.StatusBadRequest)
        return
    }

    RawTrackRequestSSP(requestID, RequestArray, []string{"USD"}, sspId, banner_type, Rawbody)
    TrackRequestSSP(request_Id, RequestArray, []string{"USD"}, sspId, banner_type)

    dsp_Ver := "2.6"

	for _, dspID := range dspIDs {

		d, err := extrafunc.ADXDSPDetail(dspID)
		if err != nil || d == nil {
			continue
		}

		dspVer := "2.5"
		if d.OpenRtbVersion == "5" {
			dspVer = "2.6"
		}

		RequestArray.Dsp = append(RequestArray.Dsp, customapi.Dsp{
			ID:             d.ExchangeID,
			Ver:            dspVer,
			Ping_url:       d.PingURL,
			AT:             d.AuctionType,
			Cur:            []string{"USD"},
			Gzip:           IntPtr(d.Gzip),
			SeconBidBuffer: 0,
		})
	}

	//RequestArray.Dsp = loadDSPsParallel(dspIDs)

	if len(RequestArray.Dsp) == 0 {
		logger.Log.Println("DSP list empty")
		fmt.Println("DSP list empty")
    } else {
    	 dsp := RequestArray.Dsp[0]
    	 dsp_Ver = dsp.Ver
    }	
    var ResponseArray map[string]interface{}
    var processErr error

    if dsp_Ver == "2.6" {
        ResponseArray, processErr = adxgetAD26(RequestArray, request_Id, sspId)
    } else {
        ResponseArray, processErr = adxgetAD25(RequestArray, request_Id, sspId)
    }

    if processErr != nil {
        http.Error(w, processErr.Error(), http.StatusBadRequest)
        return
    }
    w.WriteHeader(http.StatusOK)
    json.NewEncoder(w).Encode(ResponseArray)
}

func processRequestadxQA(w http.ResponseWriter, r *http.Request) {

	now := time.Now()
	millis := now.UnixNano() / int64(time.Millisecond)
	fmt.Println("processRequest starting time", millis)

    w.Header().Set("Content-Type", "application/json")

	sspName := r.URL.Query().Get("id")

	admin := 0
	sspId := 0

	sspDetails, err := extrafunc.ADXSSPDetail(sspName)
	if err == nil {
		sspId = sspDetails.ID
		admin = sspDetails.AdminMargin
	}

	if err != nil {
	    fmt.Println("ADXSSPDetail failed:", err)
	}

	if sspDetails == nil {
	    fmt.Println("ADXSSPDetail returned nil")
	}

  	dspIDs, err := unserializeDSPs(sspDetails.LinkedDSP)

    body, err := io.ReadAll(r.Body)
    if err != nil {
        http.Error(w, "cannot read body", http.StatusBadRequest)
        return
    }
    defer r.Body.Close()

    fmt.Println("\nBODY =", string(body))
    Rawbody := string(body)
    var fullReq map[string]interface{}

    if err := json.Unmarshal(body, &fullReq); err != nil {
        http.Error(w, "invalid JSON", http.StatusBadRequest)
        return
    }

	fmt.Println("fullReq",fullReq)

    requestID, ok := fullReq["id"].(string)
	if !ok {
	    http.Error(w, "request id not found", http.StatusBadRequest)
	    return
	}

	fmt.Println("Request ID:", requestID)

    u1 := uuid.Must(uuid.NewV4())
	request_Id := u1.String()

	fmt.Println("request_Id",request_Id)

    if APIStatus == 1 {

	    var deviceIP, deviceUA string
		var ifa, dpidsha1, dpidmd5, didsha1, didmd5 string

		if deviceObj, ok := fullReq["device"].(map[string]interface{}); ok {

		    if ip, ok := deviceObj["ip"].(string); ok {
		        deviceIP = ip
		    }

		    if ua, ok := deviceObj["ua"].(string); ok {
		        deviceUA = ua
		    }

		    if v, ok := deviceObj["ifa"].(string); ok {
		        ifa = v
		    }

		    if v, ok := deviceObj["dpidsha1"].(string); ok {
	        dpidsha1 = v
		    }

		    if v, ok := deviceObj["dpidmd5"].(string); ok {
		        dpidmd5 = v
		    }

		    if v, ok := deviceObj["didsha1"].(string); ok {
		        didsha1 = v
		    }

		    if v, ok := deviceObj["didmd5"].(string); ok {
		        didmd5 = v
		    }
		}

		var finaldevice string

		if ifa != "" {
		    finaldevice = ifa
		} else if dpidsha1 != "" {
		    finaldevice = dpidsha1
		} else if dpidmd5 != "" {
		    finaldevice = dpidmd5
		} else if didsha1 != "" {
		    finaldevice = didsha1
		} else if didmd5 != "" {
		    finaldevice = didmd5
		} else {
		    finaldevice = ""
		}

		minified, _ := json.Marshal(fullReq)
		prob := CheckFraud(deviceIP, finaldevice, deviceUA)
		raw_request := string(minified)

		if prob > 0.6 {
		    Track_Fraud(sspId, prob, raw_request)
		    w.WriteHeader(http.StatusNoContent)
        	return
		} else {
		    //fmt.Println("✅ Clean Traffic")
		}
	}
    
	var  banner_type string
    if impList, ok := fullReq["imp"].([]interface{}); ok {

        for i, impObj := range impList {

            impMap, ok := impObj.(map[string]interface{})
            if !ok {
                continue
            }

			if _, exists := impMap["banner"]; exists {
				banner_type = "banner"
			} else if _, exists := impMap["video"]; exists {
				banner_type = "video"
			} else if _, exists := impMap["audio"]; exists {
				banner_type = "audio"
			} else if _, exists := impMap["native"]; exists {
				banner_type = "native"
			}

            oldBF, ok := impMap["bidfloor"].(float64)
            if ok {
                margin := oldBF * float64(admin) / 100
                newBF := oldBF + margin
                fmt.Println("Old Bidfloor:", oldBF, "New Bidfloor:", newBF)
                impMap["bidfloor"] = newBF
            }
            impList[i] = impMap
        }
        fullReq["imp"] = impList
    }

    updatedJSON, err := json.Marshal(fullReq)
    if err != nil {
        http.Error(w, "failed to marshal JSON", http.StatusInternalServerError)
        return
    }

    fmt.Println("\nUPDATED JSON =", string(updatedJSON))

    RequestArray := &customapi.CustomRequest{}
    if err := json.Unmarshal(updatedJSON, RequestArray); err != nil {
        http.Error(w, "invalid JSON for CustomRequest", http.StatusBadRequest)
        return
    }

	RawTrackRequestSSP(requestID, RequestArray, []string{"USD"}, sspId, banner_type,Rawbody)
	TrackRequestSSP(request_Id, RequestArray, []string{"USD"}, sspId, banner_type)

	dsp_Ver := "2.6"

	for _, dspID := range dspIDs {

		d, err := extrafunc.ADXDSPDetail(dspID)
		if err != nil || d == nil {
			continue
		}

		dspVer := "2.5"
		if d.OpenRtbVersion == "5" {
			dspVer = "2.6"
		}

		RequestArray.Dsp = append(RequestArray.Dsp, customapi.Dsp{
			ID:             d.ExchangeID,
			Ver:            dspVer,
			Ping_url:       d.PingURL,
			AT:             d.AuctionType,
			Cur:            []string{"USD"},
			Gzip:           IntPtr(d.Gzip),
			SeconBidBuffer: 0,
		})
	}

	//RequestArray.Dsp = loadDSPsParallel(dspIDs)

	if len(RequestArray.Dsp) == 0 {
		fmt.Println("DSP list empty")
    } else {
    	 dsp := RequestArray.Dsp[0]
    	 dsp_Ver = dsp.Ver
    }	
    var ResponseArray map[string]interface{}
    var processErr error

    if dsp_Ver == "2.6" {
        ResponseArray, processErr = adxgetAD26(RequestArray, request_Id, sspId)
    } else {
        ResponseArray, processErr = adxgetAD25(RequestArray, request_Id, sspId)
    }

    if processErr != nil {
        http.Error(w, processErr.Error(), http.StatusBadRequest)
        return
    }
    w.WriteHeader(http.StatusOK)
    json.NewEncoder(w).Encode(ResponseArray)
}

type FraudResponse struct {
    Probability float64 `json:"probability"`
}

var httpClient = &http.Client{
    Timeout: 200 * time.Millisecond,
}

func CheckFraud(deviceIP, ifa, deviceUA string) float64 {

    uaHash := hashString(deviceUA)
    fraudKey := fmt.Sprintf("fraud:%s:%s:%s", deviceIP, ifa, uaHash)///line 669

    var probability float64
    err := redisclient.GetKey(fraudKey, &probability)
    if err == nil {
        return probability
    }

    baseURL := APIURL
    params := url.Values{}
    params.Add("ip", deviceIP)
    params.Add("deviceId", ifa)
    params.Add("userAgent", deviceUA)

    req, err := http.NewRequest(http.MethodGet, baseURL+"?"+params.Encode(), nil)
    if err != nil {
        return 0
    }

    req.Header.Set("Accept", "application/json")
    req.Header.Set("x-api-key", APIKey)

    resp, err := httpClient.Do(req)
    if err != nil {
        return 0
    }
    defer resp.Body.Close()

    if resp.StatusCode != 200 {
        return 0
    }

    var result FraudResponse
    if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
        return 0
    }

    redisclient.SetKey(fraudKey, result.Probability, 24*time.Hour)

    return result.Probability
}

func Track_Fraud(sspId int, prob float64, raw_request string) {
	if DbTrack == "clickhouse" {
		kafkaClient.Track_Fraud(uint16(sspId), prob, raw_request)
	} else if DbTrack == "kafka" {
		kafkaClient.Track_Fraud(uint16(sspId), prob, raw_request)
	} else {
		kafkaClient.Track_Fraud(uint16(sspId), prob, raw_request)
	}
}

func loadDSPsParallel(dspIDs []int) []customapi.Dsp {
	var (
		wg     sync.WaitGroup
		mutex  sync.Mutex
		result = make([]customapi.Dsp, 0, len(dspIDs))
	)

	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Millisecond)
	defer cancel()

	for _, id := range dspIDs {
		wg.Add(1)

		go func(dspID int) {
			defer wg.Done()

			select {
			case <-ctx.Done():
				return
			default:
			}

			d, err := extrafunc.ADXDSPDetail(dspID)
			if err != nil || d == nil {
				return
			}

			ver := "2.5"
			if d.OpenRtbVersion == "5" {
				ver = "2.6"
			}

			dsp := customapi.Dsp{
				ID:             d.ExchangeID,
				Ver:            ver,
				Ping_url:       d.PingURL,
				AT:             d.AuctionType,
				Cur:            []string{"USD"},
				Gzip:           IntPtr(d.Gzip),
				SeconBidBuffer: 0,
			}

			mutex.Lock()
			result = append(result, dsp)
			mutex.Unlock()
		}(id)
	}

	wg.Wait()
	return result
}

func adxgetAD25(RequestArray *customapi.CustomRequest, request_id string, sspId int) (map[string]interface{}, error) {
	
	Channel := make(chan map[string]interface{})
	ResponseArray := make(map[string]interface{})
	
	ErrorArray := validate.ValidateRequest(RequestArray)
	if len(ErrorArray) == 0 {
	
		go ad.Ssp_adxadprocessing25(Channel, RequestArray, redisclient, request_id,sspId)
		ResponseArray = <-Channel
		return ResponseArray, nil
	} else {
		return ResponseArray, ErrorArray[0]
	}
}


func adxgetAD26(RequestArray *customapi.CustomRequest, request_id string, sspId int) (map[string]interface{}, error) {

	Channel := make(chan map[string]interface{})
	ResponseArray := make(map[string]interface{})
	ErrorArray := validate.ValidateRequest(RequestArray)

	if len(ErrorArray) == 0 {
		go ad.Ssp_adxadprocessing26(Channel, RequestArray, redisclient, request_id,sspId)
		ResponseArray = <-Channel
		return ResponseArray, nil
	} else {
		return ResponseArray, ErrorArray[0]
	}
}

func getRequestDetails(r *http.Request) map[string]interface{} {
	req_details := make(map[string]interface{})
	req_details["ssp_name"] = r.URL.Query().Get("id")
	req_details["key"] = r.URL.Query().Get("secret_key")
	req_details["Method"] = r.Method
	req_details["URL"] = r.URL.String()
	req_details["Proto"] = r.Proto
	req_details["Host"] = r.Host
	req_details["RemoteAddr"] = r.RemoteAddr
	protocol := "http"
	if r.TLS != nil {
		protocol = "https"
	}
	req_details["protocol"] = protocol
	fmt.Println("Portocal :", protocol)
	for k, v := range r.Header {
		req_details[k] = v
	}
	return req_details
}

func ArrayToStringPrism(a interface{}, delim string) string {
	return strings.Trim(strings.Replace(fmt.Sprint(a), " ", delim, -1), "[]")
}

func TrackRequestSSP(request_id string, req *customapi.CustomRequest, cur []string, dsp_id int, banner_type string) {
	t := time.Now()
	y := t.Year()
	var user_age int
	var currency, country, domain, os, ip, ua, browser, lan, make, model, device_type, page, ref, gender string

	if len(cur) > 0 {
		currency = ArrayToStringPrism(cur, ",")
	}
	if req.Device.Geo != nil {

		country = req.Device.Geo.Country
	}
	if req.Site != nil {
		domain = req.Site.Domain
		page = req.Site.Page
		ref = req.Site.Ref
	}
	if req.Device != nil {
		os = req.Device.OS
		ip = req.Device.IP
		ua = req.Device.UA
		lan = req.Device.Language
		make = req.Device.Make
		model = req.Device.Model
		// device_type = fmt.Sprint(req.Device.DeviceType)
		if req.Device.DeviceType == 1 || req.Device.DeviceType == 4 {
			device_type = "Mobile"
		} else if req.Device.DeviceType == 2 {
			device_type = "Personal Computer"
		} else if req.Device.DeviceType == 3 {
			device_type = "Connected TV"
		} else if req.Device.DeviceType == 5 {
			device_type = "Tablet"
		} else if req.Device.DeviceType == 6 {
			device_type = "Connected Device"
		} else if req.Device.DeviceType == 7 {
			device_type = "Set top Box"
		}
	}

	if req.User != nil {
		gender = req.User.Gender
		if req.User.YOB != 0 {
			user_age = y - req.User.YOB
		}
	}

	if DbTrack == "clickhouse" {
		clickClient.Track_requestSSP(request_id, uint16(dsp_id), banner_type, country, domain, os, ip, ua, lan, currency, fmt.Sprint(user_age), gender, browser, device_type, make, model, page, ref)
	} else if DbTrack == "kafka" {
		kafkaClient.Track_requestSSP(request_id, uint16(dsp_id), banner_type, country, domain, os, ip, ua, lan, currency, fmt.Sprint(user_age), gender, browser, device_type, make, model, page, ref)
	} else {
		clickClient.Track_requestSSP(request_id, uint16(dsp_id), banner_type, country, domain, os, ip, ua, lan, currency, fmt.Sprint(user_age), gender, browser, device_type, make, model, page, ref)
	}	
}

func RawTrackRequestSSP(requestID string, req *customapi.CustomRequest, cur []string, dsp_id int, banner_type string, Rawbody string) {
	var (
		channelId      string
		streamId       string
		contentTitle   string
		appBundle      string
		appName        string
		publisherID    string
		platform       string
		deviceIFA      string
		sourceID       string
		sourceType     string
		rawIP          string
		//ipSource 		string
		//hashedIP 		string
		ssaiMode       string
		contentURL     string
		podID          string
		podSlotNumber  int
		podSlotTotal   int
		adSlotWidth    int
		adSlotHeight   int
		vastVersion    string
		placementID    string
		passKey        string
		sessionID      string
		adDuration     int
		deviceDNT     int
	)

	if req.Ext != nil && req.Ext.BNS != nil {
		bns := req.Ext.BNS

		channelId = bns.ChannelID
		streamId = bns.StreamID
		contentTitle = bns.ContentTitle
		//appBundle = bns.App
		//appName = bns.Channel
		publisherID = bns.RefID
		//platform = bns.Format
		//deviceIFA = bns.DeviceID
		//sourceID = bns.DeviceSession
		//sourceType = bns.Placement

		passKey = bns.PassKey
		adDuration = bns.AdDuration
		ssaiMode = bns.SSAIMode
		placementID = bns.PlacementID

		sessionID = bns.SessionID
		contentURL = bns.ContentURL
		
		podID = bns.PodID
		podSlotNumber = bns.PodSlotNumber
		podSlotTotal = bns.PodSlotTotal
		adSlotWidth = bns.AdSlotWidth
		adSlotHeight = bns.AdSlotHeight
		vastVersion = bns.VASTVersion
	}

	if req.App != nil {
	    appBundle = req.App.Bundle
	    appName = req.App.Name 

	    sourceType = "App"
	    if req.App.Publisher != nil {
	        sourceID = req.App.Publisher.ID
	    }

	    if req.Device != nil {
	        platform = req.Device.OS // "Android" or "iOS"
	    }
	}

	fmt.Println(passKey)
	fmt.Println(adDuration)
	fmt.Println(ssaiMode)
	fmt.Println(placementID)

	if req.Device != nil {
	    deviceIFA = req.Device.IFA
	    deviceDNT = req.Device.DNT // 0 = Tracking allowed, 1 = Do Not Track
    	//lmt = req.Device.Lmt // 0 = Tracking allowed, 1 = Limit Ad Tracking

    	if req.Device.IP != "" {
	        rawIP = req.Device.IP
	    } else if req.Device.IPv6 != "" {
	        rawIP = req.Device.IPv6
	    }
	}

	var country, state, city, metro, latitude, longitude, dpidmd5 string
	if req.Device != nil && req.Device.Geo != nil {
		country = req.Device.Geo.Country
		state = req.Device.Geo.Region
		city = req.Device.Geo.City
		metro = req.Device.Geo.Metro
		latitude = fmt.Sprint(req.Device.Geo.Lat)
		longitude = fmt.Sprint(req.Device.Geo.Lon)
	}

	
	deviceTypeUint16 := uint16(0)
	if req.Device != nil {
		deviceTypeUint16 = uint16(req.Device.DeviceType)
		dpidmd5 = req.Device.PIDMD5
	}

	if DbTrack == "clickhouse" {
		clickClient.Track_raw_bid_request(requestID, uint16(dsp_id),appBundle, appName, publisherID,platform,deviceTypeUint16, uint16(deviceDNT), deviceIFA,sourceID, sourceType,rawIP, dpidmd5,country, state, city, metro, latitude, longitude, channelId, contentTitle, streamId, sessionID, contentURL, podID,uint16(podSlotTotal),uint16(podSlotNumber),uint16(adSlotHeight),uint16(adSlotWidth),vastVersion,Rawbody)
	} else if DbTrack == "kafka" {
		kafkaClient.Track_raw_bid_request(requestID, uint16(dsp_id),appBundle, appName, publisherID,platform,deviceTypeUint16, uint16(deviceDNT), deviceIFA,sourceID, sourceType,rawIP, dpidmd5,country, state, city, metro, latitude, longitude, channelId, contentTitle, streamId, sessionID, contentURL, podID,uint16(podSlotTotal),uint16(podSlotNumber),uint16(adSlotHeight),uint16(adSlotWidth),vastVersion,Rawbody)
	} else {
		clickClient.Track_raw_bid_request(requestID, uint16(dsp_id),appBundle, appName, publisherID,platform,deviceTypeUint16, uint16(deviceDNT), deviceIFA,sourceID, sourceType,rawIP, dpidmd5,country, state, city, metro, latitude, longitude, channelId, contentTitle, streamId, sessionID, contentURL, podID,uint16(podSlotTotal),uint16(podSlotNumber),uint16(adSlotHeight),uint16(adSlotWidth),vastVersion,Rawbody)
	}	
}

func processVastTrackingadx(w http.ResponseWriter, r *http.Request) {
	q := r.URL.Query()

	adxid, _ := strconv.Atoi(r.URL.Query().Get("adxid"))
	
	exchangeid, _ := strconv.Atoi(r.URL.Query().Get("exchangeid"))
	event := r.URL.Query().Get("event")
	// offer report tracking---------------------------------------------
	campaignID, _ := strconv.Atoi(q.Get("campaignid"))
	offerID := q.Get("offerid")
	offerName := q.Get("offer_name")
	adRequestID := q.Get("requestid")
	creativeID := q.Get("creativeid")
	supplyID := q.Get("supply_id")
	sourceImpID := q.Get("source_impression_id")
	offerSentID := q.Get("offer_sent_id")
	offerSentStat := q.Get("offer_sent_status")
	offerAssignID := q.Get("offer_assignment_id")
	attribClearID := q.Get("attributed_cleared_impression_id")
	appBundle := q.Get("app_bundle")
	appName := q.Get("app_name")
	platform := q.Get("platform")
	invSourceID := q.Get("inv_source_id")
	invSourceType := q.Get("inv_source_type")
	supplyName := q.Get("supply_name")
	pubID := q.Get("pub_id")
	pubName := q.Get("pub_name")
	sessionID := q.Get("playback_session_id")
	contentID := q.Get("content_id")
	contentTitle := q.Get("content_title")
	
	if DbTrack == "clickhouse" {
		clickClient.Track_vastSSP(uint16(exchangeid), uint64(adxid), event)
		clickClient.Track_vastDSP(uint16(exchangeid), uint64(adxid), event)
		if event=="complete"{
		clickClient.Track_offer_report_stats(
            offerSentID, offerSentStat, offerID, offerName ,offerAssignID,
            uint32(campaignID),
            attribClearID, sourceImpID, adRequestID, creativeID,
            appBundle, appName, invSourceID, invSourceType, platform,
            supplyID, supplyName, pubID, pubName,
            sessionID, contentID, contentTitle,
        )
		//    clickClient.Track_offer_send(
        //     sessionID, adRequestID, offerID, supplyID, q.Get("adxid"),
        //     clickClient.ClientIPFromRequest(r),
        // )

		}
		} else if DbTrack == "kafka" {
		kafkaClient.Track_vastSSP(uint16(exchangeid), uint64(adxid), event)
		kafkaClient.Track_vastDSP(uint16(exchangeid), uint64(adxid), event)
		if event =="complete"{
			kafkaClient.Track_offer_report_stats(
			offerSentID, offerSentStat, offerID, offerName, offerAssignID,
			uint32(campaignID),
			attribClearID, sourceImpID, adRequestID, creativeID,
			appBundle, appName, invSourceID, invSourceType, platform,
			supplyID, supplyName, pubID, pubName,
			sessionID, contentID, contentTitle,
		)
		}
	} else {
		clickClient.Track_vastSSP(uint16(exchangeid), uint64(adxid), event)
		clickClient.Track_vastDSP(uint16(exchangeid), uint64(adxid), event)
		if event=="complete"{
			clickClient.Track_offer_report_stats(
            offerSentID, offerSentStat, offerID, offerName ,offerAssignID,
            uint32(campaignID),
            attribClearID, sourceImpID, adRequestID, creativeID,
            appBundle, appName, invSourceID, invSourceType, platform,
            supplyID, supplyName, pubID, pubName,
            sessionID, contentID, contentTitle,
        )
		}
	}	

	return
}

func processImpUrladx(w http.ResponseWriter, r *http.Request) {
	adxid := r.URL.Query().Get("adxid")
	bidderid := r.URL.Query().Get("bidderid")
	requestid := r.URL.Query().Get("requestid")
	ssp_req_Id := r.URL.Query().Get("ssp_req_Id")
	banner_type := r.URL.Query().Get("banner_type")
	price := r.URL.Query().Get("won_price")

	bidder_id, _ := strconv.Atoi(bidderid)
	adx_id, _ := strconv.Atoi(adxid)

	encodedNURL := r.URL.Query().Get("imprice")
	nurlBytes, _ := base64.StdEncoding.DecodeString(encodedNURL)
	adminMarginStr := string(nurlBytes)
	adminMargin, _ := strconv.ParseFloat(adminMarginStr, 64)

	auction_price := StringToFloat(price, 64)
	Track_ADXImp(requestid, bidder_id, adx_id, banner_type, auction_price,adminMargin)
	Track_ADXRawImp(ssp_req_Id, bidder_id, adx_id, banner_type, auction_price,adminMargin)
}

func Track_ADXRawImp(request_id string, dsp_id int, adxid int, banner_type string, won_price float64, adminMargin float64) {

	finalPrice := won_price + adminMargin

    switch DbTrack {
    case "clickhouse":
        clickClient.RawTrack_Imp(request_id, uint16(dsp_id), uint16(adxid), banner_type, finalPrice, adminMargin)
    case "kafka":
        kafkaClient.RawTrack_Imp(request_id, uint16(dsp_id), uint16(adxid), finalPrice, adminMargin)
    default:
        clickClient.RawTrack_Imp(request_id, uint16(dsp_id), uint16(adxid), banner_type, finalPrice, adminMargin)
    }
}

func Track_ADXImp(request_id string, dsp_id int, adxid int, banner_type string, won_price float64, adminMargin float64) {

	finalPrice := won_price + adminMargin

    switch DbTrack {
    case "clickhouse":
        clickClient.Track_ImpSSP(request_id, uint16(dsp_id), uint16(adxid), banner_type, won_price, adminMargin)
        clickClient.Track_ImpDSP(request_id, uint16(dsp_id), uint16(adxid), banner_type, finalPrice, adminMargin)
    case "kafka":
        kafkaClient.Track_ImpSSP(request_id, uint16(dsp_id), uint16(adxid), won_price, adminMargin)
        kafkaClient.Track_ImpDSP(request_id, uint16(dsp_id), uint16(adxid), finalPrice, adminMargin)
    default:
        clickClient.Track_ImpSSP(request_id, uint16(dsp_id), uint16(adxid), banner_type, won_price, adminMargin)
        clickClient.Track_ImpDSP(request_id, uint16(dsp_id), uint16(adxid), banner_type, finalPrice, adminMargin)
    }
}

func processBillingnoticeadx(w http.ResponseWriter, r *http.Request) {

	// id := r.URL.Query().Get("id")
	//~ bidderid := r.URL.Query().Get("bidderid")

	burl, err := base64.StdEncoding.DecodeString(r.URL.Query().Get("burl"))
	if err != nil {
		logger.Log.Println("Error : ", err.Error())
		return
	}
	// Make a cURL get request
	resp, err := http.Get(string(burl))

	// Log error when request not successful
	if err != nil {
		logger.Log.Println("Error : ", err.Error())
		return
	}

	// Close response body
	defer resp.Body.Close()

}

func processWinnoticeadxOL(w http.ResponseWriter, r *http.Request) {

	// Read params
	id := r.URL.Query().Get("id")
	bidderid := r.URL.Query().Get("bidderid")
	encodedNURL := r.URL.Query().Get("nurl")

	if encodedNURL == "" {
		http.Error(w, "missing nurl", http.StatusBadRequest)
		return
	}

	// Decode base64 nurl
	nurlBytes, err := base64.StdEncoding.DecodeString(encodedNURL)
	if err != nil {
		logger.Log.Println("Base64 decode error:", err.Error())
		http.Error(w, "invalid nurl", http.StatusBadRequest)
		return
	}

	nurl := string(nurlBytes)

	fmt.Println(
		"WinNotice received",
		"id:", id,
		"bidderid:", bidderid,
		"nurl:", nurl,
	)

	// HTTP client with timeout (VERY IMPORTANT)
	client := &http.Client{
		Timeout: 2 * time.Second,
	}

	resp, err := client.Get(nurl)
	if err != nil {
		fmt.Println("DSP win notice error:", err.Error())
		http.Error(w, "DSP call failed", http.StatusBadGateway)
		return
	}
	defer resp.Body.Close()

	fmt.Println("DSP win notice status:", resp.StatusCode)

	// Respond immediately to caller
	w.WriteHeader(http.StatusOK)
	w.Write([]byte("OK"))
}

func processWinnoticeadx(w http.ResponseWriter, r *http.Request) {

	auctionID := r.URL.Query().Get("auctionId")
	fmt.Println("auctionID", auctionID)

	Bidid := r.URL.Query().Get("bidid")
	fmt.Println("Bidid", Bidid)

	priceStr := r.URL.Query().Get("price")
	Price, _ := strconv.ParseFloat(priceStr, 64)

	logger.Log.Println("auctionID : ",auctionID)
	logger.Log.Println("Bidid : ",Bidid)
	logger.Log.Println("priceStr : ",priceStr)

	redisKey := fmt.Sprintf("win:%s", auctionID)

	var nurl string
	err := redisclient.GetKey(redisKey, &nurl)
	if err != nil {
	    log.Println("Redis GET error:", err)
	    return
	}

	if nurl == "" {
	    log.Println("Win notice not found or expired")
	    return
	}
	logger.Log.Println("nurl : ",nurl)
	fmt.Println("Win Notice URL:", nurl)

	u, err := url.Parse(nurl)
	if err != nil {
	    log.Fatal(err)
	}
	q := u.Query()

	auction_ID := q.Get("id")
	bidderID  := q.Get("bidderid")
	adxID     := q.Get("adxid")
	nurlParam := q.Get("nurl")

	fmt.Println("auctionID:", auction_ID)
	fmt.Println("bidderID:", bidderID)
	fmt.Println("adxID:", adxID)

	nurlBytes, _ := base64.StdEncoding.DecodeString(nurlParam)
	NurlStr := string(nurlBytes)

	fmt.Println("NurlStr:", NurlStr)

	logger.Log.Println("NurlStr : ",NurlStr)

	u1, err1 := url.Parse(NurlStr)
	if err1 != nil {
	    log.Fatal(err1)
	}
	q1 := u1.Query()
	finalPriceStr := q1.Get("price")
	finalPrice, _ := strconv.ParseFloat(finalPriceStr, 64)

	bidderIDInt, _ := strconv.Atoi(bidderID)
	adxIDInt, _ := strconv.Atoi(adxID)

	banner_type := "video"

	// HTTP client with timeout (VERY IMPORTANT)
	client := &http.Client{
		Timeout: 2 * time.Second,
	}

	resp, errn := client.Get(NurlStr)
	if errn != nil {
		fmt.Println("DSP win notice error:", err.Error())
		http.Error(w, "DSP call failed", http.StatusBadGateway)
		return
	}
	defer resp.Body.Close()

	fmt.Println("DSP win notice status:", resp.StatusCode)

	ad.Track_winDSP(auctionID, bidderIDInt, adxIDInt, banner_type, float64(Price))
	ad.Track_winSSP(auctionID, bidderIDInt, adxIDInt, banner_type, float64(finalPrice))
}

func processVastWrapperadx(w http.ResponseWriter, r *http.Request) {

	var (
		x   []byte
		err error
	)
	xmlS := &vastxmlstructs.VastTypes{}
	key := r.URL.Query().Get("key")
	err = redisclient.GetKey(key, xmlS)

	if xmlS.VAST2 != nil {
		x, err = xml.MarshalIndent(xmlS.VAST2, "", "  ")
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
	} else if xmlS.WVAST2 != nil {
		x, err = xml.MarshalIndent(xmlS.WVAST2, "", "  ")
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
	} else if xmlS.VAST3 != nil {
		x, err = xml.MarshalIndent(xmlS.VAST3, "", "  ")
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
	} else if xmlS.WVAST3 != nil {
		x, err = xml.MarshalIndent(xmlS.WVAST3, "", "  ")
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
	} else if xmlS.VAST4 != nil {
		x, err = xml.MarshalIndent(xmlS.VAST4, "", "  ")
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
	} else if xmlS.WVAST4 != nil {
		x, err = xml.MarshalIndent(xmlS.WVAST4, "", "  ")
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
	} else if xmlS.VAST41 != nil {
		x, err = xml.MarshalIndent(xmlS.VAST41, "", "  ")
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
	} else if xmlS.WVAST41 != nil {
		x, err = xml.MarshalIndent(xmlS.WVAST41, "", "  ")
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
	}
	if err != nil {
		logger.Log.Println("Key : "+key+" expired or error in getting redis key: ", err.Error())
		http.Error(w, "Not Found", http.StatusNotFound)
		return
	}

	allowedHeaders := "Accept, Content-Type, Content-Length, Accept-Encoding, Authorization,X-CSRF-Token"
	w.Header().Set("Access-Control-Allow-Origin", "*")
	u, _ := url.Parse(r.Header.Get("Referer"))
	w.Header().Set("Content-Type", "text/xml; charset=utf-8")
	w.Header().Set("Access-Control-Allow-Origin", u.Scheme+"://"+u.Host)
	w.Header().Set("Access-Control-Allow-Credentials", "true")
	w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
	w.Header().Set("Access-Control-Allow-Headers", allowedHeaders)
	w.Header().Set("Access-Control-Expose-Headers", "Authorization")
	w.Write(x)
}

/*********************** ADX End *************************/


// Function for processing incoming request
func processRequest(w http.ResponseWriter, r *http.Request) {

	ResponseArray := make(map[string]interface{})
	RequestArray := &customapi.CustomRequest{}

	// create header
	w.Header().Add("Content-Type", "application/json")

	err := json.NewDecoder(r.Body).Decode(&RequestArray)
	fmt.Printf("Alpha request%+v\n", RequestArray)

	if err != nil {
		ResponseArray["message"] = "Request Error"
		w.WriteHeader(http.StatusBadRequest)
		json.NewEncoder(w).Encode(ResponseArray)
		return
	}

	if len(RequestArray.Dsp) > 0 {
		for _, dsp := range RequestArray.Dsp {
			version := dsp.Ver

			switch version {
			case "2.6":
				ResponseArray, err = getAD26(RequestArray)
			case "2.5":
				ResponseArray, err = getAD25(RequestArray)
			default:
				ResponseArray, err = getAD25(RequestArray)
			}
		}
	}	

	//~ return

	if err != nil {
		ResponseArray["message"] = err.Error()
		w.WriteHeader(http.StatusBadRequest)
		json.NewEncoder(w).Encode(ResponseArray)
		return
	} else {
		w.WriteHeader(http.StatusOK)
		json.NewEncoder(w).Encode(ResponseArray)
		return
	}
}

// Function for getting AD
func getAD25(RequestArray *customapi.CustomRequest ) (map[string]interface{}, error) {
	Channel := make(chan map[string]interface{})
	ResponseArray := make(map[string]interface{})
	ErrorArray := validate.ValidateRequest(RequestArray)

	if len(ErrorArray) == 0 {
		go ad.Ssp_adprocessing25(Channel, RequestArray, redisclient )
		ResponseArray = <-Channel
		return ResponseArray, nil
	} else {
		return ResponseArray, ErrorArray[0]
	}
}

// Function for getting AD
func getAD26(RequestArray *customapi.CustomRequest) (map[string]interface{}, error) {
	Channel := make(chan map[string]interface{})
	ResponseArray := make(map[string]interface{})
	ErrorArray := validate.ValidateRequest(RequestArray)

	if len(ErrorArray) == 0 {
		go ad.Ssp_adprocessing26(Channel, RequestArray, redisclient)
		ResponseArray = <-Channel
		return ResponseArray, nil
	} else {
		return ResponseArray, ErrorArray[0]
	}
}

// Function for processing Win Notice request
func processWinnoticeold(w http.ResponseWriter, r *http.Request) {
	//~ id := r.URL.Query().Get("id")
	//~ bidderid := r.URL.Query().Get("bidderid")
	nurl, err := base64.StdEncoding.DecodeString(r.URL.Query().Get("nurl"))
	if err != nil {
		logger.Log.Println("Error : ", err.Error())
		return
	}
	// Make a cURL get request
	resp, err := http.Get(string(nurl))
	// Log error when request not successful
	if err != nil {
		logger.Log.Println("Error : ", err.Error())
		return
	}

	// Close response body
	defer resp.Body.Close()
}

func processWinnotice(w http.ResponseWriter, r *http.Request) {

	// Read params
	id := r.URL.Query().Get("id")
	bidderid := r.URL.Query().Get("bidderid")
	encodedNURL := r.URL.Query().Get("nurl")

	if encodedNURL == "" {
		http.Error(w, "missing nurl", http.StatusBadRequest)
		return
	}

	// Decode base64 nurl
	nurlBytes, err := base64.StdEncoding.DecodeString(encodedNURL)
	if err != nil {
		logger.Log.Println("Base64 decode error:", err.Error())
		http.Error(w, "invalid nurl", http.StatusBadRequest)
		return
	}

	nurl := string(nurlBytes)

	fmt.Println(
		"WinNotice received",
		"id:", id,
		"bidderid:", bidderid,
		"nurl:", nurl,
	)

	// HTTP client with timeout (VERY IMPORTANT)
	client := &http.Client{
		Timeout: 2 * time.Second,
	}

	resp, err := client.Get(nurl)
	if err != nil {
		fmt.Println("DSP win notice error:", err.Error())
		http.Error(w, "DSP call failed", http.StatusBadGateway)
		return
	}
	defer resp.Body.Close()

	fmt.Println("DSP win notice status:", resp.StatusCode)

	// Respond immediately to caller
	w.WriteHeader(http.StatusOK)
	w.Write([]byte("OK"))
}

// Function for processing Win Notice request
func processBillingnotice(w http.ResponseWriter, r *http.Request) {

	// id := r.URL.Query().Get("id")
	//~ bidderid := r.URL.Query().Get("bidderid")

	burl, err := base64.StdEncoding.DecodeString(r.URL.Query().Get("burl"))
	if err != nil {
		logger.Log.Println("Error : ", err.Error())
		return
	}
	// Make a cURL get request
	resp, err := http.Get(string(burl))

	// Log error when request not successful
	if err != nil {
		logger.Log.Println("Error : ", err.Error())
		return
	}

	// Close response body
	defer resp.Body.Close()

}

// Function for processing Ad Click request
func processImpUrl(w http.ResponseWriter, r *http.Request) {
	// ProcessDetails := make(map[string]interface{})
	zoneid := r.URL.Query().Get("zoneid")
	// bannerid := r.URL.Query().Get("bannerid")
	// campaignid := r.URL.Query().Get("campaignid")
	bidderid := r.URL.Query().Get("bidderid")
	requestid := r.URL.Query().Get("requestid")
	banner_type := r.URL.Query().Get("banner_type")
	price := r.URL.Query().Get("won_price")

	encodedNURL := r.URL.Query().Get("imprice")
	nurlBytes, _ := base64.StdEncoding.DecodeString(encodedNURL)
	adminMarginStr := string(nurlBytes)
	adminMargin, _ := strconv.ParseFloat(adminMarginStr, 64)


	bidder_id, _ := strconv.Atoi(bidderid)
	zone_id, _ := strconv.Atoi(zoneid)

	auction_price := StringToFloat(price, 64)
	Track_win(requestid, bidder_id, zone_id, banner_type, auction_price,adminMargin)

}

func Track_win(request_id string, dsp_id int, zone_id int, banner_type string, won_price float64, adminMargin float64) {

	if DbTrack == "clickhouse" {
		clickClient.Track_win(request_id, uint16(dsp_id), uint64(zone_id), banner_type, won_price)
	} else if DbTrack == "kafka" {
		kafkaClient.Track_win(request_id, uint16(dsp_id), uint64(zone_id), banner_type, won_price, adminMargin)
	} else {
		clickClient.Track_win(request_id, uint16(dsp_id), uint64(zone_id), banner_type, won_price)
	}	
}

// Function for coverting float to string
func StringToFloat(str string, bit int) float64 {
	if flt, err := strconv.ParseFloat(str, bit); err == nil {
		return flt
	}
	return 0
}

// Function for processing Loss Notice request
func processLossnotice(w http.ResponseWriter, r *http.Request) {
	id := r.URL.Query().Get("id")
	bidderid := r.URL.Query().Get("bidderid")
	log.Println("loss", id)
	log.Println("loss", bidderid)
	lurl, err := base64.StdEncoding.DecodeString(r.URL.Query().Get("lurl"))
	if err != nil {
		logger.Log.Println("Error : ", err.Error())
		return
	}
	// Make a cURL get request
	resp, err := http.Get(string(lurl))

	// Log error when request not successful
	if err != nil {
		logger.Log.Println("Error : ", err.Error())
		return
	}

	// Close response body
	defer resp.Body.Close()
}

// Function for processing Loss Notice request
func processVastWrapper(w http.ResponseWriter, r *http.Request) {

	var (
		x   []byte
		err error
	)
	xmlS := &vastxmlstructs.VastTypes{}
	key := r.URL.Query().Get("key")
	err = redisclient.GetKey(key, xmlS)

	if xmlS.VAST2 != nil {
		x, err = xml.MarshalIndent(xmlS.VAST2, "", "  ")
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
	} else if xmlS.WVAST2 != nil {
		x, err = xml.MarshalIndent(xmlS.WVAST2, "", "  ")
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
	} else if xmlS.VAST3 != nil {
		x, err = xml.MarshalIndent(xmlS.VAST3, "", "  ")
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
	} else if xmlS.WVAST3 != nil {
		x, err = xml.MarshalIndent(xmlS.WVAST3, "", "  ")
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
	} else if xmlS.VAST4 != nil {
		x, err = xml.MarshalIndent(xmlS.VAST4, "", "  ")
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
	} else if xmlS.WVAST4 != nil {
		x, err = xml.MarshalIndent(xmlS.WVAST4, "", "  ")
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
	} else if xmlS.VAST41 != nil {
		x, err = xml.MarshalIndent(xmlS.VAST41, "", "  ")
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
	} else if xmlS.WVAST41 != nil {
		x, err = xml.MarshalIndent(xmlS.WVAST41, "", "  ")
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
	}
	if err != nil {
		logger.Log.Println("Key : "+key+" expired or error in getting redis key: ", err.Error())
		http.Error(w, "Not Found", http.StatusNotFound)
		return
	}

	allowedHeaders := "Accept, Content-Type, Content-Length, Accept-Encoding, Authorization,X-CSRF-Token"
	w.Header().Set("Access-Control-Allow-Origin", "*")
	u, _ := url.Parse(r.Header.Get("Referer"))
	w.Header().Set("Content-Type", "text/xml; charset=utf-8")
	w.Header().Set("Access-Control-Allow-Origin", u.Scheme+"://"+u.Host)
	w.Header().Set("Access-Control-Allow-Credentials", "true")
	w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
	w.Header().Set("Access-Control-Allow-Headers", allowedHeaders)
	w.Header().Set("Access-Control-Expose-Headers", "Authorization")
	w.Write(x)
}

func VastWrapper(w http.ResponseWriter, r *http.Request) {

	key := r.URL.Query().Get("overlaykey")
	allowedHeaders := "Accept, Content-Type, Content-Length, Accept-Encoding, Authorization,X-CSRF-Token"
	w.Header().Set("Access-Control-Allow-Origin", "*")
	u, _ := url.Parse(r.Header.Get("Referer"))
	w.Header().Set("Content-Type", "text/xml; charset=utf-8")
	w.Header().Set("Access-Control-Allow-Origin", u.Scheme+"://"+u.Host)
	w.Header().Set("Access-Control-Allow-Credentials", "true")
	w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
	w.Header().Set("Access-Control-Allow-Headers", allowedHeaders)
	w.Header().Set("Access-Control-Expose-Headers", "Authorization")

	var (
		err error
	)
	var xmlS string
	err = redisclient.GetKey(key, &xmlS)

	if err != nil {
		http.Error(w, "Not Found", http.StatusNotFound)
		return
	}

	w.Write([]byte(xmlS))
}

func GetMin(k int) (m int) {
	if k <= 15 && k >= 0 {
		m = 0
	} else if k <= 30 && k > 15 {
		m = 15
	} else if k <= 45 && k > 30 {
		m = 30
	} else if k <= 59 && k > 45 {
		m = 45
	}
	return
}

// Function for getting minutes
func GetMinalt(k int) (m int) {

	if k%5 > 0 {
		m = k - (k % 5)

	}

	return

}

// Function for processing Loss Notice request
func processVastTracking(w http.ResponseWriter, r *http.Request) {

	zoneid, _ := strconv.Atoi(r.URL.Query().Get("zoneid"))
	exchangeid, _ := strconv.Atoi(r.URL.Query().Get("exchangeid"))
	event := r.URL.Query().Get("event")

	if DbTrack == "clickhouse" {
		clickClient.Track_vast(uint16(exchangeid), uint64(zoneid), event)
	} else if DbTrack == "kafka" {
		kafkaClient.Track_vast(uint16(exchangeid), uint64(zoneid), event)
	} else {
		clickClient.Track_vast(uint16(exchangeid), uint64(zoneid), event)
	}	

	return
}

// Function for processing Loss Notice request
func processHBTracking(w http.ResponseWriter, r *http.Request) {

	zoneid, _ := strconv.Atoi(r.URL.Query().Get("zoneid"))
	bidder := r.URL.Query().Get("bidder")
	event := r.URL.Query().Get("event")

	if DbTrack == "clickhouse" {
		clickClient.Track_HB(bidder, uint64(zoneid), event)
	} else if DbTrack == "kafka" {
		kafkaClient.Track_HB(bidder, uint64(zoneid), event)
	} else {
		clickClient.Track_HB(bidder, uint64(zoneid), event)
	}		
	return
}

// Function for adding extra zeros
func AddZeros(count int) (result string) {
	if len(strconv.Itoa(count)) == 1 {
		result = "0" + strconv.Itoa(count)
	} else {
		result = strconv.Itoa(count)
	}
	return
}


func Prebid_Cron() {
	fmt.Println("cron started")
	ctx := context.Background()
	t := time.Now()

	// Round down to nearest hour
	t = t.Truncate(time.Hour)
	start := t.Add(-1 * time.Hour).Format("2006-01-02 15:04:05")

	// Insert aggregated data into hb_reports
	query := `
INSERT INTO hb_reports 
(
    date_time, zoneid, hb_bidder, hb_source, hb_media, hb_size, 
    hb_wonbid, impression, country, currency, click, type, request, response
)
SELECT
    toStartOfHour(date_time) AS agg_datetime,
    zoneid,
    hb_bidder,
    hb_source,
    hb_media,
    hb_size,
    sum(hb_wonbid)   AS hb_wonbid,
    sum(impression)  AS impression,
    country,
    currency,
    sum(click)       AS click,
    type,
    sum(request)     AS request,
    sum(response)    AS response
FROM hb_tracking
WHERE zoneid != 0
  AND hb_bidder != ''
  AND date_time >= subtractHours(now(), 1)
  AND date_time < now()
GROUP BY
    agg_datetime, zoneid, hb_bidder, hb_source, hb_media, hb_size, country, currency, type
`

	client := clickConnect.ClickhouseConnection()
	defer client.Close()

	// Run aggregation insert
	if err := client.Do(ctx, ch.Query{Body: query}); err != nil {
		fmt.Println("Insert Error:", err)
	}

	// Cleanup old raw records from hb_tracking
	truncateQuery := fmt.Sprintf(
		`ALTER TABLE hb_tracking DELETE WHERE toStartOfHour(date_time) = toDateTime('%s')`,
		start,
	)
	if err := client.Do(ctx, ch.Query{Body: truncateQuery}); err != nil {
		fmt.Println("Delete Error:", err)
	}

	fmt.Println("cron completed. Deleted raw data at hour:", start)
}



func Clickhouse_Cron() {

	fmt.Println("cron started")

	ctx := context.Background()
	t := time.Now()

	ist, _ := time.LoadLocation("Asia/Kolkata")
	nowUTC := time.Now().UTC()
	nowIST := nowUTC.In(ist)

	logger.Log.Printf("\n ssp_dj_hourly_table runningUTC: %s IST: %s\n",nowUTC.Format("2006-01-02 15:04:05"),	nowIST.Format("2006-01-02 15:04:05"))

	// t := time.Date(2024, time.January, 5, 13, 00, 0, 0, time.UTC)
	// fmt.Println("New Time:", t)
	/* layout := "2006-01-02 15:04:05"
	str := "2020-04-28 18:00:00"
	t, _ := time.Parse(layout, str)
	log.Println(t) */
	yC := t.Year()
	monC := AddZeros(int(t.Month()))
	dC := AddZeros(t.Day())
	hC := AddZeros(t.Hour())
	layout := "2006-01-02 15:04:00"
	str := strconv.Itoa(yC) + "-" + monC + "-" + dC + " " + hC + ":00:00"
	t, _ = time.Parse(layout, str)
	start := t.Add(time.Duration(-60) * time.Minute).Format("2006-01-02 15:04:05")

	// Example query
	query := `INSERT INTO ssp_dj_hourly_table( * ) SELECT bidderid,zoneid,pmp_deal,banner_type,TEMP.country_code,TEMP.country_name,TEMP.domain,TEMP.os,TEMP.ip,TEMP.user_agent,TEMP.language,TEMP.currency,TEMP.user_age,TEMP.user_gender,TEMP.browser,TEMP.device_type,TEMP.device_make,TEMP.device_model,TEMP.page_url,TEMP.ref_url,SUM(TEMP.req_c) AS req_c,SUM(TEMP.res_c) AS res_c,SUM(TEMP.win_c) AS win_c,SUM(TEMP.imp_c) AS imp_c,SUM(TEMP.won_p) AS won_p,SUM(TEMP.adm_r) AS adm_r,TEMP.time FROM( SELECT toStartOfHour(t1.datatime) time,t1.bidderid bidderid,t1.zoneid zoneid,0 As pmp_deal,t1.banner_type banner_type,t1.country_code country_code,t1.country_name country_name,t1.domain domain,t1.os os,t1.ip ip,t1.user_agent user_agent,t1.language language,t1.currency currency,t1.user_age user_age,t1.user_gender user_gender,t1.browser browser,t1.device_type device_type,t1.device_make device_make,t1.device_model device_model,t1.page_url page_url,t1.ref_url ref_url,SUM(ifNull(t1.request_count, 0)) AS req_c,SUM(ifNull(t2.response_count, 0)) AS res_c,0 AS win_c,0 AS imp_c,0 AS won_p,0 AS adm_r FROM ssp_dj_request_stats AS t1 LEFT JOIN ssp_dj_response_stats AS t2 ON t1.request_id = t2.request_id WHERE toStartOfHour(t1.datatime) = '` + start + `' GROUP BY t1.request_id,t1.bidderid,t1.zoneid,t1.banner_type,t1.country_code,t1.country_name,t1.domain,t1.os,t1.ip,t1.user_agent,t1.language,t1.currency,t1.user_age,t1.user_gender,t1.browser,t1.device_type,t1.device_make,t1.device_model,t1.page_url,t1.ref_url,toStartOfHour(t1.datatime) UNION ALL SELECT toStartOfHour(t1.datatime) time,t1.bidderid bidderid,t1.zoneid zoneid,0 As pmp_deal,t1.banner_type banner_type,t1.country_code country_code,t1.country_name country_name,t1.domain domain,t1.os os,t1.ip ip,t1.user_agent user_agent,t1.language language,t1.currency currency,t1.user_age user_age,t1.user_gender user_gender,t1.browser browser,t1.device_type device_type,t1.device_make device_make,t1.device_model device_model,t1.page_url page_url,t1.ref_url ref_url,0 AS req_c,0 AS res_c,SUM(ifNull(t3.win_count, 0)) AS win_c,SUM(ifNull(t3.imp_count, 0)) AS imp_c,SUM(ifNull(CAST(t3.won_price, 'Decimal64(6)'), 0)) AS won_p,SUM(ifNull(CAST(t3.admin_share, 'Decimal64(6)'), 0)) AS adm_r FROM ssp_dj_request_stats AS t1 JOIN ssp_dj_win_stats AS t3 ON t1.request_id = t3.request_id WHERE toStartOfHour(t1.datatime) = '` + start + `' GROUP BY t1.request_id,t1.bidderid,t1.zoneid,t1.banner_type,t1.country_code,t1.country_name,t1.domain,t1.os,t1.ip,t1.user_agent,t1.language,t1.currency,t1.user_age,t1.user_gender,t1.browser,t1.device_type,t1.device_make,t1.device_model,t1.page_url,t1.ref_url,toStartOfHour(t1.datatime))as TEMP GROUP BY TEMP.time,bidderid,zoneid,pmp_deal,banner_type,TEMP.country_code,TEMP.country_name,TEMP.domain,TEMP.os,TEMP.ip,TEMP.user_agent,TEMP.language,TEMP.currency,TEMP.user_age,TEMP.user_gender,TEMP.browser,TEMP.device_type,TEMP.device_make,TEMP.device_model,TEMP.page_url,TEMP.ref_url`

	Client := clickConnect.ClickhouseConnection()
	defer Client.Close()
	input := proto.Input{}
	if err := Client.Do(ctx, ch.Query{
		Body:  query,
		Input: input,
	}); err != nil {
		fmt.Println(err)
	}

	vast_query := `INSERT INTO ssp_dj_vast_report (*) SELECT t1.bidderid,t1.zoneid,t1.event,SUM(ifNull(t1.count, 0)) AS event_count, toStartOfHour(t1.datatime) AS time FROM ssp_dj_vast_stats AS t1 WHERE toStartOfHour(t1.datatime) = '` + start + `' GROUP BY bidderid,zoneid,event,toStartOfHour(t1.datatime)`

	if err1 := Client.Do(ctx, ch.Query{
		Body:  vast_query,
		Input: input,
	}); err1 != nil {
		fmt.Println(err1)
	}

	table_name := []string{"ssp_dj_request_stats", "ssp_dj_response_stats", "ssp_dj_win_stats", "ssp_dj_vast_stats"}
	for i := 0; i < len(table_name); i++ {
		truncate_query := `ALTER TABLE ` + table_name[i] + ` DELETE WHERE toStartOfHour(datatime)='` + start + `'`
		if err := Client.Do(ctx, ch.Query{
			Body:  truncate_query,
			Input: input,
		}); err != nil {
			fmt.Println(err)
		}
	}
	fmt.Println("cron completed ", start)

}

// Cron Function
func executeCronJob() {

	gocron.Every(1).Hour().Do(Clickhouse_Cron)

	<-gocron.Start()
}


func VastWrapperHandler(w http.ResponseWriter, r *http.Request) {
    key := r.URL.Query().Get("keyv")
    if key == "" {
        http.Error(w, "Missing key", http.StatusBadRequest)
        return
    }

    // Prepare a variable to hold the VAST XML
    var vastXML string

    // Pass pointer to variable
    err := redisclient.GetKey(key, &vastXML)
    if err != nil || vastXML == "" {
        http.Error(w, "VAST not found", http.StatusNotFound)
        return
    }

    w.Header().Set("Content-Type", "text/xml; charset=utf-8")
    w.Write([]byte(vastXML))
}



func main() {
	// Concurrently execute cron functions
	//go executeCronJob()
	

	ipAddr := constants.AppHost
	logger.Log.Println("Server started at " + constants.AppProtocol + ipAddr + constants.AppPort)
	log.Println("Server started at " + constants.AppProtocol + ipAddr + constants.AppPort)

	// http.Handler
	router := mux.NewRouter().StrictSlash(true)
	router.HandleFunc("/", home)
	router.HandleFunc("/loaderio-d853366ab91d80480a5c055b09649ec3.txt", validataion).Methods("GET")
	router.HandleFunc("/loaderio-d853366ab91d80480a5c055b09649ec3", validataion).Methods("GET")
	router.HandleFunc("/loaderio-d853366ab91d80480a5c055b09649ec3.html	", validataion).Methods("GET")

	router.HandleFunc(constants.SSPEndPoint, processRequest).Methods("POST")
	
	router.HandleFunc(constants.WinNoticeEndPoint, processWinnotice).Methods("GET")
	router.HandleFunc(constants.BillingNoticeEndPoint, processBillingnotice).Methods("GET")
	router.HandleFunc(constants.ImpUrlEndPoint, processImpUrl).Methods("GET")
	router.HandleFunc(constants.LossNoticeEndPoint, processLossnotice).Methods("GET")
	router.HandleFunc(constants.VastWrapperEndPoint, processVastWrapper).Methods("GET")
	router.HandleFunc(constants.VastTrackingEndPoint, processVastTracking).Methods("GET")

	/*********************** ADX Start *************************/
	
	router.HandleFunc(constants.ADXEndPoint, processRequestadx).Methods("POST")
	router.HandleFunc(constants.WinNoticeAdxEndPoint, processWinnoticeadx).Methods("GET")
	router.HandleFunc(constants.BillingNoticeAdxEndPoint, processBillingnoticeadx).Methods("GET")
	router.HandleFunc(constants.ImpUrlAdxEndPoint, processImpUrladx).Methods("GET")
	router.HandleFunc(constants.VastWrapperAdxEndPoint, processVastWrapperadx).Methods("GET")
	router.HandleFunc(constants.VastTrackingAdxEndPoint, processVastTrackingadx).Methods("GET")
	/*********************** ADX End *************************/



	router.HandleFunc(constants.HBTrackingEndPoint, processHBTracking).Methods("GET")
	router.HandleFunc(constants.HBEventEndPoint, HBEvent).Methods("GET")

	router.HandleFunc("/VastWrapper", VastWrapper).Methods("GET")
	router.HandleFunc("/vast_tags", VastWrapperHandler).Methods("GET")
	router.HandleFunc("/health", healthval).Methods("GET")


	/*http.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
	    w.WriteHeader(http.StatusOK)
	    w.Write([]byte("Success"))
	})*/

	http.HandleFunc("/testhealth", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "text/plain")
		w.WriteHeader(http.StatusOK)
		w.Write([]byte("Success"))
	})


	
	srv := &http.Server{
		Addr:    constants.AppPort,
		Handler: router,
		TLSConfig: &tls.Config{
			MinVersion:               tls.VersionTLS13,
			PreferServerCipherSuites: true,
		},
	}

	srv.SetKeepAlivesEnabled(false)

	if err := srv.ListenAndServeTLS(constants.CertFile, constants.KeyFile); err != nil {
		panic(err)
	}

	/*if err := http.ListenAndServe(constants.AppPortraw, router); err != nil {
		panic(err)
	}*/
}
