package queries

import (
	"database/sql"
	"fmt"
)

func GetOrderListExcel(
	db *sql.DB,
	search string,
	currAcc string,
	orderDate string,
) (*sql.Rows, error) {

	q := OrderListBaseQuery + " AND 1=1 "
	args := []interface{}{}

	// SEARCH
	if search != "" {
		q += `
AND (
  LOWER(h.OrderNumber) LIKE LOWER(@p1) OR
  LOWER(h.CurrAccCode) LIKE LOWER(@p1) OR
  LOWER(ca.CurrAccDescription) LIKE LOWER(@p1) OR
  LOWER(h.Description) LIKE LOWER(@p1) OR
  LOWER(mt.AttributeDescription) LIKE LOWER(@p1) OR
  LOWER(py.AttributeDescription) LIKE LOWER(@p1)
)
`
		args = append(args, "%"+search+"%")
	}

	// CURRACC
	if currAcc != "" {
		q += fmt.Sprintf(" AND h.CurrAccCode = @p%d ", len(args)+1)
		args = append(args, currAcc)
	}

	// DATE
	if orderDate != "" {
		q += fmt.Sprintf(
			" AND CONVERT(varchar, h.OrderDate, 23) = @p%d ",
			len(args)+1,
		)
		args = append(args, orderDate)
	}

	// ORDER BY SONDA
	q += " ORDER BY h.CreatedDate DESC "

	return db.Query(q, args...)
}
