@extends('backend.layouts.master')

@section('title')
  {{ __('Order Manage') . ' - ' . $title }}
@endsection

@section('navbar-content')
  <div class="content-header">
    <div class="container-fluid">
      <div class="row mb-2">
        <div class="col-sm-6">
          <h1 class="m-0"> {{ __('Goods') }} </h1>
        </div><!-- /.col -->
        <div class="col-sm-6">
          <ol class="breadcrumb float-sm-right">
            <li class="breadcrumb-item">
              <a href="{{ route('home') }}">{{ __('Dashboard') }}</a>
            </li>
            @if(helper::roleAccess('proforma.invoice.list'))
              <li class="breadcrumb-item">
                <a href="{{ route('proforma.invoice.list') }}">{{ __('PI List') }}</a>
              </li>
            @endif
            <li class="breadcrumb-item active">
              <span>{{ $title }}</span>
            </li>
          </ol>
        </div><!-- /.col -->
      </div><!-- /.row -->
    </div><!-- /.container-fluid -->
  </div>
@endsection

@section('admin-content')
  <section class="row">
    <div class="col-md-12">
      <div class="card card-default">
        <div class="card-header">
          <h3 class="card-title">{{ $title }}</h3>
          <div class="card-tools">
            @if(helper::roleAccess('proforma.invoice.list'))
              <a class="btn btn-tool btn-default" href="{{ route('proforma.invoice.list') }}">
                <i class="fa fa-list"></i>
                <span>{{ __('PI List') }}</span>
              </a>
            @endif
            <span id="buttons"></span>
            <a class="btn btn-tool btn-default" data-card-widget="collapse">
              <i class="fas fa-minus"></i>
            </a>
            <a class="btn btn-tool btn-default" data-card-widget="remove">
              <i class="fas fa-times"></i>
            </a>
          </div>
        </div><!-- /.card-header -->
        <div class="card-body">
          <form class="needs-validation" method="POST" action="{{ route('proforma.invoice.update', $pi->id) }}" novalidate enctype="multipart/form-data" >
            @csrf
            <div class="col-md-10 offset-md-1 py-0">
              <div class="form-row">
                <div class="col-md-6 mb-3">
                  <label for="piNumber">{{ __('PI Number * :') }}</label>
                  <input type="text" name="pi_number" class="form-control form-control-sm" id="piNumber" placeholder="PI Number" value="{{ old('pi_number', $pi->pi_number) }}" required />
                  @error('pi_number')
                    <span class=" error text-red text-bold">{{ $message }}</span>
                  @enderror
                </div>
                <div class="col-md-6 mb-3">
                  <label for="orderID">{{ __('Order * :') }}</label>
                  <select class="form-control select2" name="order_id" id="orderID" disabled >
                      <option value="{{ $order->id }}" >{{ '[' . $order->po_number . '] - ' . $order->buyer->name . ' - (' . $order->style_no . ')' }}</option>
                      <input type="hidden" name="buyer_id" value="{{ $order->buyer_id }}" />
                  </select>
                  @error('order_id')
                    <span class=" error text-red text-bold">{{ $message }}</span>
                  @enderror
                </div>
                <div class="col-md-6 mb-3">
                  <label for="piDate">{{ __('PI Date * :') }}</label>
                  <div class="input-group input-group-sm date" id="reservationdate1" data-target-input="nearest">
                    <input type="text" id="piDate" name="pi_date" data-toggle="datetimepicker" value="{{ old('pi_date', $pi->pi_date) }}" class="form-control datetimepicker-input" data-target="#reservationdate1" />
                    <div class="input-group-append" data-target="#reservationdate1" data-toggle="datetimepicker">
                      <div class="input-group-text">
                        <i class="fa fa-calendar"></i>
                      </div>
                    </div>
                  </div>
                  @error('pi_date')
                    <span class=" error text-red text-bold">{{ $message }}</span>
                  @enderror
                </div>
                <div class="col-md-6 mb-3">
                  <label for="vatNumber">{{ __('VAT Number * :') }}</label>
                  <input type="text" name="vat_number" class="form-control form-control-sm" id="vatNumber" placeholder="VAT Number" value="{{ old('vat_number', $pi->vat_number) }}" required />
                  @error('vat_number')
                    <span class=" error text-red text-bold">{{ $message }}</span>
                  @enderror
                </div>
              </div>
            </div>    
            <hr>
            <div class="col-12 table-responsive">
              <table class="table table-striped table-bordered">
                <thead>
                  <tr>
                    <th width="100px">{{ __('SL') }}</th>
                    <th width="200px">{{ __('HS Code') }}</th>
                    <th>{{ __('Item Description') }}</th>
                    <th class="text-center" width="100px" >{{ __('Qty') }}</th>
                    <th class="text-center" width="100px" >{{ __('Unit Price') }}</th>
                    <th style="text-align:right" width="150px">{{ __('Total') }}</th>
                  </tr>
                </thead>
                <tbody>
                  @foreach ($invoice->details as $key => $item)
                    <tr>
                      <td>{{ $loop->iteration }}</td>
                      <td>
                        @if ($item->hs_code != null)
                          <span>{{ $item->hs_code }}</span>
                        @else
                          <input type="text" name="hs_code[]" class="form-control form-control-sm" id="hsCode{{ $key+1 }}" placeholder="HS Code" required />
                        @endif
                      </td>
                      <td>
                        <div class="row" >
                          <div class="ml-1" style="width: 45px !important;" >
                            <img src="{{ $item->thumbnail }}" class="" alt="" width="40px" height="40px" />
                          </div>
                          <div class="col" >
                            <strong>{{ $item->goods_name ?? 'N/A' }}</strong>
                            <br>
                            <small>{{ $item->category ?? 'N/A' }}</small>
                          </div>
                        </div>
                      </td>
                      <td class="text-center">
                        <span class="quantity">{{ $item->quantity ?? 0 }}</span>
                      </td>
                      <td class="text-right">
                        <input type="number" class="form-control form-control-sm rate" name="rate[]" value="{{ $item->rate }}" id="rate{{ $key+1 }}" placeholder="Unit Price" {{ $item->rate > 0 ? '' : '' }} />
                      </td>
                      <td class="text-right">
                        <input type="number" class="form-control form-control-sm price" name="price[]" value="{{ $item->price }}" id="price{{ $key+1 }}" placeholder="Total Price" {{ $item->price > 0 ? 'readonly' : '' }} />
                      </td>
                    </tr>
                  @endforeach
                </tbody>
                <tfoot>
                  <tr>
                    <th colspan="3" style="text-align: right">{{ __('TOTAL =') }}</th>
                    <td class="text-center">{{ $invoice->details->sum('quantity') }}</td>
                    <td></td>
                    <th class="text-right" id="totalvalue">{{ number_format($pi->order->amount, 2) . '/-' }}</th>
                  </tr>
                </tfoot>
              </table>
            </div>
            <div class="col-md-12">
              <div class="from-group">
                <label for="note">{{ __('Invoice Note') }}</label>
                <textarea name="note" class="form-control form-control-sm" id="note" cols="30" rows="10">{!! $pi->note !!}</textarea>
              </div>
            </div>
            <div class="col-md-12">
              <div class="row">
                <div class="col-md-3 mb-3">
                  <label for="exampleInputFile">{{ __('Attachments :') }}</label>
                  <div class="input-group input-group-sm">
                    <div class="custom-file">
                      {{-- <input type="file" name="attachments[]" class="custom-file-input" id="attachments" accept=".jpg, .jpeg, .png, .gif, .webp" multiple /> --}}
                      <input type="file" name="attachments[]" class="custom-file-input" id="attachments" accept=".jpg, .jpeg, .png, .gif, .webp, .pdf, .doc, .docx, .rtf, .xls, .xlsx, .csv, .txt" multiple />
                      <label class="custom-file-label" for="attachments" >{{ __('Choose file') }}</label>
                    </div>
                  </div>
                </div>
                <div class="col-md-12">
                  <div id="selected-files-container" class="row"></div>
                </div>
              </div>
            </div>
            <div class="col-md-12">
              <button class="btn btn-info" type="submit">
                <i class="fa fa-save"></i>
                <span>&nbsp; {{ __('Save') }}</span>
              </button>
            </div>
          </form>
        </div><!-- /.card-body -->
        <div class="card-footer"></div>
      </div>
    </div><!-- /.col-->
  </section>
