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

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

  before_action :admin_space
  
  def admin_space
    @admin_space = "default"
  end
  
  def index
    @p_articles = PArticle.all

    if params[:search][:p_product_color].to_s != ""
      if params[:search][:p_product_color].to_s == "null"
        @p_articles = @p_articles.joins(:p_product_ref).where("p_product_color_id = ?", nil)
      else
        @p_articles = @p_articles.joins(:p_product_ref).where("p_product_color_id = ?", params[:search][:p_product_color])
      end
    end

    if params[:search][:p_product_ref_cc_name]
      @p_articles = @p_articles.joins(:p_product_ref).where("cc_name LIKE ?", "#{params[:search][:p_product_ref_cc_name]}%")
    end

    if params[:search][:p_grade_id]
      @p_articles = @p_articles.where("p_grade_id LIKE ?", "#{params[:search][:p_grade_id]}%")
    end

    if params[:search][:p_product_ref_cc_code]
      @p_articles = @p_articles.joins(:p_product_ref).where("cc_code LIKE ?", "#{params[:search][:p_product_ref_cc_code]}%")
    end

    if params[:search][:p_article_serial_num]
      @p_articles = @p_articles.joins(:p_article_serial_nums).where("value LIKE ?", "#{params[:search][:p_article_serial_num]}%")
    end


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

  def show
    @p_article = PArticle.find(params[:id])

  end

  def new
    @p_article = PArticle.new
    @p_article_serial_nums = @p_article.p_article_serial_nums.build

    @p_serial_num_type = @p_article_serial_nums.build_p_serial_num_type
    # @p_serial_num_value = @p_article_serial_nums.build_p_serial_num_value
  end

  def edit
    @p_article = PArticle.find(params[:id])
    
  end

  def create
    @p_article = PArticle.new(params.require(:p_article).permit!)

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

  end


  def update
    @p_article = PArticle.find(params[:id])


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


  def destroy
    @p_article = PArticle.find(params[:id])
    @p_article.destroy
    
  end
end
