@extends('layouts.default')
@extends('content_wrappers.md-10')

@section('title', ' | Edit '.$recipe->name)
@section('heading', 'Edit Recipe: '.$recipe->name)

@section('content')
<div class="panel-body">
  {{ Form::model($recipe, array('route' => array('recipes.update', $recipe->id), 'method' => 'PUT', 'id' => 'recipeForm')) }}
    <div class="row">
      <div class="form-group col-md-offset-3 col-md-6 text-center">
        {{ Form::label('name', 'Recipe Name:') }}
        {{ Form::text('name', null, array('class' => 'form-control', 'id' => 'name')) }}
      </div>
    </div>
    <div class="row">
      <div class="form-group col-md-3 text-center">
        {{ Form::label('author', 'Created By:') }}
        {{ Form::text('author', null, array('class' => 'form-control', 'id' => 'authorFilter')) }}
      </div>
      <div class="col-md-3 text-center">
        {{ Form::label('user_id', 'Maintained By:') }}
        <select name="user_id" class="form-control" id="user">
          @foreach($lists['owners'] as $user)
            <option value="{{ $user->id}}" {{ $recipe->user->id == $user->id ? 'selected' : '' }}> {{ $user->name }}</option>
          @endforeach
        </select>
      </div>
      <div class="col-md-3 text-center">Entered On: {{$recipe->date_entered->format('Y/m/d') }}</div>
      <div class="col-md-3 text-center">Last Changed: {{$recipe->date_modified->format('Y/m/d') }}</div>
    </div>
    <div class="row">
      <div class="col-sm-offset-3 col-sm-3 text-center">
        {{ Form::label('servings', 'Servings:') }}
        {{ Form::text('servings', null, array('class' => 'form-control','id' => 'servings')) }}
      </div>
      <div class="col-sm-3 text-center">
        {{ Form::label('servings', 'Serving Size:') }}
        {{ Form::text('serving_size', null, array('class' => 'form-control','id' => 'serving_size')) }}
      </div>
    </div>
    <br />
    <div class="row"><div class="panel-heading"><h1>Categories</h1></div></div>
    <div id="categories" class="row text-center">
      @foreach ($recipe->categories as $category)
        <span>
          {{ Form::hidden('category_'.$category->id.'_name', $category->name, array('class' => 'form-control category_name')) }}
          {{ Form::button(ucwords($category->name), array('class' => 'btn form-control category_button','style'=>'width:100px;margin-left:10px;margin-bottom:10px;'))}}
        </span>
      @endforeach
    </div>
    <div class='row text-center'>
      <div class='col-sm-offset-4 col-sm-2'><input id="categoryFilter" class="filter form-control" type="text" placeholder="Search.."></div>
      <div class='col-sm-2'>{{ Form::button("Add", array('id'=>'addCategory','class'=>'form-control'))}}</div>
    </div>
    <br />
    <div class="row"><div class="panel-heading"><h1>Description</h1></div></div>
    {{ Form::textarea('description', $recipe->description, array('class' => 'form-control', 'id' => 'descriptionEditor')) }}
    <br />
    <div class="row"><div class="panel-heading"><h1>Ingredients</h1></div></div>
    <div class="table-responsive">
      <table class="table table-bordered table-striped" id="ingredientTable">
        <thead>
          <tr>
            <th class='col-sm-1'>Order</th>
            <th class='col-sm-2'>Alternative?</th>
            <th class='col-sm-1'>Quantity</th>
            <th class='col-sm-2'>Measurement</th>
            <th class='col-sm-5'>Name&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp</th>
            <th class='col-sm-5'>Notes</th>
            <th class='col-sm-2'></th>
          </tr>
        </thead>
        @foreach ($recipe->ingredients as $index => $ingredient)
          <tr class="recipeIngredient">
            <td>{{Form::hidden("ingredient_".$ingredient->id."_order",$ingredient->order,array('class' => 'form-control ingredientOrder'))}}</td>
            <td>
              @if($index == 0)
                {{Form::checkbox("ingredient_".$ingredient->id."_alternative",null,$ingredient->alternative,array('class' => 'form-control ingredientAlternative','disabled'))}}
              @else
                {{Form::checkbox("ingredient_".$ingredient->id."_alternative",null,$ingredient->alternative,array('class' => 'form-control ingredientAlternative'))}}
              @endif
            </td>
            <td>{{Form::text("ingredient_".$ingredient->id."_quantity",$ingredient->quantity,array('class' => 'form-control ingredientQuantity'))}}</td>
            <td>{{Form::text("ingredient_".$ingredient->id."_measurement",$ingredient->measurement,array('class' => 'form-control ingredientMeasurement'))}}</td>
            <td>{{Form::text("ingredient_".$ingredient->id."_name",$ingredient->name,array('class' => 'form-control ingredientName'))}}</td>
            <td>{{Form::text("ingredient_".$ingredient->id."_notes",$ingredient->special_notes,array('class' => 'form-control ingredientNotes'))}}</td>
            <td>{{Form::button("Remove",array('class' => 'form-control ingredientRemove'))}}</td>
          </tr>
        @endforeach
          <tr id="blankRow"><td colspan='7'></td></tr>
          <tr id="addRow">
            <td></td>
            <td>{{Form::checkbox(null,null,false,array('class' => 'form-control ingredientAlternative','id'=>'addIngredientAlternative'))}}</td>
            <td>{{Form::text(null,null,array('class' => 'form-control ingredientQuantity'))}}</td>
            <td>{{Form::text(null,null,array('class' => 'form-control ingredientMeasurement'))}}</td>
            <td>{{Form::text(null,null,array('class' => 'form-control ingredientName'))}}</td>
            <td>{{Form::text(null,null,array('class' => 'form-control ingredientNotes'))}}</td>
            <td>{{Form::button("Add",array('class' => 'form-control','id' => 'addIngredient'))}}</td>
          </tr>
      </table>
    </div>

    <br /><br />
    <div class="row"><div class="panel-heading"><h1>Instructions</h1></div></div>
    {{ Form::textarea('instructions', $recipe->instructions, array('class' => 'form-control', 'id' => 'instructionsEditor')) }}
