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

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

  before_action :admin_space
  
  def admin_space
    @admin_space = "ventes"
  end
  
  def index
    @s_projects = SProject.includes(:p_customer)


    if params[:search][:code].to_s != ""
      @s_projects = @s_projects.where("p_number LIKE ?","%#{params[:search][:code]}%")
   
    end
    
    if params[:search][:name].to_s != ""
      @s_projects = @s_projects.where("name LIKE ? or description LIKE ?","%#{params[:search][:name]}%","%#{params[:search][:name]}%")
    end
    
    if params[:search][:parent].to_s == "Oui"
      @s_projects = @s_projects.where("parent_id is not NULL")
    elsif params[:search][:parent].to_s == "Non"
      @s_projects = @s_projects.where(:parent_id => nil)
    end
    

    @s_projects = sort_by_sorting(@s_projects, "created_at 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 
    		@s_projects = @s_projects.page(page).per(per_page)
      
      }
    end


  end

  def show
    @s_project = SProject.find(params[:id])

  end

  def new
    @s_project = SProject.new(:parent_id => params[:parent_id])
  
  end

  def edit
    @s_project = SProject.find(params[:id])
    
  end

  def create
    @s_project = SProject.new(params.require(:s_project).permit!)

    if @s_project.save
      if @s_project.parent
        redirect_to [:admin, @s_project.parent]
      else
        redirect_to admin_s_projects_path
      end
    else
      render action: "new"
 
    end

  end


  def update
    @s_project = SProject.find(params[:id])


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


  def destroy
    @s_project = SProject.find(params[:id])
    @s_project.destroy
    
  end
end
