#new_promotion
class Promotion < ApplicationRecord
  validates_presence_of  :promo_code,:promo_start_date,:promo_end_date,:promo_start_hour,:promo_end_hour,:promo_type,:original_product,:min_qty

  has_many :promotion_products

  accepts_nested_attributes_for :promotion_products , :allow_destroy => true , update_only: true

  PROMO_TYPE1 = "Quantity"
  PROMO_TYPE2 = "Net_off" # 3000 => - 500  => 2500 [total]
  PROMO_TYPE3 = "Net_price" # 1800 => 1000 => 1000
  PROMO_TYPE4 = "Percentage"

  def is_promo_day
    promo_day.include? Date.current.wday.to_s
  end

  def self.promo_activate(saleObj)
    current_day = Time.current.strftime("%Y-%m-%d")
    current_time = Time.current.strftime('%H:%M:%S')
    day = Date.current.wday
    promoList = is_between_promo_datetime(current_day,current_time)

    promoList.each do |promo|
      if promo.is_promo_day
        if item = saleObj.qty_of(promo.original_product)
          check_promo_type(promo, item, saleObj)
        end
      end
    end
  end

  def self.is_between_promo_datetime(current_day,current_time) #database is not local time
    promoList = Promotion.where("(Date_Format(CONVERT_TZ(promo_start_date, '+00:00', '<%= Time.zone.formatted_offset %>'), '%Y-%m-%d') <=? AND Date_Format(CONVERT_TZ(promo_start_date, '+00:00', '<%= Time.zone.formatted_offset %>'), '%Y-%m-%d') >=?) AND (promo_start_hour < ? AND promo_end_hour > ?)", current_day, current_day, current_time, current_time)
    return promoList
  end

  def self.check_promo_type(promo, orderitem, saleObj)
    promo.promotion_products.each do |promo_product|
     if promo_product.item_code.downcase == orderitem[:item_instance_code]
       same = true
     else
       # return false, promo_product
       same = false
     end
     # same, promo_product = check_giveaway_product(promo, orderitem[0][0])
     if promo.promo_type == Promotion::PROMO_TYPE1
       if same
         give_promotion_same_product(orderitem[:qty], promo.min_qty, promo_product.min_qty, orderitem, saleObj, promo_product.item_code)
       else
         give_promotion_second_product(orderitem[:qty], promo.min_qty, promo_product.item_code, orderitem, saleObj)
       end

     elsif promo.promo_type == Promotion::PROMO_TYPE2
        give_promotion_nett_off(same,promo_product,promo.min_qty, orderitem, saleObj)

     elsif promo.promo_type == Promotion::PROMO_TYPE3
       give_promotion_nett_price(same,promo_product,promo.min_qty, orderitem, saleObj)

     elsif promo.promo_type == Promotion::PROMO_TYPE4
       give_promotion_discount(same,promo_product,promo.min_qty, orderitem, saleObj)
     end
   end
  end

  def self.check_giveaway_product(promo, orderitem)
    # promo_pp = []
    # flag = false
    # promo.promotion_products.each do |promo_product|
    #   if promo_product.item_code == orderitem
    #     # return true, promo_product
    #     promo_pp.push(promo_product)
    #   else
    #     # return false, promo_product
    #   end
    # end
  end

  def self.give_promotion_same_product(qty, promoqty, foc_min_qty, orderitem, saleObj,promo_product)
    puts " Order qty: " + qty.to_s + " / promoqty: " + promoqty.to_s + " / giveaway: " + foc_min_qty.to_s
    multiple = qty.to_i / promoqty.to_i # loop count
    charge_qty = 0
    foc_qty = 0
    if multiple > 0
     multiple.times.each do |key|
       if qty > promoqty
         charge_qty += promoqty
         different = qty - promoqty
         qty = different
         if different == 0
            foc_qty += foc_min_qty
         else
           foc_qty += foc_min_qty
           qty = qty - foc_min_qty
         end
       else
          charge_qty += qty
       end
     end
     if multiple == foc_qty
       charge_qty += qty
     end
    else
     charge_qty += qty
    end

    price = 0
    source = saleObj.orders.first.source
    item = saleObj.order_items.where(item_instance_code: promo_product).first

    if !item.nil?
     update_existing_item(foc_qty, item, saleObj, "promotion", item[:price], source)
    end
  end
                                         # AA - 10        # 3          # BB         # orderList, #S34345
  def self.give_promotion_second_product(orderitem_count, foc_min_qty, promo_product, orderitem, saleObj)
    puts "..... orderitem_count: " + orderitem_count.to_s + " / foc_min_qty: " + foc_min_qty.to_s + " /promo_product: " + promo_product + " orderitem: " + orderitem.to_s

    promotion_qty = orderitem_count.to_i / foc_min_qty.to_i # get foc item qty
    foc_qty = saleObj.qty_of(promo_product).qty rescue 0
    if (foc_qty < promotion_qty)
      promotion_qty = foc_qty
    end
    # item = OrderItem.find_by_item_instance_code(promo_product)

    price = 0
    source = saleObj.orders.first.source
    item = saleObj.order_items.where(item_instance_code: promo_product).first

    if !item.nil?
      update_existing_item(promotion_qty, item, saleObj, "promotion", item[:price],source)
    end
  end

  def self.update_existing_item(qty, item, saleObj, type, item_price,source)
    if qty > 0
      menu_category = MenuCategory.get_menu_category(item[:item_code]) #get menu category for menu items

      sale_item = SaleItem.new
      if !menu_category.nil?
        sale_item.menu_category_code = menu_category.code
        sale_item.menu_category_name = menu_category.name
      end
      sale_item.product_code = item[:item_code]
      sale_item.item_instance_code = item[:item_instance_code]
      sale_item.product_name = item[:item_name] + "(promotion)"
      sale_item.product_alt_name = item[:alt_name]
      sale_item.account_id = item[:account_id]
      sale_item.remark = type
      sale_item.status = "promotion"
      sale_item.qty = qty * (-1)

      sale_item.unit_price = item_price # * (-1)
      sale_item.taxable_price = (qty * item_price) * (-1)
      sale_item.price = qty * item_price * (-1)

      sale_item.is_taxable = 1
      sale_item.sale = saleObj
      sale_item.save

      saleObj.sale_items << sale_item
      saleObj.compute_by_sale_items(saleObj.total_discount, nil, source)
    end
  end


  def self.give_promotion_nett_off(same, promo_product, foc_min_qty, orderitem, saleObj)
    puts " same: " + same.to_s + " promo_product: " + promo_product.item_code.to_s + " foc_min_qty: " + foc_min_qty.to_s + " orderitem: " + orderitem.to_s

    foc_qty = orderitem[:qty].to_i / foc_min_qty
    if !same
      order_qty = saleObj.qty_of(promo_product.item_code).qty rescue 0
      foc_qty = orderitem[:qty].to_i / foc_min_qty

      if foc_qty > order_qty
        foc_qty = order_qty
      end
    end

    source = saleObj.orders.first.source
    item = saleObj.order_items.where(item_instance_code: promo_product.item_code).first

    if !item.nil?
      update_existing_item(foc_qty, item, saleObj, "promotion nett off", promo_product.net_off,source)
    end
  end

  def self.give_promotion_nett_price(same, promo_product, foc_min_qty, orderitem, saleObj)
    puts " same: " + same.to_s + " promo_product: " + promo_product.item_code.to_s + " foc_min_qty: " + foc_min_qty.to_s + " orderitem: " + orderitem.to_s

    foc_qty = orderitem[:qty].to_i / foc_min_qty
    if !same
      order_qty = saleObj.qty_of(promo_product.item_code).qty rescue 0
      foc_qty = orderitem[:qty].to_i / foc_min_qty

      if foc_qty > order_qty
        foc_qty = order_qty
      end
    end

    source = saleObj.orders.first.source
    item = saleObj.order_items.where(item_instance_code: promo_product.item_code).first

    if !item.nil?
     price = item[:price].to_i - promo_product.net_price.to_i
     update_existing_item(foc_qty, item, saleObj, "promotion nett price", price,source)
    end
  end

  def self.give_promotion_discount(same, promo_product, foc_min_qty, orderitem, saleObj)
    puts " same: " + same.to_s + " promo_product: " + promo_product.item_code.to_s + " foc_min_qty: " + foc_min_qty.to_s + " orderitem: " + orderitem.to_s

    foc_qty = orderitem[:qty].to_i / foc_min_qty
    if !same
      order_qty = saleObj.qty_of(promo_product.item_code).qty rescue 0
      foc_qty = orderitem[:qty].to_i / foc_min_qty

      if foc_qty > order_qty
        foc_qty = order_qty
      end
    end

    source = saleObj.orders.first.source
    item = saleObj.order_items.where(item_instance_code: promo_product.item_code).first
    puts saleObj
    puts item
    #  total = orderitem[1].to_i * item.price
    if item
      total = item[:price]
      price = calculate_discount(total, promo_product.percentage)
      # source = Order.find(item.order_id).source
      update_existing_item(foc_qty, item, saleObj, "promotion discount", price,source)
    end
  end

  def self.calculate_discount(total, percentage)
    return (total * percentage) / 100
  end
end
