class Foodcourt::VoidController < BaseFoodcourtController
  authorize_resource :class => false

  def overall_void
    sale_id = params[:sale_id]
    remark  = params[:remark]
    order_source = params[:type] #tax profile source
    access_code = params[:access_code]

    if Sale.exists?(sale_id)
      sale = Sale.find_by_sale_id(sale_id)
      # update count for shift sale
      if(sale.sale_status == "completed")
        if sale.shift_sale_id != nil
          shift = ShiftSale.find(sale.shift_sale_id)
          shift.calculate(sale_id, "void")
        end
      else
        # void before sale payment complete
        if sale.shift_sale_id != nil
          shift = ShiftSale.find(sale.shift_sale_id)
          shift.total_void = shift.total_void + sale.grand_total
          shift.save
        end
      end

      if sale.discount_type == "member_discount"
        sale.update_attributes(total_discount: 0)
        sale.compute_by_sale_items(0, nil, order_source)
      end

      sale.rounding_adjustment = 0.0
      sale.payment_status = 'void'
      sale.sale_status = 'void'
      sale.save

      #call paymal to void
      if !sale.sale_payments.nil?
        membership_response = sale.paymal_payment_void
        Rails.logger.debug "---------Paymal Payment Void response in VoidController"
        Rails.logger.debug membership_response.to_json
      end

      PrintReceiptJob.perform_later(current_shop.shop_code, sale.sale_id)

      if table = sale.booking.dining_facility
        unless table.current_bookings.exists?
          table.update_attributes(status: 'available')
        end
      end

      # FOr Sale Audit
      action_by = current_user.name
      if access_code != "null" && current_user.role == "cashier"
        action_by = Employee.find_by_emp_id(access_code).name
      end

      # remark = "Void Sale ID #{sale_id} | Receipt No #{sale.receipt_no} | Receipt No #{sale.receipt_no} | Table ->#{table.name}"
      sale_audit = SaleAudit.record_audit_for_edit(sale_id,current_user.name, action_by,remark,"SALEVOID" )

      # update complete order items in oqs
      SaleOrder.where("sale_id = '#{ sale_id }'").find_each do |sodr|
        AssignedOrderItem.where("order_id = '#{ sodr.order_id }'").find_each do |aoi|
          aoi.delivery_status = 1
          aoi.save
        end
      end
    end
    head :no_content
  end
end
