class Origami::PaymentsController < BaseOrigamiController
  authorize_resource :class => false
  def index
  end

  def first_bill
    sale_id = params[:sale_id] # sale_id
    sale_data = Sale.find_by_sale_id(sale_id)
    sale_items = SaleItem.where("sale_id=?",sale_id)
    member_info = nil

    # For Cashier by Zone
    bookings = Booking.where("sale_id='#{sale_id}'")
    if bookings.count > 1 
      # for Multiple Booking
      table = DiningFacility.find(bookings[0].dining_facility_id)
    else
      table = DiningFacility.find(bookings[0].dining_facility_id)        
    end

    cashier_zone = CashierTerminalByZone.find_by_zone_id(table.zone_id)
    cashier_terminal = CashierTerminal.find(cashier_zone.cashier_terminal_id)

    # Print for First Bill to Customer
    unique_code = "ReceiptBillPdf"
     #shop detail
    shop_details =  Shop::ShopDetail 
    # customer= Customer.where('customer_id=' +.customer_id)
    customer = Customer.find(sale_data.customer_id)

    # rounding adjustment
      if shop_details.is_rounding_adj
        a = sale_data.grand_total % 25 # Modulus
        b = sale_data.grand_total / 25 # Division
        #not calculate rounding if modulus is 0 and division is even
        #calculate rounding if modulus is zero or not zero and division are not even
        if (a != 0.0 && b%2 != 0.0) || (a==0.0 && b%2 !=0)
          new_total    = Sale.get_rounding_adjustment(sale_data.grand_total)
          rounding_adj = new_total-sale_data.grand_total
          sale_data.update_attributes(grand_total: new_total,old_grand_total: sale_data.grand_total,rounding_adjustment:rounding_adj)        
        end
      end
      #end rounding adjustment

    # get member information
    rebate = MembershipSetting.find_by_rebate(1)
    if customer.membership_id != nil && rebate
      member_info = Customer.get_member_account(customer)
      # current_balance = SaleAudit.paymal_search(sale_id)
      current_balance = 0
    end
    # get printer info
    print_settings=PrintSetting.find_by_unique_code(unique_code)

    # find order id by sale id
    # sale_order = SaleOrder.find_by_sale_id(@sale_data.sale_id)

    # Calculate price_by_accounts
    item_price_by_accounts = SaleItem.calculate_price_by_accounts(sale_items)
    discount_price_by_accounts = SaleItem.get_discount_price_by_accounts(sale_items)

    printer = Printer::ReceiptPrinter.new(print_settings)

    printer.print_receipt_bill(print_settings,cashier_terminal,sale_items,sale_data,customer.name, item_price_by_accounts, discount_price_by_accounts, member_info, shop_details, "Frt",current_balance)    
  end

  def create
    cash = params[:cash]
    sale_id = params[:sale_id]
    member_info = nil

    if(Sale.exists?(sale_id))
      saleObj = Sale.find(sale_id)
      shop_details =  Shop::ShopDetail 
      
      # rounding adjustment
      if shop_details.is_rounding_adj
        a = saleObj.grand_total % 25 # Modulus
        b = saleObj.grand_total / 25 # Division
        #not calculate rounding if modulus is 0 and division is even
        #calculate rounding if modulus is zero or not zero and division are not even
        if (a != 0.0 && b%2 != 0.0) || (a==0.0 && b%2 !=0)
          new_total    = Sale.get_rounding_adjustment(saleObj.grand_total)
          rounding_adj = new_total-saleObj.grand_total
          saleObj.update_attributes(grand_total: new_total,old_grand_total: saleObj.grand_total,rounding_adjustment:rounding_adj)        
        end
      end
      #end rounding adjustment

      sale_payment = SalePayment.new
      sale_payment.process_payment(saleObj, @user, cash, "cash")

      render json: JSON.generate({:status => saleObj.rebate_status, :message => "Can't Rebate coz of Sever Error "})
      rebate_amount = nil

      # For Cashier by Zone
      bookings = Booking.where("sale_id='#{sale_id}'")
      if bookings.count > 1 
        # for Multiple Booking
        table = DiningFacility.find(bookings[0].dining_facility_id)
      else
        table = DiningFacility.find(bookings[0].dining_facility_id)        
      end

      cashier_zone = CashierTerminalByZone.find_by_zone_id(table.zone_id)
      cashier_terminal = CashierTerminal.find(cashier_zone.cashier_terminal_id)

      # For Print
      unique_code = "ReceiptBillPdf"
      customer= Customer.find(saleObj.customer_id)
       
      # get member information
      rebate = MembershipSetting.find_by_rebate(1)
      credit_data = SalePayment.find_by_sale_id_and_payment_method(sale_id,'creditnote')
      
      if customer.membership_id != nil && rebate && credit_data.nil?
        member_info    = Customer.get_member_account(customer)
        rebate_amount  = Customer.get_membership_transactions(customer,saleObj.receipt_no)
        current_balance = SaleAudit.paymal_search(sale_id)
      end
      
      # get printer info
      print_settings=PrintSetting.find_by_unique_code(unique_code)
      # Calculate Food and Beverage Total
      item_price_by_accounts = SaleItem.calculate_price_by_accounts(saleObj.sale_items)
      discount_price_by_accounts = SaleItem.get_discount_price_by_accounts(saleObj.sale_items)

      printer = Printer::ReceiptPrinter.new(print_settings)
      printer.print_receipt_bill(print_settings,cashier_terminal,saleObj.sale_items,saleObj,customer.name, item_price_by_accounts, discount_price_by_accounts, member_info,rebate_amount,shop_details, "Paid",current_balance)   
    end    
  end

  def show
    sale_id = params[:sale_id]

    @member_discount = MembershipSetting.find_by_discount(1)
    
    if Sale.exists?(sale_id)
      @cash = 0.0
      @other = 0.0
      @ppamount = 0.0
      @visacount= 0.0
      @jcbcount= 0.0
      @mastercount = 0.0
      @credit = 0.0
      @sale_data = Sale.find_by_sale_id(sale_id)
      @balance = 0.00
      @accountable_type = ''
      @table_no = ''

      @shop        =  Shop::ShopDetail  
      if @shop.is_rounding_adj
          new_total    = Sale.get_rounding_adjustment(@sale_data.grand_total)
      else
          new_total    = @sale_data.grand_total
      end
      @rounding_adj = new_total-@sale_data.grand_total

      #get customer amount
      @customer = Customer.find(@sale_data.customer_id)
      accounts = @customer.tax_profiles
      @account_arr =[]
      accounts.each do |acc|
        account = TaxProfile.find(acc)
        @account_arr.push(account)
      end
      
      rebate = MembershipSetting.find_by_rebate(1)
      # get member information
      if @customer.membership_id != nil && rebate
        response = Customer.get_member_account(@customer)
        if response["status"]==true
         response["account_data"].each do |res|
          if res["accountable_type"] == "RebateAccount" || res["accountable_type"] == "RebatebonusAccount"
             @balance += res["balance"]
            #  @accountable_type = res["accountable_type"]
             @accountable_type = "Rebate Balance"
          end
        end
        end
      end            

      #end customer amount

      @sale_data.bookings.each do |sbk|
        df = DiningFacility.find(sbk.dining_facility_id)
        @table_no = df.type + ' ' + df.name
        @checkin_time = sbk.checkin_at
        break
      end

        @sale_data.sale_payments.each do |spay|
         if spay.payment_method == "cash"
           @cash = spay.payment_amount
         end
         if spay.payment_method == "mpu"
           @other += spay.payment_amount
         elsif spay.payment_method == "paypar"
           @ppamount += spay.payment_amount
         elsif spay.payment_method == "visa"
           @visacount += spay.payment_amount
         elsif spay.payment_method == "jcb"
           @jcbcount += spay.payment_amount
         elsif spay.payment_method == "master"
           @mastercount += spay.payment_amount
         elsif spay.payment_method == "creditnote"
           @credit += spay.payment_amount
         end
      end
    end
  end

  def reprint
    sale_id = params[:sale_id]
    member_info = nil

    saleObj = Sale.find(sale_id)

    # For Cashier by Zone
    bookings = Booking.where("sale_id='#{sale_id}'")
    if bookings.count > 1 
      # for Multiple Booking
      table = DiningFacility.find(bookings[0].dining_facility_id)
    else
      table = DiningFacility.find(bookings[0].dining_facility_id)        
    end

    cashier_zone = CashierTerminalByZone.find_by_zone_id(table.zone_id)
    cashier_terminal = CashierTerminal.find(cashier_zone.cashier_terminal_id)

    unique_code = "ReceiptBillPdf"
    customer= Customer.find(saleObj.customer_id)

    #shop detail
    shop_details =  Shop::ShopDetail 
    # get member information
    rebate = MembershipSetting.find_by_rebate(1)
    if customer.membership_id != nil && rebate
      member_info = Customer.get_member_account(customer)
      rebate_amount  = Customer.get_membership_transactions(customer,saleObj.receipt_no)
      current_balance = SaleAudit.paymal_search(sale_id)
    end
    # get printer info
    print_settings=PrintSetting.find_by_unique_code(unique_code)

    # Calculate price_by_accounts
    item_price_by_accounts = SaleItem.calculate_price_by_accounts(saleObj.sale_items)
    discount_price_by_accounts = SaleItem.get_discount_price_by_accounts(saleObj.sale_items)

    printer = Printer::ReceiptPrinter.new(print_settings)
    printer.print_receipt_bill(print_settings,cashier_terminal,saleObj.sale_items,saleObj,customer.name, item_price_by_accounts, discount_price_by_accounts, member_info,rebate_amount,shop_details, "Re-print",current_balance)
  end

  def foc    
    cash          = params[:cash]
    sale_id       = params[:sale_id]
    sub_total       = params[:sub_total]
    member_info   = nil
    rebate_amount = nil
    current_balance = nil

    if(Sale.exists?(sale_id))
      saleObj      = Sale.find(sale_id)
      sale_payment = SalePayment.new
      sale_payment.process_payment(saleObj, @user, cash, "foc")

      # For Cashier by Zone
      bookings = Booking.where("sale_id='#{sale_id}'")
      if bookings.count > 1 
        # for Multiple Booking
        table = DiningFacility.find(bookings[0].dining_facility_id)
      else
        table = DiningFacility.find(bookings[0].dining_facility_id)        
      end

      cashier_zone = CashierTerminalByZone.find_by_zone_id(table.zone_id)
      cashier_terminal = CashierTerminal.find(cashier_zone.cashier_terminal_id)

      # Re-call Sale Data
      saleObj      = Sale.find(sale_id)

      unique_code = "ReceiptBillPdf"
      customer= Customer.find(saleObj.customer_id)
      
       #shop detail
      shop_details =  Shop::ShopDetail 

      # get printer info
      print_settings=PrintSetting.find_by_unique_code(unique_code)
      # Calculate Food and Beverage Total
      item_price_by_accounts = SaleItem.calculate_price_by_accounts(saleObj.sale_items)
      discount_price_by_accounts = SaleItem.get_discount_price_by_accounts(saleObj.sale_items)

      printer = Printer::ReceiptPrinter.new(print_settings)
      printer.print_receipt_bill(print_settings,cashier_terminal,saleObj.sale_items,saleObj,customer.name, item_price_by_accounts, discount_price_by_accounts, member_info,rebate_amount,shop_details, "FOC",nil)   
    end    
  end

  def rounding_adj

      saleObj      = Sale.find(params[:sale_id])
      @shop        = Shop.find_by_id(1)
      
      if @shop.is_rounding_adj
        a = saleObj.grand_total % 25 # Modulus
        b = saleObj.grand_total / 25 # Division 
        #not calculate rounding if modulus is 0 and division is even
        #calculate rounding if modulus is zero or not zero and division are not even
        if (a != 0.0 && b%2 != 0.0) || (a==0.0 && b%2 !=0) 
          new_total    = Sale.get_rounding_adjustment(saleObj.grand_total)
          rounding_adj = new_total-saleObj.grand_total
          saleObj.update_attributes(grand_total: new_total,old_grand_total: saleObj.grand_total,rounding_adjustment:rounding_adj)
        end
      end
  end
end