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

  #discount page show from origami index with selected order
  def index
    # get printer info
    @print_settings = PrintSetting.get_precision_delimiter()
    @webview = false
    if check_mobile
      @webview = true
    end

	  sale_id = params[:id]
    @cashier_type = params[:type]
    if Sale.exists?(sale_id)
      @sale_data = Sale.find(sale_id)
      if @sale_data.bookings[0].dining_facility_id.to_i > 0
        @table =  DiningFacility.find(@sale_data.bookings[0].dining_facility_id)
      else
        @table = nil
      end
    end

    @member_discount = MembershipSetting.find_by_discount(1)
    @accounts = Account.all
  end

  #discount page show from origami index with selected order
  def create
    order_source = params[:cashier_type]
    sale_id = params[:sale_id]
    discount_items = JSON.parse(params[:discount_items])
    overall_discount = params[:overall_discount]
    sub_total = params[:sub_total]

    if Sale.exists?(sale_id)
      sale = Sale.find(sale_id)
      if sale.bookings[0].dining_facility_id.to_i > 0
        table_id = sale.bookings[0].dining_facility_id
        table = DiningFacility.find(table_id)
      else
        table = nil
        table_id = nil
      end

      # sale.total_discount = overall_discount.to_f
      # sale.total_amount = sub_total.to_f
      # sale.grand_total = (sub_total.to_f - overall_discount.to_f) + sale.total_tax;
      # sale.save
      if discount_items.length > 0

        #save sale item for discount
        discount_items.each do |di|
          discount = di['discount'].to_d
          discount_type = di['discount_type']

          sale_item = SaleItem.find(di["id"])
          discount_item = SaleItem.find_or_initialize_by(parent_id: di['id'])

          discount_item.discount = discount
          if discount_type == 'nett'
            discount_item.discount_type = 'nett'
            discount_item.product_name = "#{sale_item.product_name} - discount"
            unit_price = discount
          elsif discount_type == 'percentage'
            discount_item.discount_type = 'percentage'
            discount_item.product_name = "#{sale_item.product_name} - discount(#{discount}%)"
            unit_price = sale_item.unit_price * (discount / 100)
          end

          price = unit_price * sale_item.qty

          discount_item.menu_category_code = sale_item.menu_category_code
          discount_item.menu_category_name = sale_item.menu_category_name

          discount_item.sale_id = sale_id
          discount_item.product_code = sale_item != nil ? sale_item.product_code : sale_id
          discount_item.item_instance_code = sale_item.item_instance_code
          discount_item.product_alt_name = ""
          discount_item.status = "Discount"

          discount_item.qty = sale_item.qty
          discount_item.unit_price = unit_price
          discount_item.taxable_price = -price
          discount_item.is_taxable = sale_item.is_taxable
          discount_item.account_id = sale_item.account_id

          discount_item.price = -price
          discount_item.save

          action_by = current_user.name
          remark = "Discount Item Name ->#{sale_item.product_name}-Product Code ->#{sale_item.product_code} | Price [#{sale_item.price}] | Receipt No #{sale.receipt_no} "

          sale_audit = SaleAudit.record_audit_discount(discount_item.sale_id, sale.cashier_name, action_by, remark, "ITEMDISCOUNT" )
        end
      end

      # Re-calc All Amount in Sale
      if overall_discount.to_f > 0
        action_by = current_user.name
        if table.nil?
          remark = "Discount Overall Price [#{overall_discount}]| Receipt No #{sale.receipt_no} | Table- no Table "
        else
          remark = "Discount Overall Price [#{overall_discount}]| Receipt No #{sale.receipt_no} | Table- #{table.name} "
        end

        sale_audit = SaleAudit.record_audit_discount(sale.sale_id,sale.cashier_name, action_by,remark,"OVERALLDISCOUNT" )
      end
      sale.compute_by_sale_items(overall_discount.to_f, nil,order_source)
      if !table.nil?
        result = {:status=> "Success", :table_id => table_id, :table_type => table.type }
      else
        result = {:status=> "Success" }
      end
    else
      if !table.nil?
        result = {:status=> "Please, Check Again!", :table_id => table_id, :table_type => table.type }
      else
        result = {:status=> "Please, Check Again!" }
      end
    end

    render :json => result.to_json
  end

  # Remove selected discount Items
  def remove_discount_items
    order_source = params[:cashier_type]
    sale_id = params[:sale_id]
    discount_items = JSON.parse(params[:discount_items])
    if Sale.exists?(sale_id)
      sale = Sale.find(sale_id)
      if sale.bookings[0].dining_facility_id.to_i > 0
        table_id = sale.bookings[0].dining_facility_id
        table = DiningFacility.find(table_id)
      else
        table_id = nil
        table = nil
      end

      if discount_items.length > 0
        #destroy sale item for discount
        discount_items.each do |di|
          sale_item = SaleItem.find(di["id"])

          discount_item =  sale_item.discount_item

          next if discount_item.nil?

          sale.total_amount = (sale.total_amount + discount_item.price.abs)

           action_by = current_user.name
           if table.nil?
            remark = "Remove Item Discount Item Name ->#{discount_item.product_name}-Product Code ->#{discount_item.product_code} | Price [#{discount_item.price}] | Receipt No #{sale.receipt_no} | Table- No Table "
           else
           remark = "Remove Item Discount Item Name ->#{discount_item.product_name}-Product Code ->#{discount_item.product_code} | Price [#{discount_item.price}] | Receipt No #{sale.receipt_no} | Table- #{table.name} "
           end
           sale_audit = SaleAudit.record_audit_discount(sale.sale_id,sale.cashier_name, action_by,remark,"REMOVEITEMDISCOUNT" )

          discount_item.destroy
        end
      end

      # sale.grand_total = (sale.total_amount - sale.total_discount) + sale.total_tax;
      # sale.save
      # Re-calc All Amount in Sale
      sale.compute_by_sale_items(sale.total_discount, nil, order_source)
      if table.nil?
        result = {:status=> "Success"}
      else
        result = {:status=> "Success", :table_id => table_id, :table_type => table.type }
      end

    else
      if table.nil?
        result = {:status=> "Please, Check Again!"}
      else
        result = {:status=> "Please, Check Again!", :table_id => table_id, :table_type => table.type }
      end

    end

    render :json => result.to_json
  end

  # Remove all discount Items
  def remove_all_discount
    sale_id = params[:id]
    order_source = params[:type]

    if Sale.exists?(sale_id)
      sale = Sale.find(sale_id)

      if sale.bookings[0].dining_facility_id.to_i > 0
        table_id = sale.bookings[0].dining_facility_id
        table = DiningFacility.find(table_id)
        table_type = table.type
      else
        table_id = nil
        table = nil
        table_type = nil
      end

      discount_items = []
      #destroy all discount sale item
      sale.sale_items.each do |si|
        if si.status == "Discount" && si.price < 0
          sale.total_amount = (sale.total_amount + si.price.abs)
          discount_items.push(si)
        end
      end

      # sale.total_discount = 0
      # sale.grand_total = (sale.total_amount - sale.total_discount) + sale.total_tax;
      # sale.save

      #destroy in sale.sale_items
      sale.sale_items.destroy(discount_items)

      action_by = current_user.name
      if table.nil?
        remark = "Remove Discount Sale Id [#{sale.sale_id}]| Receipt No #{sale.receipt_no} | Table- No Table"
      else
        remark = "Remove Discount Sale Id [#{sale.sale_id}]| Receipt No #{sale.receipt_no} | Table- #{table.name} "
      end
      sale_audit = SaleAudit.record_audit_discount(sale.sale_id,sale.cashier_name, action_by,remark,"REMOVEALLDISCOUNT" )

      # Re-calc All Amount in Sale
      sale.compute_by_sale_items(0, nil, order_source)
      if table.nil?
        result = {:status=> "Success"}
      else
        result = {:status=> "Success", :table_id => table_id, :dining => table.name, :table_type => table_type }
      end

    else
      if table.nil?
        result = {:status=> "Please, Check Again!"}
      else
        result = {:status=> "Please, Check Again!", :table_id => table_id, :dining => table.name, :table_type => table_type }
      end

    end

    render :json => result.to_json
  end

  # Member Discount
  def member_discount
    order_source    = params[:cashier_type]
    sale_id         = params[:sale_id]
    is_card         = params[:is_card]
    sub_total       = params[:sub_total]
    tax_type        = params[:tax_type]
    sale            = Sale.find(sale_id)
    if is_card == 'true'
      is_card = true
      else is_card.to_s == 'false'
      is_card = false
    end
    # Check for Card Payment
    is_card_payment = SalePayment.get_sale_payments_by_card(sale.sale_payments)

    # if is_card  != "true"
      account_types =  Account.where("discount=?",true)
      table_id      = sale.bookings[0].dining_facility_id
      # table_type    = DiningFacility.find(table_id).type

      # Get Prices for each accounts (eg: food, beverage)
      account_price = SaleItem.calculate_price_by_accounts(sale.sale_items)
      acc_prices    = Array.new;

      account_types.each do |at|
        account_price.each do |pc|
          if pc[:name] == at.title && pc[:price]>0
             str={type:pc[:name],amount:pc[:price]}
             acc_prices.push(str)
          end
        end
      end
      generic_customer_id = sale.customer.membership_id
      receipt_no          = sale.receipt_no
      membership          = MembershipSetting.find_by_membership_type("paypar_url")
      memberaction        = MembershipAction.find_by_membership_type("member_discount")
      merchant_uid        = memberaction.merchant_account_id.to_s
      campaign_type_id    = memberaction.additional_parameter["campaign_type_id"]
      auth_token          = memberaction.auth_token.to_s
      url                 = membership.gateway_url.to_s + memberaction.gateway_url.to_s
      account_no = sale.customer.paypar_account_no rescue nil

      # Check for items for Paypar Cloud
      if acc_prices.length > 0
          begin
          response        = HTTParty.post(url,
                                  :body => { account_no: account_no,
                                            generic_customer_id:generic_customer_id ,
                                             campaign_type_id: campaign_type_id,
                                             receipt_no: receipt_no,
                                             merchant_uid:merchant_uid,
                                             campaign_method:acc_prices.to_json,
                                             total_sale_transaction_amount: sale.grand_total,
                                             is_card: is_card,
                                             auth_token:auth_token}.to_json,
                                  :headers => {
                                      'Content-Type' => 'application/json',
                                      'Accept'       => 'application/json; version=4'
                           }, :timeout => 10)
          rescue HTTParty::Error
            response = {"status": false, "message": "Http party error" }

          rescue Net::OpenTimeout
            response = {"status": false, "message": "Connection TIme out " }
          rescue OpenURI::HTTPError
            response = {"status": false, "message": "Can't open membership server " }

          rescue SocketError
            response = {"status": false, "message": "Can't open membership server " }
          end
      else
          response = {"status": false, "message": "You have no selected discount item" }
      end
      Rails.logger.debug "-------------- Member Discount Osaka ---------"
      Rails.logger.debug response.to_json
      # Re-calc All Amount in Sale
      if response["status"] == true
          discount_amount   = response["discount_earned"]
          if response["discount_bonus_earned"]
            discount_amount = discount_amount + response["discount_bonus_earned"]
          end
          sale.compute_by_sale_items(discount_amount, 'member_discount', order_source, tax_type)
          result = {:status=> "Success",:title=>"Member Discount", :table_id => table_id }
      elsif response["status"] == "500"
          result = {:status=> response["error"],:title=>"Alert", :table_id => table_id }
      else
        result = {:status=> response["message"],:title=>"Alert", :table_id => table_id }
      end

      render :json => result.to_json

    # end #end Is Card Payment
  end

end