</div>

{{ Form::submit('Update Recipe', array('class' => 'btn btn-primary','id'=>'submit')) }}

{{ Form::close() }}
@endsection

@section('scripts')
  <script src="https://cdn.ckeditor.com/4.17.2/standard-all/ckeditor.js"></script>
  <script type="text/javascript" src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
  <script>
    CKEDITOR.replace('instructionsEditor');
    CKEDITOR.replace('descriptionEditor');

    var authors = @json($lists['authors']);
    $("#authorFilter").autocomplete({
      source: authors
    });
    var categories = @json($lists['categories']);
    $("#categoryFilter").autocomplete({
      source: categories
    });

    var ingredients = @json($lists['ingredients']);
    $(".ingredientName").autocomplete({
      source: ingredients
    });

    var measurements = @json($lists['measurements']);
    $(".ingredientMeasurement").autocomplete({
      source: measurements
    });

    $("#categories").on("click",'.category_button',function(){
      $(this).parent().remove();
    });

    $("#addCategory").on("click", function(){
      var newCategory = upperWords($('#categoryFilter').val().toLowerCase());
      var currentCategories = [];
      $(".category").each(function(){
        currentCategories.push($(this).text());
      });
      if(newCategory!="" && currentCategories.indexOf(newCategory) == -1){
        var id=uuidv4();
        $("#categories").append('<input name="category_'+id+'_name" type="hidden" class="form-control category_name ui-autocomplete-input" autocomplete="off" value="'+newCategory+'"><button type="button" class="btn form-control category_button" style="width: 100px; margin-left: 10px;margin-bottom: 10px;">'+newCategory+'</button>');
      }
    });

    function upperWords(str){
      words=str.split(" ");
      words.forEach(function(word,i){
        words[i]=word[0].toUpperCase() + word.slice(1,word.length);
      });
      return words.join(" ");
    }

    $("#ingredientTable").on("click",".ingredientRemove",function(){
      $(this).parent().parent().remove();
      $("#ingredientTable").find('.recipeIngredient .ingredientAlternative:first').attr('disabled',true);
      $("#ingredientTable").find('.recipeIngredient .ingredientAlternative:first').attr('checked',false);
    });

    $("#addIngredient").on("click", function(){
      var ingredientAlternative=$('#addIngredientAlternative').prop("checked");
      var ingredientQuantity=$('#addRow .ingredientQuantity').val();
      var ingredientMeasurement=$('#addRow .ingredientMeasurement').val();
      var ingredientName=$('#addRow .ingredientName').val();
      var ingredientNotes=$('#addRow .ingredientNotes').val();
      if(isFraction(ingredientQuantity) && ingredientMeasurement != "" && ingredientName != ""){
        var id=uuidv4();
        var newRow='<tr class="recipeIngredient">';
        newRow+='<td><input name="ingredient_'+id+'_order" type="hidden" class="form-control ingredientOrder ui-autocomplete-input" autocomplete="off"></td>';
        newRow+='<td><input name="ingredient_'+id+'_alternative" type="checkbox" '+ (ingredientAlternative ? 'checked="checked"' : "") +'class="form-control ingredientAlternative"></td>';
        newRow+='<td><input name="ingredient_'+id+'_quantity" type="text" value="'+ingredientQuantity+'" class="form-control ingredientQuantity"></td>';
        newRow+='<td><input name="ingredient_'+id+'_measurement" type="text" value="'+ingredientMeasurement+'" class="form-control ingredientMeasurement ui-autocomplete-input" autocomplete="off"></td>';
        newRow+='<td><input name="ingredient_'+id+'_name" type="text" value="'+ingredientName+'" class="form-control ingredientName ui-autocomplete-input" autocomplete="off"></td>';
        newRow+='<td><input name="ingredient_'+id+'_notes" type="text" value="'+ingredientNotes+'" class="form-control ingredientNotes ui-autocomplete-input" autocomplete="off"></td>';
        newRow+='<td><button type="button" class="form-control ingredientRemove">Remove</button></td>';
        newRow+='</tr>';
        $("#blankRow").before(newRow);
        $("#ingredientTable").find('.recipeIngredient .ingredientAlternative:first').attr('disabled',true);
        $("#ingredientTable").find('.recipeIngredient .ingredientAlternative:first').attr('checked',false);
      }else{
        if(ingredientMeasurement == ""){alert("Ingredient measurement required")};
        if(ingredientName == ""){alert("Ingredient name required")};
      }
    });

    function isFraction(value){
      var pattern = new RegExp(/(^\d+\/\d+$)|(^\d*\.\d+$)|(^\d+ \d\/\d$)|(^\d+$)/);
      if(value.match(pattern)){return true}
      else{
        alert("Ingredient quantity must be a decimal or fraction");
        return false
      }
    }
    $('#submit').on("click",function(){
      $('.recipeIngredient').each(function(index){
        $(this).find('.ingredientOrder').val(index);
      });
      $('#recipeForm').submit();
    });

    function uuidv4() {
      return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
          var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
          return v.toString(16);
      });
    }
  </script>
@endsection

@section('styles')
  <link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
@endsection
