class Origami::SaleEditController < BaseOrigamiController
  authorize_resource :class => false
   # Index for sale item void OR edit
   def edit
     sale_id = params[:sale_id]
     @table_id = params[:table_id]
     @saleobj = Sale.find(sale_id)
   end

   # create item void. make duplicate old record and update qty and price
   def item_void
     saleitemId = params[:sale_item_id]
     saleitemObj = SaleItem.find(saleitemId)
     saleitemObj.remark = 'void'
     saleitemObj.save
     @newsaleitem = SaleItem.new
     @newsaleitem = saleitemObj.dup
     @newsaleitem.save
     @newsaleitem.qty = saleitemObj.qty * -1
     @newsaleitem.price = saleitemObj.price * -1
     @newsaleitem.is_taxable = 1
     @newsaleitem.product_name = saleitemObj.product_name + " - void"
     @newsaleitem.save
   end

  def item_edit
    saleitemId = params[:sale_item_id]
    update_qty = params[:update_qty]
    update_price = params[:update_price]
    saleitemObj = SaleItem.find(saleitemId)
    saleitemObj.remark = 'void'
    saleitemObj.save
    @newsaleitem = SaleItem.new
    @newsaleitem = saleitemObj.dup
    @newsaleitem.save
    @newsaleitem.qty = update_qty
    @newsaleitem.price = update_price
    @newsaleitem.unit_price = update_price
    @newsaleitem.taxable_price = update_price
    @newsaleitem.is_taxable = 0
    @newsaleitem.remark = 'edit'
    @newsaleitem.product_name = saleitemObj.product_name + " - updated"
    @newsaleitem.save
  end

   # make cancel void item
   def item_void_cancel
     saleitemId = params[:sale_item_id]
     saleitemObj = SaleItem.find(saleitemId)
     both = SaleItem.where('product_code=?',saleitemObj.product_code)
     both.each do |item|
       if item.qty.to_i > 0
         item.remark = nil
         item.save
       end
     end
     saleitemObj.destroy
   end

   # remove all void items
   def cancel_all_void
     sale_id = params[:sale_id]
     saleobj = Sale.find(sale_id)
     saleobj.sale_items.each do |item|
       if item.qty.to_i < 0
          item.destroy
       else
         item.remark = nil
       end
       item.save
     end
   end

   def apply_void
     sale_id = params[:sale_id]
     saleObj =  Sale.find(sale_id)
     saleObj.compute_without_void
   end
end
