#The MIT License (MIT)
#
#Copyright (c) 2016 - 2026 rick barrette
#
#Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
#
#The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
#
#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

class CustomersController < ApplicationController

  include AuthHelper
  helper :issues
  helper :journals
  helper :projects
  helper :custom_fields
  helper :issue_relations
  helper :watchers
  helper :attachments
  helper :queries
  include QueriesHelper
  helper :repositories
  helper :sort
  include SortHelper
  helper :timelog

  before_action :add_customer, only: [:new, :create]
  before_action :view_customer, except: [:new, :create, :view]
  skip_before_action :verify_authenticity_token, :check_if_login_required, only: [:view]

  def address_to_s(address)
    return if address.nil?

    lines = [
      address.line1,
      address.line2,
      address.line3,
      address.line4,
      address.line5
    ].compact_blank

    city_line = [
      address.city,
      address.country_sub_division_code,
      address.postal_code
    ].compact_blank.join(" ")

    lines << city_line unless city_line.blank?

    lines.join("\n")
  end

  def add_customer
    global_check_permission(:add_customers)
  end

  def allowed_params
    params.require(:customer).permit(:name, :email, :primary_phone, :mobile_phone, :phone_number, :notes)
  end

  # Used for autocomplete form
  def autocomplete
    # Support both existing 'q' param and new 'name'/'phone' params
    name_query = (params[:name] || params[:q] || params[:term]).to_s.strip
    phone_query = params[:phone].to_s.gsub(/\D/, '')

    sql_matches = []

    # 1. Check for phone number matches via SQL
    if phone_query.present?
      sql_matches += Customer.where("phone_number LIKE :p OR mobile_phone_number LIKE :p", p: "%#{phone_query}%")
    end

    # 2. Check for exact or partial name matches via SQL
    if name_query.present?
      safe_name = ActiveRecord::Base.sanitize_sql_like(name_query)
      sql_matches += Customer.where("name LIKE :t", t: "%#{safe_name}%")
    end

    sql_matches = sql_matches.uniq

    # 3. Handle spelling errors using built-in string distance
    fuzzy_matches = []
    if name_query.present?
      require 'did_you_mean/jaro_winkler'
      
      # Only scan records we haven't already matched
      unmatched = Customer.all - sql_matches
      
      fuzzy_matches = unmatched.select do |c|
        # 0.6 is the threshold. 1.0 is an exact match.
        DidYouMean::JaroWinkler.distance(c.name.to_s.downcase, name_query.downcase) > 0.6
      end
    end

    # Combine results and limit to top 20
    items = (sql_matches + fuzzy_matches).first(20)

    # Return JSON formatted for both existing usage and new jQuery UI requirements
    render json: items.map { |i|
      { id: i.id, name: i.name, phone_number: i.phone_number, mobile_phone_number: i.mobile_phone_number }
    }
  end

  def create
    @customer = Customer.new(allowed_params)

    respond_to do |format|
      if @customer.save
        log "Customer ##{@customer.id} created successfully."
        format.html { redirect_to @customer, notice: l(:notice_successful_create) }
        format.json { render json: { id: @customer.id, name: @customer.name }, status: :created }
      else
        format.html { render :new }
        format.json { render json: { errors: @customer.errors.full_messages }, status: :unprocessable_entity }
      end
    end
  rescue => e
    log "Failed to create customer: #{e.message}"
    respond_to do |format|
      format.html {
        flash[:error] = e.message
        redirect_to new_customer_path
      }
      format.json {
        render json: { errors: [e.message] }, status: :internal_server_error
      }
    end
  end

  def edit
    @customer = Customer.find_by_id(params[:id])
    return render_404 unless @customer
  rescue => e
    log "Failed to edit customer"
    flash[:error] = e.message
    render_404
  end

  def filter_estimates_by_customer
    @filtered_estimates = Estimate.all.where(customer_id: params[:selected_customer])
  end

  def filter_invoices_by_customer
    @filtered_invoices = Invoice.all.where(customer_id: params[:selected_customer])
  end

  def index
    if params[:search]
      @customers = Customer.search(params[:search]).order(:name).paginate(page: params[:page])
      if only_one_non_zero?(@customers)
        redirect_to @customers.first
      end
    end
  end

  def load_issue_data
    @journals = @issue.journals.preload(:details).preload(user: :email_address).reorder(:created_on, :id).to_a

    @journals.each_with_index { |j, i| j.indice = i + 1 }
    @journals.reject!(&:private_notes?) unless User.current.allowed_to?(:view_private_notes, @issue.project)
    Journal.preload_journals_details_custom_fields(@journals)
    @journals.select! { |journal| journal.notes? || journal.visible_details.any? }
    @journals.reverse! if User.current.wants_comments_in_reverse_order?

    @changesets = @issue.changesets.visible.preload(:repository, :user).to_a
    @changesets.reverse! if User.current.wants_comments_in_reverse_order?

    @relations = @issue.relations.select { |r| r.other_issue(@issue)&.visible? }
    @allowed_statuses = @issue.new_statuses_allowed_to(User.current)
    @priorities = IssuePriority.active
    @time_entry = TimeEntry.new(issue: @issue, project: @issue.project)
    @relation   = IssueRelation.new
  end

  def log(msg)
    Rails.logger.info "[CustomersController] #{msg}"
  end

  def new
    @customer = Customer.new
    
    if request.xhr?
      render partial: 'form', layout: false, locals: { hide_submit: true, hide_toolbar: true }
    end
  end

  def only_one_non_zero?(array)
    found_non_zero = false
    array.each do |val|
      if val != 0
        return false if found_non_zero
        found_non_zero = true
      end
    end
    found_non_zero
  end

  def share
    issue = Issue.find(params[:id])
    token = issue.share_token
    redirect_to view_path(token.token)
  rescue ActiveRecord::RecordNotFound
    flash[:error] = t(:notice_issue_not_found)
    render_404
  end

  def show
    @customer = Customer.find_by_id(params[:id])
    return render_404 unless @customer

    @open_issues = @customer.issues
      .joins(:status)
      .includes(:status, :project, :tracker, :priority)
      .where(issue_statuses: { is_closed: false })
      .order(id: :desc)

    @closed_issues = @customer.issues
      .joins(:status)
      .includes(:status, :project, :tracker, :priority)
      .where(issue_statuses: { is_closed: true })
      .order(id: :desc)

    @hours = TimeEntry
      .joins(:issue)
      .where(issues: { id: @open_issues.select(:id) })
      .sum(:hours)

    @closed_hours = TimeEntry
      .joins(:issue)
      .where(issues: { id: @closed_issues.select(:id) })
      .sum(:hours)

  rescue => e
    Rails.logger.error "Failed to load customer ##{params[:id]}: #{e.message}\n#{e.backtrace.join("\n")}"
    flash[:error] = e.message
    render_404
  end

  def sync
    Customer.sync
    redirect_to :home, flash: { notice: I18n.t(:label_syncing) }
  end

  def update
    @customer = Customer.find_by_id(params[:id])
    @customer.update(allowed_params)
    flash[:notice] = t :notice_customer_updated
    redirect_to @customer
  rescue => e
    log "Failed to update customer: #{e.message}"
    flash[:error] = e.message
    redirect_to edit_customer_path
  end

  def view
    User.current = User.anonymous
    @token = CustomerToken.active.find_by(token: params[:token])
    return render_403 unless @token
    @issue = @token.issue
    return render_403 unless @issue
    return render_403 unless @issue.customer_id == @token.issue.customer_id
    session[:token] = @token.token
    load_issue_data
  rescue ActiveRecord::RecordNotFound
    render_403
  end

  def view_customer
    global_check_permission(:view_customers)
  end

end