class Admin::OffersController < ApplicationController
  layout "admin"
  before_filter :auth_admin

  def index

    # filters default value
    params[:o] ||= 'created-desc'
    params[:r] ||= 10

    if params[:need_id]
      @need = Need.find(params[:need_id])
      @offers = @need.offers
    else
      @offers = Offer.all
    end

    if(params[:q] and params[:q] != '')
      @offers = @offers.joins(:need).where("needs.title like ? or offers.supplier like ?" ,"%#{params[:q]}%","%#{params[:q]}%")
    end

    case params[:o]
    when 'created-asc'
      @offers = @offers.order(created_at: :asc)
    when 'created-desc'
      @offers = @offers.order(created_at: :desc)
    when 'alpha-asc'
      @offers = @offers.order(supplier: :asc)
    when 'alpha-desc'
      @offers = @offers.order(supplier: :desc)
    when 'price-asc'
      @offers = @offers.order(price: :asc)
    when 'price-desc'
      @offers = @offers.order(price: :desc)
    when 'need-alpha-asc'
      @offers = @offers.joins(:need).order('needs.title asc')
    when 'need-alpha-desc'
      @offers = @offers.joins(:need).order('needs.title desc')
    end

    @orders = {
      "Les plus récentes" => 'alpha-asc',
      "Fournisseurs (de A à Z)" => 'alpha-asc',
      "Fournisseurs (de Z à A)" => 'alpha-desc',
      "Besoin (de A à Z)" => 'need-alpha-asc',
      "Besoin (de Z à A)" => 'need-alpha-desc',
      "Prix négociés croissants" => 'price-asc',
      "Prix négociés décroissants" => 'price-desc'
    }


    @offers = @offers.page(params[:page]).per(params[:r])



  end

  def new
    @need = Need.find(params[:need_id])
    @offer = Offer.new
  end

  def create
    @need = Need.find(params[:need_id])
    @offer = Offer.new(offer_params)
    if @offer.save
      @need.offers << @offer
      flash[:notice] = "Offre créée avec succès."
      @offer.validate!
      redirect_to admin_need_offers_path(@need)
    else
      render :action => "new"
    end
  end

  def edit
    @offer = Offer.find(params[:id])
    if params[:need_id]
      @need = Need.find(params[:need_id])
    end
  end

  def update
    @offer = Offer.find(params[:id])
    if @offer.update_attributes(offer_params)
      flash[:notice] = "Offre modifiée avec succès."
      if params[:need_id]
        @need = Need.find(params[:need_id])
        redirect_to admin_need_offers_path(@need)
      else
        redirect_to admin_offers_path
      end
    else
      render :action => "edit"
    end
  end

  def destroy
    @offer = Offer.find(params[:id])

    if(@offer.destroy)
      flash[:notice] = "Offre supprimée avec succès."
    else
      flash[:error] = "Impossible de supprimer cette offre"
    end

    if params[:need_id]
      @need = Need.find(params[:need_id])
      redirect_to admin_need_offers_path(@need)
    else
      redirect_to admin_offers_path
    end

  end


  def accepted
    @offer = Offer.find(params[:id])
  end

  def download_zip

    require 'zip'

    @offer = Offer.find(params[:id])



    zipfile_name =  "#{Rails.root}/private_medias/zip/tmp_zip.zip"
    csvfile_name =  "#{Rails.root}/private_medias/zip/tmp_csv.csv"

    File.delete(zipfile_name) if File.exist?(zipfile_name)
    File.delete(csvfile_name) if File.exist?(csvfile_name)

    Zip::File.open(zipfile_name, Zip::File::CREATE) do |zipfile|

      @offer.accepted_offers.each do |accepted_offer|

        customer_name = "#{accepted_offer.customer.organisation} (#{accepted_offer.customer.firstname} #{accepted_offer.customer.name})"

        accepted_offer.documents.each do |document|

          document_name = document.title


          if document.document.file
            if document.particulars?
              zipfile.add("#{customer_name}/#{document_name}/#{document.title}-NÉGOS.pdf", document.get_particularized_document_file_path)
            else
              zipfile.add("#{customer_name}/#{document_name}/#{document.title}-NÉGOS.pdf", document.document.current_path)
            end
          end

          if document.returned_document.file
            zipfile.add("#{customer_name}/#{document_name}/#{document.title}-RETOURNÉ.pdf", document.returned_document.current_path)
          end
        end

      end

      CSV.open(csvfile_name, "wb",headers: true, :col_sep => ";" ) do |csv|
        csv << ["Société", "prénom", "nom", "Téléphone","Email","Offres acceptée?", "Acceptée le", "Intéressé le"].map{|row| row.encode("iso-8859-1")}
        @offer.need.wishes.each do |wish|
          accepted_offer = @offer.accepted_offers.where(customer_id: wish.customer.id).first
          if accepted_offer
            accepted = true
          else
            accepted = false
          end
          csv << [
            wish.customer.organisation ? wish.customer.organisation : "Aucune",
            wish.customer.firstname,
            wish.customer.name,
            wish.customer.phone,
            wish.customer.email,
            accepted ? "Oui" : "Non",
            accepted ? accepted_offer.updated_at.to_s : "",
            wish.updated_at.to_s
          ].map{|row| row.encode("iso-8859-1")}
        end


      end

      zipfile.add("Utilisateurs intéressés.csv", csvfile_name)

    end



    filename = "[Besoin:#{@offer.need.title}][Offre:#{@offer.supplier}] Export des documents fait le #{DateTime.now.to_time.strftime('%d/%m/%y')}.zip"

    send_file(zipfile_name, :filename => filename)
    #File.delete(zipfile_name)

  end

  def upload_documents
    @offer = Offer.find(params[:id])

    if request.post?

      counter = 0
      @offer.accepted_offers.each do |accepted_offer|
        document = Document.new
        document.title = params[:document][:title]
        document.document = params[:document][:document]
        document.accepted_offer = accepted_offer

        if params[:document][:document]
          document.state = "document_available"
        end

        document.save
        CustomerMailer.document_available(accepted_offer.customer, document).deliver
        counter = counter + 1
      end

      flash[:notice] = "#{counter} document(s) créé(s)"
      redirect_to accepted_admin_offer_path(@offer)
    end

  end





  private

  def offer_params
    params.require(:offer).permit! #(:supplier, :price, :fee_percentage, :reseaux_ids, :gain)
  end

end
