class Contact < ActiveRecord::Base

  belongs_to :admin
  has_many :contact_actions
  validates :name, :presence => true
  #validates :email, :presence => true, :if => :email_needed?
  validates :email, :format => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i, :if => :email_needed?
  #validates :message, :presence => true
  #validates :phone, :presence => true
  
  has_many :contact_files
  
  validates :address, :presence => true, :if => :address_needed?
  validates :cp, :presence => true, :if => :address_needed?
  validates :city, :presence => true, :if => :address_needed?
  
  has_many :contact_products
  has_many :d_products, :through => :contact_products
  
  accepts_nested_attributes_for :contact_products
  
  def email_needed?
    true if self.email?
  end
  
  def address_needed?
    true if self.raison_id == 4
  end
  
  before_validation do
    if (true or ((raison_id == 4 )) and !self.email? and !self.phone?)
      errors.add(:email, "Vous devez indiquer votre numéro de téléphone et/ou votre email") 
      errors.add(:phone, "Vous devez indiquer votre numéro de téléphone et/ou votre email") 
      
    end


    
  end
  
  

  def syncro
    require 'net/https'
    require 'open-uri'
    @params = {
      :name => self.name,

      :firstname => self.firstname,

      :corporate => self.corporate,

      :email => self.email,

      :phone => self.phone,

      :message => self.message,
      
      :provenance_id => self.provenance_id
    }
    

    if Rails.env.development?
      api_url ="http://localhost:3030/admin/contacts/api"
    else
      api_url = "https://groupe-payre.fr/admin/contacts/api"
    end

    @c = Curl::Easy.new(api_url) do |curl|      
      curl.verbose = true
    end


    @c.http_post(
    Curl::PostField.content(:name, @params[:name]),
    Curl::PostField.content(:firstname, @params[:firstname]),
    Curl::PostField.content(:corporate, @params[:corporate]),
    Curl::PostField.content(:email, @params[:email]),
    Curl::PostField.content(:phone, @params[:phone]),
    Curl::PostField.content(:message, @params[:message]),
    Curl::PostField.content(:provenance_id, @params[:provenance_id])
    
    )

    @debug = @c.body_str
    
     
    
  end

end
