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

class Public::POrdersController < ApplicationController
  layout "public"

  before_action :identify_cart_process

  before_action :p_customer_validated, :except => [:cart, :ipn]

  before_action :set_menu

  # before_action :update_locales

  # helper :'paiement_cic/form'

  skip_before_action :verify_authenticity_token, only: [:ipn]

  # before_action :get_colissimo_token, only: [:particulars, :particulars_save]

  def set_menu
    @boutique = true
  end

  def identify_cart_process
    @for_order = true
  end

  def cart


    @boutique_step = 1
    
    
    #@current_p_customer_sheet.price_line_block.ct_creation_date = Time.now
    
    @current_p_customer_sheet.save
    
    @p_customer_sheet = @current_p_customer_sheet
    
    
    
    
    # @p_customer_sheet.purge_cart
  end

  def chronopost_places
    @cp = params[:cp]
  end

  def update_cart
    @p_customer_sheet = @current_p_customer_sheet


    if @p_customer_sheet.update_attributes(params.require(:p_customer_sheet).permit!)

       respond_to do |format|
         format.html { redirect_to cart_public_p_orders_path()}
         format.js { render :layout => false }
       end


    else
     render action: "cart"

    end
  end

  def particulars

    @boutique_step = 3
    @p_customer_sheet = @current_p_customer_sheet
    # @p_customer_sheet.purge_cart
    if session[:p_id]
      @p_customer_sheet.price_line_block.particular_send_id = session[:p_id]
      @p_customer_sheet.price_line_block.particular_bill_id = session[:p_id]
      session[:p_id] = nil
    elsif !@p_customer_sheet.price_line_block.particular_send and pa = current_p_customer.particulars.first()
      @p_customer_sheet.price_line_block.particular_send = pa
    end

    if current_p_customer.particulars.count == 0
      redirect_to new_public_particular_path(:for_order => true)
    end

  end


  def particulars_save

    @boutique_step = 3
    @p_customer_sheet = @current_p_customer_sheet

    # @p_customer_sheet.purge_cart

    # @p_customer_sheet.price_line_block.particulars_neededs = true



    if @p_customer_sheet.update_attributes(params.require(:p_customer_sheet).permit!)

      if @p_customer_sheet.price_line_block.valid?

        redirect_to recap_public_p_orders_path()
      end



    else
     render action: "particulars"

    end

  end

  def recap
    @p_customer_sheet = @current_p_customer_sheet

    # @p_customer_sheet.purge_cart


    # if @p_customer_sheet.price_line_block.p_vourcher and @p_customer_sheet.price_line_block.p_vourcher.used
    #   @p_customer_sheet.price_line_block.p_vourcher = nil
    #   @p_customer_sheet.save
    # end

    # if params[:code]

    #   if p_vourcher = PVourcher.where(:token => params[:code].strip.upcase).where("used is null or used = 0").first
    #     @p_customer_sheet.price_line_block.p_vourcher = p_vourcher
    #     @p_customer_sheet.save
    #   else
    #     @bon_error = true
    #   end

    # end


    @p_customer_sheet.p_payment_type_id = 1 if !@p_customer_sheet.p_payment_type
    @boutique_step = 4




  end

  def recap_save

    @boutique_step = 4

    @p_customer_sheet = @current_p_customer_sheet
    @p_customer_sheet.web_order = true
    @p_customer_sheet.demande_type = "Demande de bon de commande"
    @p_customer_sheet.state = 'brouillon'

    # @p_customer_sheet.purge_cart

    # if @p_customer_sheet.price_line_block.p_shipper and @p_customer_sheet.price_line_block.p_shipper.with_custom_date
    #   @p_customer_sheet.price_line_block.wish_date = @p_customer_sheet.price_line_block.ship_custom_date

    # else
    #   @p_customer_sheet.price_line_block.wish_date = nil
    # end
    @p_customer_sheet.save



    # @p_customer_sheet.validate_cgv = true
    # @p_customer_sheet.validate_payment_type = true





    if @p_customer_sheet.update_attributes(params.require(:p_customer_sheet).permit!)

      #@p_customer_sheet.generate_bc
      #@p_customer_sheet.generate_fa if @p_customer_sheet.acompte_percent?

      #AdminMailer.notify_order().deliver

      cookies[:current_p_customer_sheet_id] = nil

      redirect_to thank_public_p_order_path(:id => @p_customer_sheet.id)




    else
      render :action => "recap"


    end



  end

  def paid_by_cb
    @boutique_step = 4

    @p_customer_sheet = @current_p_customer_sheet

    # @p_customer_sheet.purge_cart

    @p_customer_sheet.token = rand(1000000) if !@p_customer_sheet.token?
    @p_customer_sheet.save
  end


  def ipn

    puts params

    @p_customer_sheet = PCustomerSheet.find_by_token params[:reference].to_s[0..21]


    if PaiementCic.verify_hmac(params)


      code_retour = params['code-retour']

      if code_retour == "Annulation"

        @p_customer_sheet.update_attribute :ogone_status, "Paiement refusé par la banque."

      elsif code_retour == "payetest"

        @p_customer_sheet.update_attribute :ogone_status, "TEST accepté par la banque."

        paid = true
      elsif code_retour == "paiement"

        @p_customer_sheet.update_attribute :ogone_status, "Paiement accepté par la banque."


        paid = true
      end



      receipt = "0"

    else

      @p_customer_sheet.update_attribute :ogone_status, "Document Falsifie."

      receipt = "1\n#{PaiementCic.mac_string}"

    end



    @p_customer_sheet.save

    if paid
      @p_customer_sheet.state = "Réglée"

      @p_customer_sheet.customer_validation_at = Time.now

      @p_customer_sheet.paid = true
      @p_customer_sheet.paid_at = Time.now

      @p_customer_sheet.save

      @p_customer_sheet.archive_now

      @p_customer_sheet.price_line_block.generate_vourchers

      @recap = ApplicationController.renderer.render partial: "public/p_customer_sheets/mail_recap.html.haml", :locals => {:@p_customer_sheet => @p_customer_sheet}
      mail_hist = MailHist.generate_mail(@p_customer_sheet.p_customer.locale, MailType.find_or_create("confirmation-commande"), @p_customer_sheet.p_customer.email, {:arguments => {:recap_commande => @recap, :recap_ba => @p_customer_sheet.ba_for_mails}, :p_customer_sheet => @p_customer_sheet, :p_customer => @p_customer_sheet.p_customer, :element => @p_customer_sheet})

      if p_vourcher = @p_customer_sheet.price_line_block.p_vourcher
        p_vourcher.used = true
        p_vourcher.save
      end


    end


    render :inline => "Pragma: no-cache\nContent-type: text/plain\n\nversion=2\ncdr=#{receipt}"

  end

  def paid_by_cb_confirm




    @p_customer_sheet = @current_p_customer_sheet

    if false

      @p_customer_sheet.state = "Réglée"

      @p_customer_sheet.customer_validation_at = Time.now

      @p_customer_sheet.paid = true
      @p_customer_sheet.paid_at = Time.now

      @p_customer_sheet.save

      #@recap = ApplicationController.renderer.render partial: "public/p_customer_sheets/mail_recap.html.haml", :locals => {:@p_customer_sheet => @p_customer_sheet}
      #mail_hist = MailHist.generate_mail(@p_customer_sheet.p_customer.locale, MailType.find_or_create("confirmation-commande"), @p_customer_sheet.p_customer.email, {:arguments => {:recap_commande => @recap}, :p_customer_sheet => @p_customer_sheet, :p_customer => @p_customer_sheet.p_customer, :element => @p_customer_sheet})

    end


    cookies[:current_p_customer_sheet_id] = nil





    redirect_to thank_public_p_order_path(:id => @p_customer_sheet.id)



  end

  def paid_by_cb_fail
    redirect_to recap_public_p_orders_path(), :notice => "Votre paiement n'a pas été accepté, vous pouvez réessayer en cliquant de nouveau sur \"Payer ma commande\""
  end


  def thank


    @p_customer_sheet = PCustomerSheet.find(params[:id])


  end

  def particulars_save

    @boutique_step = 3
    @p_customer_sheet = @current_p_customer_sheet

    # @p_customer_sheet.purge_cart

    # @p_customer_sheet.price_line_block.particulars_neededs = true



    if @p_customer_sheet.update_attributes(params.require(:p_customer_sheet).permit!)

      if @p_customer_sheet.price_line_block.valid?

        redirect_to recap_public_p_orders_path()
      end



    else
     render action: "particulars"

    end

  end

  private

  # def get_colissimo_token
  #   url = 'https://ws.colissimo.fr/widget-point-retrait/rest/authenticate.rest'
  #   headers = { "Content-Type": "application/json" }
  #   body = { "login": "877966", "password": "choco38" }
  #   response =  HTTParty.post(url, body: body, headers: headers)
  #   @colissimo_token = JSON.parse(response.body)["token"]
  # end
end