@endsection

@section('scripts')
  <script>
    $(function () {
      bsCustomFileInput.init();
    });
  </script>

  <script>
    var imgInp = document.getElementById("thumbnail");
    var dummy = document.getElementById("dummy");
    imgInp.onchange = evt => {
      const [file] = imgInp.files
      if (file) {
        dummy.src = URL.createObjectURL(file)
      }
    }
  </script>

  <script>
    var note = `<ol><li><b>Origin :</b> Bangladesh</li><li><b>Shipment :</b> As per Buyer Instruction, but partial and Trans Shipment Must Be Allowed</li><li><b>Shipping port :</b> As per Buyer Instruction.</li><li><b>Delivery :</b> By Car / Cab</li><li><b>Payment :</b> At 150 days sight I, e. from the date of shipment by Irrevocable Letter Of Credit in US Dollar on Mutual Trust Bank, Uttara Model Town Branch Dhaka. Interest will be calculated for usancc period as per rate prescribed by Bangladesh Bank. Which must be an Integral part of L/C.</li><li><b>Overdue :</b> If payment is effected after maturity date.</li><li><b>Bank Swift :</b> MTBLBDDHUTR</li><li><b>Account No. :</b> 1301-010092083</li></ol>`;
    $('#note').summernote({
      placeholder: 'Proforma Invoice Note',
      value: note,
      tabsize: 2,
      height: 250,
      toolbar: [
        ['style', ['style']],
        ['font', ['bold', 'italic', 'underline', 'clear']],
        ['fontname', ['fontname']],
        ['size', ['fontsize', 'color']],
        ['para', ['ul', 'ol', 'paragraph']],
        ['insert', ['table']]
      ]
    });
    $('#note').summernote('code', note);
  </script>

  <script>
    $(document).ready(function() {
      $('#attachments').change(function() {
        var files = $(this)[0].files;
        var container = $('#selected-files-container');
        container.empty();
        for (var i = 0; i < files.length; i++) {
          var file = files[i];
          var fileName = file.name;
          var fileSize = (file.size / 1024).toFixed(2) + ' KB';
          var card = '<div class="col-md-2">';
          card += '<div class="card">';
          card += '<div class="card-body p-2">';
          card += '<h5 class="card-title">' + fileName + '</h5>';
          card += '<p class="card-text">(' + fileSize + ')</p>';
          card += '</div></div></div>';
          container.append(card);
        }
      });
      
      $(document).on('click', '.remove-file', function() {
        var confirmation = confirm('Are you sure you want to remove this file?');
        if (confirmation) {
          var card = $(this).closest('.col-md-2');
          var index = card.index();
          var files = $('#attachments')[0].files;
          var newFiles = Array.from(files);
          newFiles.splice(index, 1);
          $('#attachments').val('');
          $('#attachments')[0].files = newFiles;
          card.remove();
        }
      });
    });
  </script>

  <script>
    $(document).ready(function() {
      $('.rate').on('input', function() {
        var $row = $(this).closest('tr');
        var quantity = parseInt($row.find('.quantity').text());
        var rate = parseFloat($(this).val());
        var totalPrice = quantity * rate;
        $row.find('.price').val(totalPrice.toFixed(2));
       let value = 0;
        $.each($('input[name="price[]"]'),function(val){
          value += Number($(this).val());
        })
        $('#totalvalue').text(value);
      });
    });
  </script>
@endsection