class Admins::JobAuthenticationsController < Admins::BaseController
  def index
    params[:status] ||= 'pending'
    params[:sort_direction] = params[:status] == 'pending' ? 'asc' : 'desc'

    if params[:status] != 'pending'
      status = case params[:status]
        when "processed" then ""
        when "agreed" then 1
        when "refused" then 2
        end
      @jobs = Job.joins("JOIN apply_actions ON container_type = 'Job' AND container_id = jobs.id")
      @jobs = @jobs.where("apply_actions.status = ?", status) if status.present?
     
    else
      @jobs = Job.drafted
    end

    @jobs = @jobs.includes(:apply_action, user: { user_extension: [:school, :department]} )

    @jobs = @jobs.order("updated_at desc")

    if params[:keyword].present?
      @jobs = @jobs.where("name like :q OR company like :q", q: "%#{params[:keyword]}%")
    end

    @jobs = paginate @jobs
  end

  def show
    @item = Job.find params[:id]
  end

  def agree
    job = Job.find(params[:id])
    apply = ApplyAction.find_or_initialize_by(user_id: job.user_id, container_id: job.id, container_type: 'Job')
    apply.status = 1
    ActiveRecord::Base.transaction do
      job.publish!
      apply.save!
    end
    render_success_js
  end

  def refuse
    job = Job.find(params[:id])
    apply = ApplyAction.find_or_initialize_by(user_id: job.user_id, container_id: job.id, container_type: 'Job')
    apply.status = 2
    apply.reason = params[:reason]
    ActiveRecord::Base.transaction do
      job.reject!
      apply.save!
    end
    render_success_js
  end


end