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],

      :address => params[:address],

      :address2 => params[:address2],

      :cp => params[:cp],

      :city => params[:city],

      :tel => params[:tel],

      :email => params[:mail],

      :place => params[:place],

      :sheet_type => params[:type],

      :owner => params[:owner],
	
      :message => params[:message]
      
    } 
    
  	@contact = Contact.new(contact_api_params)
    @contact.provenance_id = 2
    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