namespace :shift_sales do
  desc "TODO"
  task :audit, [:shift_sale_ids, :shop_code, :repayment] => [:environment] do |tasks, args|
    Rails.logger = Logger.new(STDOUT)

    if args[:shift_sale_ids].empty?
      return
    end

    if args[:shift_sale_ids].include? '..'
      shift_sales_ids = args[:shift_sale_ids].split('..').inject { |s,e| s.to_i..e.to_i }
    else
      shift_sales_ids = args[:shift_sale_ids].split(' ')
    end

    shift_sales_ids.each do |shift_sale_id|
      ActiveRecord::Base.transaction do
        shift_sale = ShiftSale.find(shift_sale_id)

        total_revenue     = 0
        total_discounts   = 0
        total_taxes       = 0
        grand_total       = 0
        cash_sales        = 0
        credit_sales      = 0
        other_sales       = 0
        nett_sales        = 0
        commercial_taxes  = 0
        total_rounding    = 0
        total_receipt     = 0
        total_void        = 0
        dining_count      = 0
        takeaway_count    = 0

        sales = shift_sale.sales.order(:created_at)
        sales.each do |sale|
          sale_payments = sale.sale_payments.order(:created_at)

          sale.grand_total = sale.total_amount - sale.total_discount

          if sale.tax_type == 'exclusive'
            sale.grand_total += sale.total_tax
          end

          sale.old_grand_total = grand_total

          if args[:shop_code]
            shop = Shop.find_by!(shop_code: args[:shop_code])
          else
            shop = Shop.first
          end

          if !['foc', 'waste', 'spoile'].include?(sale.payment_status) && (sale.sale_status != 'void' || sale_payments.present?) && shop.is_rounding_adj
            new_total = Sale.get_rounding_adjustment(sale.grand_total)
            sale.rounding_adjustment = new_total - sale.grand_total
            sale.old_grand_total = sale.grand_total
            sale.grand_total = new_total
          else
            sale.rounding_adjustment = 0.00
          end

          if !['foc', 'waste', 'spoile'].include?(sale.payment_status)
            sale.amount_changed = sale.amount_received - sale.grand_total
          else
            sale.amount_changed = 0.00
          end

          sale.update_columns(
            grand_total: sale.grand_total,
            old_grand_total: sale.old_grand_total,
            rounding_adjustment: sale.rounding_adjustment,
            amount_changed: sale.amount_changed
          )

          cash_amount     = 0
          credit_amount   = 0
          other_amount    = 0

          sale_payments.each do |sale_payment|
            if sale_payment.payment_method == 'creditnote'
              credit_amount += sale_payment.payment_amount
            else
              if SaleAudit.where("SUBSTRING_INDEX(sale_audits.remark,'||',1) = ? AND sale_audits.sale_id = ?", sale_payment.sale_payment_id, sale.sale_id).exists?
                if sale_payment.created_at.between?(shift_sale.shift_started_at, shift_sale.shift_closed_at)
                  if credit_amount >= sale_payment.payment_amount
                    credit_amount -= sale_payment.payment_amount
                  else
                    credit_amount = 0
                  end
                  if sale_payment.payment_method == 'cash'
                    cash_amount += sale_payment.payment_amount
                  else
                    other_amount += sale_payment.payment_amount
                  end
                end
              else
                if sale_payment.payment_method == 'cash'
                  cash_amount += sale_payment.payment_amount
                else
                  other_amount += sale_payment.payment_amount
                end
                sale_payment.outstanding_amount = sale.grand_total - sale_payment.payment_amount
                sale_payment.update_columns(outstanding_amount: sale_payment.outstanding_amount)
              end
            end
          end

          if sale.sale_status == 'completed'
            total_revenue     += sale.total_amount
            total_discounts   += sale.total_discount
            total_taxes       += sale.total_tax
            grand_total       += sale.grand_total
            cash_sales        += cash_amount - sale.amount_changed
            credit_sales      += credit_amount
            other_sales       += other_amount
            nett_sales        += sale.total_amount - sale.total_discount
            commercial_taxes  += sale.get_commerical_tax
            total_rounding    += sale.rounding_adjustment
            total_receipt     += 1
            if sale.customer.customer_type == 'Dinein'
              dining_count    += 1
            else
              takeaway_count  += 1
            end
          elsif sale.sale_status == 'void'
            total_receipt     += 1
            total_void        += sale.grand_total
          end
        end

        if args[:repayment]
          SalePayment.joins(:sale, :sale_audit).where(sale_payments: {created_at: shift_sale.shift_started_at..shift_sale.shift_closed_at}).where.not(sales: {shift_sale_id: shift_sale.id}).each do |sale_payment|
            if sale_payment.payment_method == 'cash'
              cash_amount += sale_payment.payment_amount
            else
              other_amount += sale_payment.payment_amount
            end
          end
        end

        shift_sale.update_columns(
          total_revenue: total_revenue,
          total_discounts: total_discounts,
          total_taxes: total_taxes,
          grand_total: grand_total,
          cash_sales: cash_sales,
          credit_sales: credit_sales,
          other_sales: other_sales.to_f,
          nett_sales: nett_sales,
          commercial_taxes: commercial_taxes,
          total_rounding: total_rounding,
          total_receipt: total_receipt,
          total_void: total_void,
          dining_count: dining_count,
          takeaway_count: takeaway_count
        )
      end
    end
  end

end
