# -*- encoding : utf-8 -*-

class Admin::MOdrPrimesController < ApplicationController
  layout "admin"
  before_action :auth_admin

  before_action :admin_space
  
  def admin_space
    @admin_space = "payments"
  end
  
  def index
    @m_odr_primes = MOdrPrime.all

    @m_odr_primes = sort_by_sorting(@m_odr_primes, "id DESC")
    respond_to do |format|
      format.html{
      
        params[:search][:per_page] = params[:search][:per_page] || 100
        per_page = params[:search][:per_page]
        page = (params[:page] and params[:page] != "") ? params[:page] : 1 
        @m_odr_primes = @m_odr_primes.page(page).per(per_page)
      
      }
    end
  end

  def show
    @m_odr_prime = MOdrPrime.find(params[:id])

  end

  def new
    @m_odr_prime = MOdrPrime.new
  
  end

  def edit
    @m_odr_prime = MOdrPrime.find(params[:id])
    
  end

  def create
    @m_odr_prime = MOdrPrime.new(params.require(:m_odr_prime).permit!)

    if @m_odr_prime.save
      
    else
      render action: "new"
 
    end

  end


  def update
    @m_odr_prime = MOdrPrime.find(params[:id])


    if @m_odr_prime.update_attributes(params.require(:m_odr_prime).permit!)
      
    else
     render action: "edit" 
      
    end
      
  end


  def destroy
    @m_odr_prime = MOdrPrime.find(params[:id])
    @m_odr_prime.destroy
    
  end

  def generate_virement
    @m_odr_prime = MOdrPrime.find(params[:id])
    
    if @m_odr_prime.p_customer.valid_m_odr_rep_rib
      @m_odr_prime.m_odr_virements.create
      @m_odr_prime.change_state("Virement demandé")
      
      
      if @m_odr_prime.p_customer.mail_hists.where(:mail_type_id => 14).count == 0
        @m_odr_prime.send_mail_type("primes-valide-1")
        
      else
        @m_odr_prime.send_mail_type("primes-valide-2")
      end
        
      
      
    else
      @m_odr_prime.change_state("Manque RIB")
      
      @m_odr_prime.send_mail_type("primes-manque-rib") if @m_odr_prime.p_customer.m_odr_rep_ribs.count == 0
    end
    
    redirect_back(fallback_location:"/")
  end
  
    
end
