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

class Public::POrdersController < ApplicationController
  layout "public"
  
  before_filter :p_customer_validated
  
  def cart
    
    @p_customer_sheet = current_p_customer_sheet
    
    
  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
    @p_customer_sheet = current_p_customer_sheet
    
  end
  
  
  def particulars_save
    @p_customer_sheet = current_p_customer_sheet
    @p_customer_sheet.validate_particulars = true
    
    
    
    if @p_customer_sheet.update_attributes(params.require(:p_customer_sheet).permit!)
      @p_customer_sheet.validate_particulars = true
      @p_customer_sheet.particular_bill.force_validation =true
      @p_customer_sheet.particular_send.force_validation=true
      if @p_customer_sheet.particular_bill.save and @p_customer_sheet.particular_send.save
        
        redirect_to recap_public_p_orders_path()
      else
        @p_customer_sheet.particular_send.save
        render action: "particulars" 
      end
       
       
    else
     render action: "particulars" 
      
    end
    
  end
  
  def recap
    @p_customer_sheet = current_p_customer_sheet
    
  end
  
  def recap_save
    @p_customer_sheet = current_p_customer_sheet
    
    @p_customer_sheet.validate_cgv = true
    @p_customer_sheet.validate_payment_type = true
    
    @p_customer_sheet.validate_particulars = true
    @p_customer_sheet.particular_bill.force_validation =true
    @p_customer_sheet.particular_send.force_validation=true
    @p_customer_sheet.ecom_status = "commande"
    
    @p_customer_sheet.customer_validation_at = Time.now
    
    if @p_customer_sheet.update_attributes(params.require(:p_customer_sheet).permit!) and @p_customer_sheet.particular_bill.save and @p_customer_sheet.particular_send.save

      @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 thank
    @p_customer_sheet = PCustomerSheet.find(params[:id])
    
  end
  
  
end
