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

class Admin::PShipTourTrucksController < ApplicationController
  layout "admin"
  before_action :auth_admin

  
  def urg_ship
    @p_customer_sheet = PCustomerSheet.find(params[:p_customer_sheet_id])
    @p_sheet_line = PSheetLine.find(params[:p_sheet_line_id])
    @p_ship_tour_truck = PShipTourTruck.find(params[:id])
    
    if @p_sheet_line.p_product.p_product_cat_id == 6 and !@p_sheet_line.externe and !@p_sheet_line.bl
      @p_ship_tour_truck_sheet_line = PShipTourTruckSheetLine.new(:p_sheet_line_id => @p_sheet_line.id)
      @p_ship_tour_truck.p_ship_tour_truck_sheet_lines << @p_ship_tour_truck_sheet_line
    
      @p_ship_tour_truck_sheet_line.p_sheet_line.to_ship(@p_ship_tour_truck)
      
      redirect_to [:admin, @p_customer_sheet]
    else
      render :inline => "Ligne déjà attribuée"
    end
    
  end
  

  def update_ship_tour_truck_sheet_lines
    @p_ship_tour_truck = PShipTourTruck.find(params[:id])
    
    @p_ship_tour_truck.p_ship_tour_truck_sheet_lines.destroy_all

    i = 0
    params[:sheet_line_ids].to_a.each do |sheet_line_id|
      @p_ship_tour_truck.p_ship_tour_truck_sheet_lines << PShipTourTruckSheetLine.new(:p_sheet_line_id => sheet_line_id.to_i, :position => i)
      i += 1
    end
    render :inline => "ok", :layout => false
  end



  def edit
    @p_ship_tour_truck = PShipTourTruck.find(params[:id])
    
  end
  
  def update
    @p_ship_tour_truck = PShipTourTruck.find(params[:id])
   
    if @p_ship_tour_truck.p_ship_tour.state != "livrée"
      @p_ship_tour_truck.assign_attributes(:tracteur_id => params[:p_ship_tour_truck][:tracteur_id],:p_driver_id => params[:p_ship_tour_truck][:p_driver_id])
    else
      @p_ship_tour_truck.assign_attributes(:p_driver_id => params[:p_ship_tour_truck][:p_driver_id])
    end
    
    @p_ship_tour_truck.set_remorques
    if @p_ship_tour_truck.save(validate: false)
      redirect_to [:admin, @p_ship_tour_truck.p_ship_tour]
    else
     render action: "edit" 
      
    end
  end
  
  

 
end
