class PurchaseOrdersController < ApplicationController
  before_action :authenticate_user!
  before_action :dashboard_topbar
  #load_and_authorize_resource :class => PurchaseOrder
  #skip_load_resource :only => [:new, :create]


  def index
    @sim_router_inventories = current_user.organisation.sim_managements
  end

  def new
    @purchase_orders = current_user.organisation.purchase_orders.build
    @purchase_orders_router_inventories = current_user.organisation.sim_managements
    @orders_selected = SimManagement.where(:id => params["sim_router_inventories_ids"])
    @selected_value = params["sim_router_inventories_ids"]
    @sim_rate_plans = SimRatePlan.all
    @nameplan_collection = PurchaseOrder.grouped_collection_of_plan_name_type
  end

  def create
    if params["purchase_order"]["sim_rate_plan_id"].present?
      plan_id = params["purchase_order"]["sim_rate_plan_id"]
      plan_amount = params["purchase_order"]["amount"]
      auto_recharge = params["purchase_order"]["auto_recharge"]
      @r_ids = SimManagement.where(id: params["mac_id"])
      @purchase_orders = current_user.organisation.purchase_orders.build
      @purchase_orders[:amount] = plan_amount
      #@purchase_orders[:ordered_by] = current_user.id
      @purchase_orders[:auto_recharge] = auto_recharge
      @purchase_orders[:sim_rate_plan_id] = plan_id
      @r_ids.each do |sim_management|
        @purchase_orders.purchase_order_items.build :itemable_id => sim_management.id, :itemable_type => sim_management.class.name
        sim_management.update_column("sim_rate_plan_id",plan_id)
      end
      @purchase_orders.save 
      flash[:success] = "Plan was selected.Please make a payment"
      redirect_to new_payment_invoice_path(:id =>@purchase_orders.id)
    else 
      flash[:error] = "Oops! Problem in Purchasing Plan.Please try later"
      Rails.logger.warn "#{purchase_orders.errors.full_messages}"
      redirect_to new_purchase_orders_path
    end
  end 


  def edit
    if params[:id].present?
      @purchase_orders = SimManagement.where(id: params["id"])
    else
    end  
  end

  def change_plan
    @sim_managements = SimManagement.where(id: params["sim_ids"])
    sim_rate_plan = SimRatePlan.where(plan_id: params[:sim_plan_id]).last
    sims_failed_to_update = []
    @sim_managements.each do |sim_management|
      if params[:button] == "change_sim_plan"
        prev_pn = sim_management.sim_rate_plan_id.deep_dup
        resp = SimRatePlan.change_plan(sim_management.sid,params[:sim_plan_id])
        if resp == true
          sim_management.update_column("sim_rate_plan_id",sim_rate_plan.id) if sim_rate_plan.present?
          PublicActivity::Activity.create(trackable_id: current_user.id, trackable_type: "SimManagement", owner_id: current_user.id, owner_type: "User", key: "sim_management.update", organisation_id: current_user.organisation_id, location_network_id: current_user.location_networks.present? ? current_user.location_networks.first.id : nil, parameters: {:attributes => {"sim_management(#{sim_management.sim_rate_plan_id})" => {"sim_rate_plan_id" => [prev_pn, sim_management.sim_rate_plan_id]}}}, assumed_by: session[:assume_user])
        else
          sims_failed_to_update << sim_management.iccid
        end
      end
      if params[:button] == "change_sim_status"
        sim_rate_plan = sim_management.sim_rate_plan
        prev_st = sim_management.current_status.deep_dup
        @response = SimRatePlan.update_status(sim_management,params[:sim_status]) if sim_rate_plan.present?
        if @response == false
          sims_failed_to_update << sim_management.iccid
        else
          sim_management.update_column("current_status",params[:sim_status])
          PublicActivity::Activity.create(trackable_id: current_user.id, trackable_type: "SimManagement", owner_id: current_user.id, owner_type: "User", key: "sim_management.update", organisation_id: current_user.organisation_id, location_network_id: current_user.location_networks.present? ? current_user.location_networks.first.id : nil, parameters: {:attributes => {"sim_management(#{sim_management.current_status})" => {"current_status" => [prev_st, sim_management.current_status]}}}, assumed_by: session[:assume_user])
        end
      end
      #if params[:button] == "change_sim_organisation"
      #  sim_organisation = sim_management.organisation
      #  if sim_organisation.present?
      #    sim_management.update("organisation_id" => params["sim_org"])
      #  else
      #    sims_failed_to_update << sim_management.iccid
      #  end
      #end
    end
    if sims_failed_to_update.present?
      flash[:notice] = "Following ICCID's <b> #{sims_failed_to_update.join(",")}</b> are not updated"
    else
      flash[:success] = "Successfully Plan/Status is updated"
    end
    redirect_to admin_sim_managements_path
  end

  def get_sim_rate_plan_details
    if params[:plan_id].present?
      @sim_details  = SimRatePlan.where(id: params["plan_id"])
      @total_amount = @sim_details.pluck(:amount).first.to_f * params["orders"].to_i
    end
    respond_to do |format|
      format.html
      format.json { render :json => {:sim_details => @sim_details,:amount => @total_amount}}
    end
  end


  private
    def purchase_orders_params
      params.require(:purchase_orders).permit(:id,:mac_id,:router_inventory_id,sim_rate_plan_id,:auto_recharge)
    end
end
