class Api::Foodcourt::VoidController < Api::ApiController

  def create
    sale_id = params[:sale_id]
    order_source = params[:type] || "food_court" #tax profile source
    access_code = params[:access_code]
    remark  = params[:remark]

		@sale = Sale.find_by_sale_id(sale_id)

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

		# 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

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

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

    # FOr Sale Audit
    action_by = current_login_employee.name
    if access_code != "null" && current_login_employee.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_login_employee.name, action_by, remark, "SALEVOID" )

    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

    @status = true
    @message = "Void succeed"
  end
end
