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

class Admin::SocietesController < ApplicationController
  layout "admin"
  before_action :auth_admin

  before_action :admin_space
  
  def admin_space
    @admin_space = "centres"
  end
  
  def index
    @societes = current_admin.societes
  
    if @societes.count != 1
      
  
      params[:search] = params[:search] || {}

      params[:search][:enabled] = "Oui" if !params[:search][:enabled]

      if params[:search][:enabled].to_s == "Oui"
        @societes = @societes.where(:enabled => true)
      elsif params[:search][:enabled].to_s == "Non"
        @societes = @societes.where(:enabled => false)
      end

      if params[:name].to_s != ""
        @societes = @societes.where("nom LIKE ?","%#{params[:name]}%")
      end

      if params[:city].to_s != ""
        @societes = @societes.where("codepostal LIKE ? or ville LIKE ?","%#{params[:city]}%", "%#{params[:city]}%")
      end

      @societes = sort_by_sorting(@societes, "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 
          @societes = @societes.page(page).per(per_page)
      
        }
      end
    else
      redirect_to admin_societe_path(@societes.first) 
    end
  end

  def show
    @societe = Societe.find(params[:id])

  end

  def new
    @societe = Societe.new
  
  end

  def edit
    @societe = Societe.find(params[:id])
    
  end

  def create
    @societe = Societe.new(params.require(:societe).permit!)

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

  end


  def update
    @societe = Societe.find(params[:id])


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


  def destroy
    @societe = Societe.find(params[:id])
    @societe.destroy
    
  end
end
