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

class Admin::MOdrFilesController < ApplicationController
  layout "admin"
  before_action :auth_admin, :except => [:download]

  before_action :admin_space
  
  def admin_space
    @admin_space = "payments"
  end
  
  def index
    @m_odr_files = MOdrFile.all

    @m_odr_files = sort_by_sorting(@m_odr_files, "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_files = @m_odr_files.page(page).per(per_page)
      
      }
    end
  end


  def show
    @m_odr_file = MOdrFile.find(params[:id])

  end

  def new
    @m_odr_file = MOdrFile.new(:m_odr_file_type_id => params[:m_odr_file_type_id], :p_customer_id => params[:p_customer_id])
  
  end

  def edit
    @m_odr_file = MOdrFile.find(params[:id])
    
  end
  
  
  def download
    @m_odr_file = MOdrFile.find(params[:id])
    
    if @m_odr_file.file
      send_file @m_odr_file.file.path, :disposition => (params[:disposition] || :inline)
    end
  end


  def send_mail
    @m_odr_file = MOdrFile.find(params[:id])
    @m_odr_file.send_mail_type(params[:slug].to_s)
    
    redirect_to [:admin, @m_odr_file]
    
    
  end

  def create
    @m_odr_file = MOdrFile.new(params.require(:m_odr_file).permit!)

    if @m_odr_file.save
      
      #@m_odr_file.m_odr_rep.change_state("En cours de traitement")
      redirect_to admin_m_odr_files_path()
    else
      render action: "new"
 
    end

  end


  def update
    @m_odr_file = MOdrFile.find(params[:id])
    @m_odr_rep = @m_odr_file.m_odr_rep

    if @m_odr_file.update_attributes(params.require(:m_odr_file).permit!)
    
      #@m_odr_file.m_odr_rep.change_state("En cours de traitement")
      @m_odr_file.p_customer.generate_prime if @m_odr_file.p_customer

      redirect_to [:admin, @m_odr_file]
    else
     render action: "edit" 
      
    end
    
    
    
      
  end


  def destroy
    @m_odr_file = MOdrFile.find(params[:id])
    @m_odr_file.destroy
    
  end

  def rotate
    deg = params[:direction] == "right" ? -90 : 90
    
    @m_odr_file = MOdrFile.find(params[:id])
    @m_odr_file.rotate(deg)
  end


end
