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

class Admin::PCustomersController < ApplicationController
  layout "admin"
  before_filter :auth_admin
  
  before_filter :admin_space
  
  
  def import
    if false
      
      @file = params[:csv_file]
    
      require 'csv'    

      csv_text = File.read("#{Rails.root}/import_csv/clients2.csv").force_encoding('ISO-8859-1')
      @csv = CSV.parse(csv_text, :headers => true, :col_sep => ";")
    end
    
  end
  
  
  
  
  def admin_space
    @admin_space = "clients"
  end
  
  
  def index
    @p_customers = PCustomer.order(:name).all
    
    @fav_p_customers = PCustomer.where(:fav => true).order(:name).all
    
    if params[:search].to_s != ""
      @p_customers = @p_customers.for_search(params[:search])
    end
    
		per_page = (params[:per_page] and params[:per_page] != "") ? params[:per_page] : 50
		page = (params[:page] and params[:page] != "") ? params[:page] : 1 
		@p_customers = @p_customers.page(page).per(per_page)
   
  end

  def show
    @p_customer = PCustomer.find(params[:id])

  end

  def new
    
    
		@p_customer = PCustomer.new()
    @p_customer.particulars << Particular.new(:pro => true, :skip_validation => true)

  end

 

  def edit
  
    
    @p_customer = PCustomer.find(params[:id])
  end

  def create
    @p_customer = PCustomer.new(params.require(:p_customer).permit!)


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

  end


  def update
    @p_customer = PCustomer.find(params[:id])


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


  def destroy
    @p_customer = PCustomer.find(params[:id])
    @p_customer.destroy
    
    
  end
  
  
  def autocomplete
    @p_customers = PCustomer.for_search(params[:search]).limit(50)
    
    respond_to do |format|
        format.json { render json: @p_customers.map {|va| { id: va.id, show_name: va.show_name }}.to_json( :only => [:id, :show_name] ) }
    end
  end
  
  def autocomplete_apercu
    @p_customer = PCustomer.find(params[:id])
    
  end
  
  
end