class Admin::Accounting::Billing::Templates::TransactionsController < Admin::Accounting::Controller
  def index
    render_success :ok, json: transactions.map { |t| transaction_props(t) }
  end

  def create
    template_transactions.build_detail(detail_params) if params[:charge]
    template_transactions.build_detail(detail_params(:credit)) if params[:credit]

    if template.save
      render_success :ok
    else
      render_error :unprocessable_entity, errors: template
    end
  end

  def update
    if transaction.update(memo: params[:memo])
      render_success :ok
    else
      render_error :unprocessable_entity, errors: transaction
    end
  end

  def destroy
    if transaction.destroy
      render_success :ok
    else
      render_error :unprocessable_entity, errors: transaction
    end
  end

  private
    def transactions
      template.transaction_details
    end

    def template_transactions
      template.template_transactions.build
    end

    def template
      @template ||= current_school.billing_templates.find_by(id: params[:template_id])
    end

    def transaction
      @transaction ||= transactions.find_by(id: params[:id])
    end

    def subcategory(type)
      current_school.accounting_subcategories.find_by(id: params[type][:subcategory_id])
    end

    def set_amount(type)
      return params[type][:amount] if type == :charge || params[type][:fixed]

      params[:charge][:amount].to_f * params[:credit][:amount].to_f / 100
    end

    def detail_params(type=:charge)
      params[type].permit(:memo).merge(
        subcategory: subcategory(type),
        amount: set_amount(type),
        charge: type == :charge,
        transaction_days: params[:days]
      )
    end

    def transaction_props(transaction)
      {
        id: transaction.id,
        template_id: template.id,
        subcategory_id: transaction.subcategory_id,
        subcategory_name: transaction.subcategory.decorate.title,
        memo: transaction.memo,
        amount: transaction.amount.to_f,
        installments: transaction.days.count,
        total: transaction.amount.to_f * transaction.days.count,
        charge: transaction.charge
      }
    end
end
