class Origami::CustomersController < BaseOrigamiController
  load_and_authorize_resource
  def index
  end

  # GET /crm/customers/1
  # GET /crm/customers/1.json
  def show
  end

  def get_customer
    filter = params[:filter]
    type   = params[:type]

    if filter.nil?
      @crm_customers = Customer.order("customer_id").page(params[:page])
      #@products = Product.order("name").page(params[:page]).per(5)
    else
      @crm_customers = Customer.search(filter)
    # search account no from paypar
      if !@crm_customers.present? && type == "card"
        response = Customer.search_paypar_account_no(filter)
        if response["status"] == true
          @crm_customers = Customer.new
          @crm_customers.name              = response["customer_data"]["name"]
          @crm_customers.contact_no        = response["customer_data"]["phone"]
          @crm_customers.email             = response["customer_data"]["email"]
          @crm_customers.date_of_birth     = response["customer_data"]["DOB"]
          @crm_customers.nrc_no            = response["customer_data"]["NRC"]
          @crm_customers.address           = response["customer_data"]["address"]
          @crm_customers.card_no           = response["customer_data"]["customer_card_no"]
          @crm_customers.paypar_account_no = filter
          @crm_customers.membership_id     = response["customer_data"]["id"]
          @crm_customers.membership_type   = response["customer_data"]["member_group_id"]
          @crm_customers.customer_type     = "Dinein"
          @crm_customers.tax_profiles      = ["1", "2"]
          @crm_customers.save
          @crm_customers = Customer.search(filter)
        else
           @crm_customers = [{"customer_id": response["status"],"message": response["message"] }]
        end
      end
    end

    render :json => @crm_customers.to_json
  end

  def add_customer
    @webview = false
    if check_mobile
      @webview = true  
    end
    
    @sale_id             = params[:sale_id]
    @cashier_type        = params[:type]
    @page                = params[:dir_page]
    
     if(@sale_id[0,3] == "SAL")
       @booking          = Booking.find_by_sale_id(@sale_id)
       if @booking.dining_facility_id.to_i > 0
        @dining_facility  = DiningFacility.find(@booking.dining_facility_id)
       else
        @dining_facility  = nil  
       end
       
    else
       @booking_order    = BookingOrder.find_by_order_id(@sale_id)
       @booking          = Booking.find(@booking_order.booking_id)
       if @booking.dining_facility_id.to_i > 0
         @dining_facility  = DiningFacility.find(@booking.dining_facility_id)
       else
        @dining_facility  = nil  
       end
    end       

    filter = params[:filter]
    
    if filter.nil?
      @crm_customers = Customer.order("customer_id") #.page(params[:page])
      #@products = Product.order("name").page(params[:page]).per(5)
    else
      @crm_customers = Customer.search(filter)       
    end
    #@crm_customers  = Customer.all
    @crm_customers   = Kaminari.paginate_array(@crm_customers).page(params[:page]).per(20)
    @crm_customer    = Customer.new
    @count_customer = Customer.count_customer
    
    # @taxes = TaxProfile.where(:group_type => 'cashier')
    @taxes = TaxProfile.unscoped.select("id, (CONCAT(name,'(',(SELECT name FROM lookups WHERE lookup_type='tax_profiles' AND value=group_type),')')) as name")
          .order("group_type ASC,order_by ASC")
    # if flash["errors"]
    #   @crm_customer.valid?
    # end
    @membership_types = Lookup.collection_of("member_group_type")
    #get paypar accountno
    @paypar_accountno = Customer.where("paypar_account_no IS NOT NULL AND paypar_account_no != ''").pluck("paypar_account_no")
    #for create customer on/off
    @create_flag = true
    lookup_customer = Lookup.collection_of('customer_settings')
    if !lookup_customer.empty?
      lookup_customer.each do |create_setting|
        if create_setting[0].downcase == "create" 
          if create_setting[1] == '0' && current_login_employee.role == 'cashier'
            @create_flag = false
          end
        end
      end
    end

    respond_to do |format|
      # format.html { render :template => "crm/customers/index" }
      format.html { render action: "index"}
      format.json { render json: @crm_customers }
    end
  end

  def update_sale_by_customer

    id           = params[:sale_id][0,3]
    customer_id  = params[:customer_id]
    customer     = Customer.find(customer_id)
    order_source = params[:type]
    # Check and find with card no
    # if(!customer_id.include? "CUS")
    #   customer = Customer.find_by_paypar_account_no(customer_id)
    #   if(customer != nil)
    #     customer_id = customer.customer_id
    #   end
    # end

    if(id == "SAL")
       sale   = Sale.find(params[:sale_id])
       status = sale.update_attributes(customer_id: customer_id)
       sale.sale_orders.each do |sale_order|
        order = Order.find(sale_order.order_id)
          status = order.update_attributes(customer_id: customer_id,order_type:customer.customer_type)
      end
      action_by = current_user.id
      remark = "Assign Customer Receipt No #{sale.receipt_no} | Sale ID #{sale.sale_id} | Customer ID ->#{customer.customer_id}- Customer Name ->#{customer.name}"
      sale_audit = SaleAudit.record_audit_for_edit(sale.sale_id,sale.cashier_id, action_by,remark,"ASSIGNCUSTOMER" )

    else
       @booking = BookingOrder.find_by_order_id(params[:sale_id])
       @orders  = BookingOrder.where("booking_id = ? ", @booking.booking_id)

        @orders.each do |bo|
          order  = Order.find(bo.order_id)
          status = order.update_attributes(customer_id: customer_id,order_type:customer.customer_type)
       end

    end

    if status == true
        render json: JSON.generate({:status => true})
        if(id == "SAL")
          sale.compute_by_sale_items(sale.sale_id, sale.sale_items, sale.total_discount, nil, order_source)
        end 
    else
        render json: JSON.generate({:status => false, :error_message => "Record not found"})
    end
  end
  
  def send_account
    amount = params[:amount]
    account_no = params[:account_no]
    receipt_no = params[:receipt_no]
    sale = Sale.find_by_receipt_no(receipt_no)
    @out = []
    action_by = current_user.name
    membership_setting = MembershipSetting.find_by_membership_type("paypar_url")
    if membership_setting.gateway_url
      member_actions =MembershipAction.find_by_membership_type("get_account_balance")
      if member_actions.gateway_url
        @campaign_type_id = nil
        url = membership_setting.gateway_url.to_s + member_actions.gateway_url.to_s
        merchant_uid= member_actions.merchant_account_id
        auth_token = member_actions.auth_token.to_s
        membership_data = SalePayment.get_paypar_account_data(url,membership_setting.auth_token,merchant_uid,auth_token,account_no,amount,receipt_no)
        if membership_data["status"]==true
          remark = "Payment by account no Receipt No #{sale.receipt_no} | Sale ID #{sale.sale_id} | Transaction ref: #{membership_data[:transaction_ref]} | Reload amount #{membership_data[:reload_amount]} | Old Balance Amount #{membership_data[:old_balance_amount]} | DateTime : #{membership_data[:date]}"
          sale_audit = SaleAudit.record_audit_for_edit(sale.sale_id,sale.cashier_id, action_by,remark,"PAYBYACCOUNT" )
        else
          remark = "Payment by account no Receipt No #{sale.receipt_no} | Sale ID #{sale.sale_id} | Remark : #{membership_data[:message]}"
          sale_audit = SaleAudit.record_audit_for_edit(sale.sale_id,sale.cashier_id, action_by,remark,"PAYBYACCOUNT" )
        end
        @out = membership_data

        render json: JSON.generate({:status => membership_data["status"], :message => membership_data["message"]})
      end
    end
  end
end
