class SaleItem < ApplicationRecord
  self.primary_key = "sale_item_id"

  #primary key - need to be unique generated for multiple shops
  before_create :generate_custom_id

  belongs_to :sale
  has_many :product_commissions

  #compute items - discount, tax, price_change
  def compute_item
  end

  # Add Sale Items
  def self.add_sale_items(sale_items)
    sale_items.each do|saleitemObj|
      @newsaleitem = SaleItem.new
      @newsaleitem = saleitemObj.dup
      @newsaleitem.save
      @newsaleitem.qty = saleitemObj.qty * (-1)    
      @newsaleitem.unit_price = saleitemObj.unit_price * (-1)
      @newsaleitem.taxable_price = (saleitemObj.unit_price * saleitemObj.qty) * (-1)
      @newsaleitem.price = (saleitemObj.unit_price * saleitemObj.qty) * (-1)     
      @newsaleitem.product_name = saleitemObj.product_name + ' (FOC)'
      @newsaleitem.save
    end    
  end

  def self.update_existing_item(qty, item, sale_id, type, item_price, price)
      # Original Item to add remark
      item.status = type
      item.save

      sale_item = SaleItem.new
      sale_item.product_code = item.product_code
      sale_item.item_instance_code = item.item_instance_code
      sale_item.product_name = item.product_name + " (#{type.upcase})"
      sale_item.product_alt_name = item.product_alt_name
      sale_item.account_id = item.account_id
      sale_item.status = type
      sale_item.remark = type
      if type == "foc" || type == "promotion" || type == "void" || type == "waste" || type == "spoile"
        sale_item.qty = qty * (-1)
      else
        sale_item.qty = qty
      end

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

      sale_item.is_taxable = 1
      sale_item.sale_id = sale_id
      sale_item.save
      sale =  Sale.find(sale_id)
      sale.compute_by_sale_items(sale.id, sale.sale_items, sale.total_discount)
  end

  def self.get_order_items_details(sale_id)
    order_details = SaleItem.select("sales.total_tax as tax_amount, sales.grand_total as grand_total_amount , sales.total_discount as discount_amount,sales.receipt_date as receipt_date,
                      sales.cashier_name,sales.receipt_no,sale_items.product_name as item_name,sale_items.qty,sale_items.price,sale_items.unit_price as total_price")
                   .joins("left join sales on sales.sale_id = sale_items.sale_id")
                   .where("sale_items.sale_id=?",sale_id)

    # sale_orders = SaleOrder.where("sale_id=?",sale_id)
    # if sale_orders
    #    sale_orders.each do |sale_order|
    #     order_details = SaleItem.select("sales.total_discount as discount_amount,DATE_FORMAT(sales.receipt_date,'%Y-%m-%d %h:%m') as receipt_date,sales.cashier_name,sales.receipt_no,sale_items.product_name as item_name,sale_items.qty,sale_items.price,sale_items.unit_price as total_price")
    #        .joins("left join sales on sales.id = sale_items.sale_id")
    #        .where("sale_items.sale_id=?",sale_order.sale_id)
    #     return order_details
    #   end
    # else
    #   return false
    # end
  end

  # Get Prices for each accounts (eg: food, beverage)
  def self.calculate_price_by_accounts(sale_items)
    price_accounts = []
    Account.all.each do |a|
      account_price = {:name => a.title, :price => 0}

      # Check for actual sale items
      sale_items.each do |si|
        if si.account_id == a.id          
          account_price[:price] = account_price[:price] + si.price
        end
      end
      price_accounts.push(account_price)
    end

    return price_accounts
  end

  # Get discount Prices for each accounts (eg: food, beverage)
  def self.get_discount_price_by_accounts(sale_items)
    discount_accounts = []
    Account.all.each do |a|
      discount_account = {:name => a.title, :price => 0}
      # Check for actual sale items
      sale_items.where("status = 'Discount'").each do |si|
        if si.account_id == a.id
          discount_account[:price] = (discount_account[:price].abs + si.price.abs) * (1)
        end
      end
      discount_accounts.push(discount_account)
    end

    return discount_accounts
  end

 # Calculate rebate_by_account
  def self.calculate_rebate_by_account(sale_items)
    rebateacc =  Account.where("rebate=?",true)
    price = 0
    rebate_arr = []
    rebateacc.each do |a|
      account_price = {:type => a.title, :amount => 0}

      # Check for actual sale items
      sale_items.each do |si|
        if si.account_id == a.id
          account_price[:amount] = account_price[:amount] + si.price
           price = price + si.price
        end

      end
      rebate_arr.push(account_price)
    end

    return price,rebate_arr
  end

  # get food price or beverage price for item
  def self.get_rebate_price(sale_item_id,rebateacc)
    price = 0
    type = ''
    item=SaleItem.select("sale_items.price , menu_items.account_id")
                          .joins("left join menu_items on menu_items.item_code = sale_items.product_code")
                          .where("sale_items.sale_item_id=?", sale_item_id.to_s)

    rebateacc.each do |i|
      if item[0].account_id == i.id
        price = item[0].price
        type  = i.title
      end
    end

    return price,type
  end

  # def self.get_overall_discount(sale_id)
  #   price = 0.0
  #   item=SaleItem.where("product_code=?", sale_id)
  #
  #   item.each do|i|
  #     price += i.price
  #   end
  #
  #   return price
  # end

   def self.get_all_sale_items(sale_id)
    sale_items = SaleItem.select("sale_id,product_code,item_instance_code,
      product_name,product_alt_name,account_id,status,remark,
      (CASE WHEN (qty > 0 AND remark IS NULL) OR (status='promotion' AND (remark = 'promotion nett price' OR remark= 'promotion discount')) THEN SUM(abs(qty)) ELSE qty END) as qty,
      unit_price,
      taxable_price,
      (CASE WHEN (price > 0 AND remark IS NULL) OR (status='promotion' AND (remark = 'promotion nett price' OR remark= 'promotion discount')) THEN SUM(abs(price)) ELSE price END) as price,
      is_taxable")
              .where("sale_id = ?",sale_id)
              .order("product_name asc")
              .group("status,product_name,item_instance_code,unit_price")
    return sale_items
  end

  private
  def generate_custom_id
    self.sale_item_id = SeedGenerator.generate_id(self.class.name, "SLI")
  end
end
