class Admin::ContactsController < ApplicationController
  layout "admin"
  
  before_filter :auth_admin, :except => :api
  skip_before_filter  :verify_authenticity_token, :only => :api
  def index
    
    @contacts = Contact.order("created_at DESC")
    
    if params[:status]
      @contacts = @contacts.where(:contact_status => params[:status])
    else
      @contacts = @contacts.where(:contact_status => "En cours")
    end
    
  end


  def show
    @contact = Contact.find(params[:id])
    
    if @contact.readed != true
      @contact.readed = true
      @contact.save
    end
    
    @contact_actions = @contact.contact_actions

  end


  def new
    @contact = Contact.new
  
  end

  def edit
    @contact = Contact.find(params[:id])
  
  end

  def create
  	@contact = Contact.new(contact_params)
    
    if @contact.save
      @contacts = Contact.order("created_at DESC").all
  	else
  		render :action => "new" 
  	end
  end

  def update
  	@contact = Contact.find(params[:id])
    
    if @contact.update_attributes(contact_params)

  	else
  		render :action => "edit" 
  	end
    
  end
  		


  def destroy
  	@contact = Contact.find(params[:id])
	  
    @contact.destroy if @contact != @current_contact
  
  end
  
  
  def api
    
    contact_api_params = {
      :name => params[:name],

      :firstname => params[:firstname],

      :corporate => params[:corporate],

      :email => params[:email],

      :phone => params[:phone],

      :message => params[:message],
      
      :provenance_id => params[:provenance_id],
      
      :contact_status => "En cours"
      
    } 
    
  	@contact = Contact.new(contact_api_params)
  
    if @contact.save(:validate => false)
      render :inline => "ok"
      puts "OK"
  	else
  		render :inline => "erreur" 
      puts "ERREUR"
      @contact.errors.each do |error|
        puts error
      end
  	end
    
    
  end
  
  
  
  private
      def contact_params
        params.require(:contact).permit!
      end



end
