class ClientManagementsController < CPanelController
  include CPanelHelper
  before_filter :is_user_authorized?
  before_filter :is_site_authorized_to_user?, :only => ["show", "site_tickets", "new_ticket", "create_ticket"]
  before_filter :is_ticket_authorized_to_user?, :only => ["close_ticket","reopen_ticket","delete_ticket", "show_ticket", "create_ticket_query"]
  
  def index
  end

  def user_sites
    @sites = current_cpanel_user.registered_sites
    @sites = Kaminari.paginate_array(@sites).page(params[:page]).per(10)
    render :layout => false
  end

  def addsite
    if session[:addsitestouser].present?
      @noticemsg = true
      @uid = session[:request_uid]
      session.delete(:addsitestouser)
      session.delete(:request_uid)
    end
  end

  def addnewsite
    @newrequest = SiteRequest.new
    @user_sites = current_cpanel_user.registered_sites.collect{|rs|[rs.title, rs.id.to_s]}
    @user_sites << ["Create new site", "newsite"]
    @user_sites << ["Upgrade from R2", "upgrade"]
    @optional_modules = RegisteredModule.where(:category_id.in => ["54ae569248345219fa080000","54abc1797470006ee0270000"], :approved => true)
  end

  def requestsite
    rs = SiteRequest.new(rs_params)
    rs.c_panel_user = current_cpanel_user
    rs.type = rs.site_id == "newsite" ? "newsite" : "existing"
    case rs.site_id
    when "newsite"
      rs.type = "newsite"
    when "upgrade"
      rs.type = "upgrade"
    else
      rs.type = "existing"
    end
    rs.save
    session[:addsitestouser] = true
    session[:request_uid] = rs.uid
    redirect_to cpanel_add_site_path
  end


  def addsitestouser
    urls = params[:urls].split(";") rescue []
    sr = SiteRequest.new
    sr.sites_to_add = urls
    sr.c_panel_user = current_cpanel_user
    sr.type = "addsites"
    sr.save
    session[:addsitestouser] = true
    session[:request_uid] = sr.uid
    redirect_to cpanel_add_site_path
  end

  def show
    @categories = ModuleApp.where(:key => "ticket").first.categories.enabled.collect{|cat| [cat.title, cat.id.to_s] }
  end

  def show_ticket
    if session[:reopen_cpanel_error].present?
      @reopen_error = session[:reopen_cpanel_error]
      session.delete(:reopen_cpanel_error)
    end
  end


  def dofirstrun
    do_first_time_run
    @sites = current_cpanel_user.registered_sites
    @sites = Kaminari.paginate_array(@sites).page(params[:page]).per(10)
    render :layout => false
  end

  def site_tickets
    if params[:category].present? && params[:keyword].present?
      regex = ::Regexp.new(".*" + params[:keyword] + ".*", "i") 
      @tickets = @site_construct.tickets.where(:category_id => params[:category], :subject => regex).order_by([:status, :desc],[:created_at, :desc]).page(params[:page]).per(10)
    elsif params[:category].present?
      @tickets = @site_construct.tickets.where(:category_id => params[:category]).order_by([:status, :desc],[:created_at, :desc]).page(params[:page]).per(10)
    elsif params[:keyword].present?
      regex = ::Regexp.new(".*" + params[:keyword] + ".*", "i") 
      @tickets = @site_construct.tickets.where(:subject => regex).order_by([:status, :desc],[:created_at, :desc]).page(params[:page]).per(10)
    else
      @tickets = @site_construct.tickets.order_by([:status, :desc],[:created_at, :desc]).page(params[:page]).per(10)
    end
    render :layout => false
  end

  def new_ticket
    @categories = ModuleApp.where(:key => "ticket").first.categories.enabled.collect{|cat| [cat.title, cat.id.to_s] }
    @ticket = Ticket.new
  end

  def create_ticket
    ticket = Ticket.new(ticket_params)
    ticket.save
    redirect_to cpanel_site_show_path(@site_construct.uid)
  end

  def close_ticket
    @ticket.status = "closed"
    @ticket.save
    if request.xhr?
      render :json => {"success" => true}.to_json
    else
      redirect_to cpanel_show_ticket_path(@ticket.id)
    end
  end

  def delete_ticket
    @ticket.destroy
    if request.xhr?
      render :json => {"success" => true}.to_json
    else
      redirect_to cpanel_show_ticket_path(@ticket.id)
    end
  end

  def reopen_ticket
    if @ticket.can_be_reopened?
      @ticket_query = @ticket.ticket_queries.new 
    else
      session[:reopen_cpanel_error] = "This ticket cannot be reopened."
      redirect_to cpanel_show_ticket_path(@ticket.id) and return
    end
  end

  def create_ticket_query
    if @ticket.can_be_reopened?
      TicketQuery.create(tq_params)
      @ticket.reopened_count = @ticket.reopened_count + 1
      @ticket.status = "open"
      @ticket.save
      redirect_to cpanel_show_ticket_path(@ticket.id) and return
    else
      session[:reopen_cpanel_error] = "This ticket cannot be reopened."
      redirect_to cpanel_show_ticket_path(@ticket.id) and return
    end
  end 

  # profile panel code

  def myprofile
    @user = CPanelUser.find(current_cpanel_user.id) rescue nil
  end

  def update_member_profile
    user = CPanelUser.find(current_cpanel_user.id) rescue nil
    user.update_attributes(update_member_profile_params)
    user.save
    redirect_to cpanel_myprofile_path
  end

  def myprofilepassword
    if session[:update_profile_password_set]
      if !session[:update_profile_password_error].blank?
        @error = session[:update_profile_password_error]
        session.delete(:update_profile_password_error)
        session.delete(:update_profile_password_set)
      else
        session.delete(:update_profile_password_set)
        @error = "success"
      end
    end
    @user = CPanelUser.find(current_cpanel_user.id) rescue nil
  end

  def update_member_profile_password
    session[:update_profile_password_set] = true
    user = CPanelUser.find(current_cpanel_user.id) rescue nil
    if user && user.authenticate(params[:current_password])
      if params[:new_password] == params[:repeat_password]
        user.update_password(params[:new_password], params[:repeat_password])
      else
        session[:update_profile_password_error] = "New password and repeat password don't match."
      end
    else
      session[:update_profile_password_error] = "Your current password did not match."
    end
    redirect_to cpanel_myprofilepassword_path
  end

  def history
    if !params[:query].present?
      @objects = SiteRequest.where(:c_panel_user_id => current_cpanel_user.id).desc(:created_at).page(params[:page]).per(15)
    elsif params[:query] == "addsites"
      @objects = SiteRequest.where(:type => "addsites", :c_panel_user_id => current_cpanel_user.id).desc(:created_at).page(params[:page]).per(15)
    else
      @objects = SiteRequest.where(:site_id => params[:query], :c_panel_user_id => current_cpanel_user.id).desc(:created_at).page(params[:page]).per(15)
    end
    if request.xhr?
      render :partial => "history_partial"
    else
      @user_sites = current_cpanel_user.registered_sites.collect{|rs|[rs.title, rs.id.to_s]}
      @user_sites << ["New site request", "newsite"] 
      @user_sites << ["Addition of sites request", "addsites"] 
    end
  end

  def see_request
    @site_request = SiteRequest.where(:uid => params[:request_uid]).first rescue nil
  end

  def see_contract
    @contract = RequestContract.where(:uid => params[:contract_uid]).first rescue nil
    @site_request = @contract.site_request
  end

  def update_contract
    contract = RequestContract.where(:uid => params[:contract_uid]).first rescue nil
    contract.update_attributes(contract_params)
    redirect_to cpanel_contract_show_path(contract.uid)
  end

  def cancel_request
    request = SiteRequest.where(:uid => params[:request_uid]).first rescue nil
    request.destroy if !request.nil?
    redirect_to cpanel_myhistory_path(:page => params[:page])
  end

  def contracts
    if !params[:query].present?
      @objects = SiteRequest.any_of({:site_id.in => current_cpanel_user.registered_site_ids.collect{|id| id.to_s}, :request_contract.ne => nil},{:c_panel_user_id => current_cpanel_user.id, :request_contract.ne => nil}).desc(:created_at).page(params[:page]).per(15)
    else
      @objects = SiteRequest.where(:site_id => params[:query], :request_contract.ne => nil).desc(:created_at).page(params[:page]).per(15)
    end
    if request.xhr?
      render :partial => "contract_partial"
    else
      @user_sites = current_cpanel_user.registered_sites.collect{|rs|[rs.title, rs.id.to_s]}
      @user_sites << ["New site request", "newsite"] 
    end
  end

  def purchases
    if !params[:query].present?
      site_requests =  SiteRequest.any_of({:site_id.in => current_cpanel_user.registered_site_ids.collect{|id| id.to_s}, :request_contract.ne => nil},{:c_panel_user_id => current_cpanel_user.id, :request_contract.ne => nil}).asc(:created_at)
      @purchases = site_requests.collect{|sr| sr.request_contract.contract_purchase if sr.request_contract.contract_purchase != nil}
      @purchases.delete(nil)
      @purchases = Kaminari.paginate_array(@purchases).page(params[:page]).per(15)
    else
      site_requests = SiteRequest.where(:site_id => params[:query], :request_contract.ne => nil).asc(:created_at)
      @purchases = site_requests.collect{|sr| sr.request_contract.contract_purchase if sr.request_contract.contract_purchase != nil}
      @purchases.delete(nil)
      @purchases = Kaminari.paginate_array(@purchases).page(params[:page]).per(15)
    end
    if request.xhr?
      render :partial => "purchase_partial"
    else
      @user_sites = current_cpanel_user.registered_sites.collect{|rs|[rs.title, rs.id.to_s]}
      @user_sites << ["New site request", "newsite"] 
    end
  end

  def confirm_contract
    contract = RequestContract.where(:uid => params[:contract_uid]).first rescue nil
    contract.confirmed = true
    contract.save
    if params[:ref] == "contract_page"
      redirect_to cpanel_contract_show_path(contract.uid)
    else
      redirect_to cpanel_mycontracts_path(:page => params[:page])
    end
  end

  private

  def is_site_authorized_to_user?
    @site_construct = RegisteredSite.where(:uid => params[:site_uid]).first
    if !current_cpanel_user.registered_site_ids.include?(@site_construct.id)
      redirect_to sites_path
    end
  end

  def is_ticket_authorized_to_user?
    @ticket = Ticket.find(params[:ticket_id]) rescue nil
    if @ticket.nil? || !current_cpanel_user.registered_site_ids.include?(@ticket.registered_site.id)
      if request.xhr?
        render :json => {"success" => false}.to_json and return
      else
        redirect_to sites_path
      end
    else
      @site_construct = @ticket.registered_site
    end
  end

  def ticket_params
    params.require(:ticket).permit!
  end

  def tq_params
    params.require(:ticket_query).permit!
  end

  def update_member_profile_params
    params.require(:c_panel_user).permit!
  end

  def rs_params
    params.require(:site_request).permit!
  end

  def contract_params
    params.require(:request_contract).permit!
  end

end