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

class Admin::PriceDocumentsController < ApplicationController
  layout "admin"
  before_action :auth_admin, :except => [:print, :consult, :consult_create, :consult_edit, :consult_update]

  before_action :admin_space, :except => :print

  def generate_stocks
    @price_document = PriceDocument.find(params[:id])
    
    @price_document.price_line_block.generate_stock
    
    
    redirect_to [:admin, @price_document]
  end
  
  def update_stocks
    @price_document = PriceDocument.find(params[:id])
    
    if @price_document.price_line_block.update_stocks
      redirect_back(fallback_location: admin_price_documents_path)
    else
      redirect_back(fallback_location: admin_price_documents_path,:notice => "Le stock n'a pas pu être mis à jour, tous les articles ne sont pas présents")
    end
  end
  
  def unarchive_now
    @price_document = PriceDocument.find(params[:id])
    
    @price_document.unarchive_now
    
    redirect_to [:admin, @price_document]
  end
  
  def archive_now
    @price_document = PriceDocument.find(params[:id])
    
    @price_document.archive_now
 
    
    redirect_to [:admin, @price_document]
  end
  
  
  def admin_space
    if (params[:document_type] and (params[:document_type] == "Facture d'achat" or params[:document_type] == "Commande achat")) or [6,7].include?(params[:price_document_type_id].to_i) or (params[:price_document_type_ids] and (params[:price_document_type_ids].include?("6") or params[:price_document_type_ids].include?("7"))) or (params[:id] and d = PriceDocument.where(:id => params[:id]).first and [6,7].include?(d.price_document_type_id))
      @admin_space = "documents"
      
      qi_menu(:documents)
      
    else
      @admin_space = "ventes"
      
      qi_menu(:ventes)
      
    end
    
    @admin_space = "documents"
    
    qi_menu(:documents)
    
  end
  
  def search_to_affect
    @p_customer = PCustomer.where(:id => params[:p_customer_id]).first
  end
  
  def index
     
    if params[:price_document_type_id]
      params[:price_document_type_ids] = [params[:price_document_type_id]]
    else
      params[:price_document_type_ids] = params[:price_document_type_ids] || ["4", "7"]
    end
    
    if @p_customer
      @price_documents = @p_customer.price_documents
    else
      @price_documents = PriceDocument
    end
    #@price_documents = @price_documents.order("created_at DESC")
    
    
    if params[:search][:cc_solded].to_s == "Oui"
      @price_documents = @price_documents.where(:cc_solded => true)
    elsif params[:search][:cc_solded].to_s == "Non"
      @price_documents = @price_documents.where(:cc_solded => false)
    end
  
  
    if params[:search][:cost_ok].to_s == "Oui"
      @price_documents = @price_documents.where(:cost_ok => true)
    elsif params[:search][:cost_ok].to_s == "Non"
      @price_documents = @price_documents.where(:cost_ok => false)
    end
  
    
    
    if true
      @price_documents = @price_documents.where(:price_document_type_id => params[:price_document_type_ids]) if params[:price_document_type_ids].size > 0

     
      if current_admin.p_commercial
        @price_documents = @price_documents.where(:p_commercial_id => current_admin.p_commercial.id )
      
      else
        if params[:search][:p_commercial_id].to_s != ""
          if params[:search][:p_commercial_id].to_s == "null"
            @price_documents = @price_documents.where(:p_commercial_id => nil)
          else
            @price_documents = @price_documents.where(:p_commercial_id => params[:search][:p_commercial_id])
          end
        end
      
      
      
      end
    
      if params[:search][:p_payment_type_id].to_s != ""
        @price_documents = @price_documents.joins(:price_line_block).where(:price_line_blocks => {:p_payment_type_id => params[:search][:p_payment_type_id]})
      
      end
    
    
      if params[:search][:d_number].to_s != ""
        @price_documents = @price_documents.where("price_documents.d_number LIKE ?","%#{params[:search][:d_number]}%")
      end
    
      if params[:amount_min].to_s != ""
        @price_documents = @price_documents.where("price_documents.cc_tot_amount_ttc >= ?", params[:amount_min])
      end
    
      if params[:amount_max].to_s != ""
        @price_documents = @price_documents.where("price_documents.cc_tot_amount_ttc <= ?", params[:amount_max])
      end
    
    


      date_regex = /^(0[1-9]|[12][0-9]|3[01])[\/](0[1-9]|1[012])[\/](19|20)\d\d$/i 
    
    
      params[:start] = Date.today.beginning_of_month.strftime('%d/%m/%Y') if !params[:start]
    
      if params[:start] and params[:start] =~ date_regex
        #fsfds = sdfsfd
        @start = Date.parse(params[:start]).beginning_of_day 
        params[:start]= @start.strftime('%d/%m/%Y')
      else
        @start = nil
      end
    
      if true
        params[:stop] = Date.today.end_of_month.strftime('%d/%m/%Y') if !params[:stop]

    
        if params[:stop].to_s != "" # and params[:stop] =~ date_regex
          @stop = Date.parse(params[:stop]).end_of_day 
        
          params[:stop]= @stop.strftime('%d/%m/%Y')
        
        
        else
           @stop = nil
        end
    
      end
      
      if params[:search][:imported].to_s == "Oui"
        @price_documents = @price_documents.where(:imported => true)
      elsif params[:search][:imported].to_s == "Non"
        @price_documents = @price_documents.where(:imported => false)
      end
  
      
      if params[:start_cc_payment_end_at] and params[:start_cc_payment_end_at] =~ date_regex
        start_cc_payment_end_at = Date.parse(params[:start_cc_payment_end_at]).beginning_of_day 
        params[:start_cc_payment_end_at]= start_cc_payment_end_at.strftime('%d/%m/%Y')
        
        @price_documents = @price_documents.where("price_documents.cc_payment_end_at >= ?", start_cc_payment_end_at)
      end
  
    
  
      if params[:stop_cc_payment_end_at].to_s != "" # and params[:stop] =~ date_regex
        stop_cc_payment_end_at = Date.parse(params[:stop_cc_payment_end_at]).end_of_day 
        params[:stop_cc_payment_end_at]= stop_cc_payment_end_at.strftime('%d/%m/%Y')
      
        @price_documents = @price_documents.where("price_documents.cc_payment_end_at <= ?", stop_cc_payment_end_at)
      end
    
      
      
      
      
    
    
      @price_documents = @price_documents.where("price_documents.date >= ?", @start) if @start

      @price_documents = @price_documents.where("price_documents.date <= ?", @stop.end_of_day) if @stop
    
      @price_documents = @price_documents.distinct
    
    end
    params[:search][:per_page] = 100000 if params[:print]
    
    
    @price_documents = sort_by_sorting(@price_documents)
    
    respond_to do |format|
      format.html{
    
        params[:search][:per_page] = params[:search][:per_page] || 50
    		per_page = params[:search][:per_page]
    		page = (params[:page] and params[:page] != "") ? params[:page] : 1 
    		@price_documents = @price_documents.page(page).per(per_page)
    
      }
    end
    

  end

  def show
    @price_document = PriceDocument.find(params[:id])

  end

  def new
    if params[:document_type]
      
      @price_document = PriceDocument.new(:p_customer_id => params[:p_customer_id], :p_fournisseur_id => params[:p_fournisseur_id])
      @price_document.price_document_type = PriceDocumentType.where(:label => params[:document_type]).first
      @price_document.price_line_block = PriceLineBlock.new(:p_customer_id => params[:p_customer_id], :p_fournisseur_id => params[:p_fournisseur_id])
      
      if @price_document.price_document_type.label == "Demande prix"
        p_product_ref_id = params[:qte].keys
        p_product_ref_qte = params[:qte].values

        p_product_ref_id.each_with_index do |key, i|
          @price_document.price_line_block.price_lines << PriceLine.new(:p_product_ref_id => key, :qte => p_product_ref_qte[i])
        end

        # @ref_price_lines = PriceLine.where(:id => params[:price_line_ids])
        # @ref_price_lines.group(:p_product_ref_id).each do |plr|
        #   @price_document.price_line_block.price_lines << PriceLine.new(:p_product_ref_id => plr.p_product_ref_id, :qte => @ref_price_lines.where(:p_product_ref_id => plr.p_product_ref_id).sum(:qte))
        # end
      
      end
      
      
    else
      @price_document = PriceDocument.new(:p_customer_id => params[:p_customer_id])
      @price_document.price_line_block = PriceLineBlock.new(:p_customer_id => params[:p_customer_id])
    
      if params[:action_type].to_s == "Avoir"
        @avoir = true
        @price_document.price_document_type = PriceDocumentType.where(:label => "Avoir").first
        @price_document.price_line_block.ct_tot_fdp_ht = 0.0
      else
        @price_document.price_document_type = PriceDocumentType.where(:label => "Facture").first
      end
    end
  
  end
  
  
  def consult
    @consult = true
    
    @demande = PriceDocument.where(:f_token => params[:id]).first
    
    @price_document = PriceDocument.new(:p_customer_id => params[:p_customer_id], :p_fournisseur_id => params[:p_fournisseur_id])
    @price_document.price_document_type = PriceDocumentType.where(:label => "Réponse fournisseur").first
    @price_document.price_line_block = PriceLineBlock.new(:p_customer_id => params[:p_customer_id], :p_fournisseur_id => params[:p_fournisseur_id])
    @price_document.doc_ref_id = @demande.id
  
    @ref_price_lines = @demande.price_line_block.price_lines
    
    @ref_price_lines.group(:p_product_ref_id).each do |plr|
      @price_document.price_line_block.price_lines << PriceLine.new(:p_product_ref_id => plr.p_product_ref_id, :qte => @ref_price_lines.where(:p_product_ref_id => plr.p_product_ref_id).sum(:qte))
    end
  
  
  end
  
  
  def consult_create
    @consult = true
    
    @price_document = PriceDocument.new(params.require(:price_document).permit!)
    @price_document.date = Date.today
    if @price_document.save
      redirect_to consult_edit_admin_price_document_path(:id => @price_document.token)
    else
      render action: "consult"
 
    end

  end
  
  
  def consult_edit
    @consult = true
    
    @price_document = PriceDocument.where(:token => params[:id]).first
  end
  

  def edit
    @price_document = PriceDocument.find(params[:id])
    
    @avoir = true if @price_document.label == "Avoir"
    
  end

  def create
    @price_document = PriceDocument.new(params.require(:price_document).permit!)
    @price_document.date = Date.today
    @avoir = true if @price_document.label == "Avoir"
    if @price_document.save
      redirect_to admin_price_documents_path(:price_document_type_id => @price_document.price_document_type_id)
    else
      render action: "new"
 
    end

  end


  def update
    @price_document = PriceDocument.find(params[:id])

    @avoir = true if @price_document.label == "Avoir"
    if @price_document.update_attributes(params.require(:price_document).permit!)
      
      if params[:public_edit].to_s == "true"
        
        @price_document.reset_for_update
        
        #@price_document.unarchive_now
        #@price_document.archive_now
        if @price_document.ref_element
          redirect_to [:admin, @price_document.ref_element]
        else
          redirect_to [:admin, @price_document]
        end
      else
        redirect_to [:admin, @price_document]
      end
      
    else
     render action: "edit" 
      
    end
      
  end


  def destroy
    @price_document = PriceDocument.find(params[:id])
    @price_document.destroy
    
  end
  
  def edit_ship
    @price_document = PriceDocument.find(params[:id])
  end
  
  def edit_ship_save
    @price_document = PriceDocument.find(params[:id])

  
    if @price_document.update_attributes(params.require(:price_document).permit!)
      
   
      redirect_to [:admin, @price_document.ref_element]

    else
     render action: "edit_ship" 
      
    end
  end
  
  def edit_lettrage
    @price_document = PriceDocument.find(params[:id])
  end
  
  def edit_lettrage_save
    @price_document = PriceDocument.find(params[:id])

  
    if @price_document.update_attributes(params.require(:price_document).permit!)
      
      @price_document.save
      redirect_to [:admin, @price_document]

    else
     render action: "edit_lettrage" 
      
    end
  end
  
  
  def print
    
  

    @price_document = PriceDocument.find_by_token(params[:id])
    @element = @price_document.ref_element
    
    doc_number = @price_document.d_number
    url = print_admin_price_document_path(:id => @price_document.token, :html => true)
  
  
  
    
    params[:inline] = true
    
    if !params[:html] # and !Rails.env.development?
      
      @data_to_send = File.open(@price_document.generate_pdf).read
      
      
      
      
      
      send_data @data_to_send, :filename =>"#{doc_number}.pdf" , :type => 'application/pdf',:disposition => (params[:inline] ? 'inline' : "attachment")
      #render :inline => "y"
    
    else
      render :layout => false
    end
    
  end
  
  
  
  def create_avoir
    @past_price_document = PriceDocument.find(params[:id])
    @price_document = @past_price_document.create_avoir
    @avoir = true
    render :layout => "admin"
    
    
  end
  

  def save_avoir
    @price_document = PriceDocument.new(params.require(:price_document).permit!)

    @avoir = true
    @price_document.price_document_type = PriceDocumentType.find_by_label("Avoir")
    
    @price_document.date = Date.today

    #@price_document.ref_element_type = self.ref_element_type,
    #@price_document.ref_element_id = self.ref_element_id
    
    


    if @price_document.save
      @price_document.archive_now
      redirect_to admin_p_customer_sheet_path(@price_document.ref_element)
    else
      render action: "create_avoir", :layout => "admin"

    end

  end
  
  
  def bill
    @past_price_document = PriceDocument.find(params[:id])
    
    @p_customer_sheet = @past_price_document.ref_element
    
    
    if @p_customer_sheet
      price_document = @p_customer_sheet.price_documents.new(:price_document_type => PriceDocumentType.find_by_label("Facture"), :bon_de_commande_id => @past_price_document.bon_de_commande_id, :bon_de_livraison_id => @past_price_document.id, :date => Date.today)
      price_document.p_customer = @past_price_document.p_customer
    
      price_document.price_line_block = @past_price_document.price_line_block.dup
  
      price_document.price_line_block.ac_bon_de_commande_id = nil
      price_document.price_line_block.ac_bon_de_livraison_id = nil
      price_document.price_line_block.ac_facture_id = nil
      price_document.price_line_block.ac_block_type = nil
     
      
      @past_price_document.price_line_block.price_lines.each do |pl|
        new_pl = pl.dup
  
        new_pl.ac_block_type = nil
 
        price_document.price_line_block.price_lines << new_pl
      end
    
      if price_document.save
      
        price_document.archive_now
        @p_customer_sheet.state = "facturée"
        @p_customer_sheet.save
        
        ## blocage temporaire de génération auto des stocks
        #price_document.price_line_block.update_stocks
      
        redirect_to admin_p_customer_sheet_path(price_document.ref_element)
      end
      
    end
    
    
    
  end
  
  
  def bl
    @past_price_document = PriceDocument.find(params[:id])
    
    @p_customer_sheet = @past_price_document.ref_element
    
    
    if @p_customer_sheet
      price_document = @p_customer_sheet.price_documents.new(:price_document_type => PriceDocumentType.find_by_label("Bon de livraison"), :bon_de_commande_id => @past_price_document.id, :date => Date.today)
      price_document.p_customer = @past_price_document.p_customer
    
      price_document.reliquat = true if @p_customer_sheet and @p_customer_sheet.price_documents.where(:cc_label => "Bon de livraison", :cancelled => false).count > 0
    
      price_document.price_line_block = @past_price_document.price_line_block.dup
      
      price_document.price_line_block.ac_bon_de_commande_id = nil
      price_document.price_line_block.ac_bon_de_livraison_id = nil
      price_document.price_line_block.ac_facture_id = nil
      price_document.price_line_block.ac_block_type = nil
      price_document.price_line_block.ac_reliquat = nil
      
      
      
      price_document.price_line_block.bk_tot_fdp_ht = price_document.price_line_block.cc_tot_fdp_ht
      
      
  
      @past_price_document.price_line_block.price_lines.each do |pl|
        new_pl = pl.dup
        new_pl.price_line_ref_id = pl.id
        new_pl.ac_block_type = nil
        
        if price_document.reliquat
          bls = @p_customer_sheet.price_documents.where(:cc_label => "Bon de livraison", :cancelled => false)
          
          qte_ok =  PriceLine.where(:price_line_ref_id => new_pl.price_line_ref_id).where(:price_line_block_id => PriceLineBlock.where(:price_lineable_type => "PriceDocument", :price_lineable_id => bls.ids)).sum(:qte)
          
          new_pl.qte = new_pl.qte - qte_ok
          
        end
        price_document.price_line_block.price_lines << new_pl
      end
    
      if price_document.save
        price_document.reset_for_update
        price_document.archive_now
        @p_customer_sheet.state = "en livraison"
        @p_customer_sheet.save
      
        redirect_to admin_p_customer_sheet_path(price_document.ref_element)
        
      else 
        render :inline => price_document.errors.messages.to_s
      end
      
    end
    
    
    
  end
  
  def cancel_now
    @price_document = PriceDocument.find(params[:id])
    
    @price_document.cancel_now
    
    redirect_back(fallback_location: admin_p_customer_sheets_path)
    
  end
  
  def generate_stat_lines
    @price_document = PriceDocument.find(params[:id])
    
    @price_document.generate_stat_lines
    
    redirect_back(fallback_location: admin_p_customer_sheets_path)
    
  end
  
  def match_p_fournisseur
    @price_document = PriceDocument.find(params[:id])
  end

  def analyse_reponses
    @price_document = PriceDocument.find(params[:id])
    @price_document_responses = PriceDocument.where(:doc_ref_id => @price_document.id )

  end
end
