@extends('backend.layouts.master')

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

@section('styles')
  <style>
    .bootstrap-switch-large { width: 200px; }
  </style>
@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">{{ __('Order Manage') }} </h1>
        </div><!-- /.col -->
        <div class="col-sm-6">
          <ol class="breadcrumb float-sm-right">
            <li class="breadcrumb-item">
              <a href="{{ !Auth::guard('web')->user() ? route('buyer.dashboard') : route('home') }}">{{ __('Dashboard') }}</a>
            </li>
            @if(helper::roleAccess('order.index'))
              <li class="breadcrumb-item">
                <a href="{{route('order.index') }}">{{ __('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.create'))
              <a class="btn btn-sm btn-default" href="{{ route('proforma.invoice.create') }}">
                <i class="fas fa-plus"></i>
                <span>{{ __('Add New') }}</span>
              </a>
            @endif
            <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">
          <span id="buttons"></span>
          <div class="table-responsive my-2">
            <table id="systemDatatable" class="display table-hover table table-bordered table-striped">
              <thead>
                <tr>
                  <th>{{ __('SL') }}</th>
                  @if (Auth::guard('web')->user())
                    <th>{{ __('Buyer Name') }}</th>
                  @endif
                  <th>{{ __('PI Number') }}</th>
                  <th>{{ __('Style No') }}</th>
                  <th>{{ __('PO Number') }}</th>
                  <th width="100px">{{ __('Order Date') }}</th>
                  <th width="100px">{{ __('Amount') }}</th> 
                  <th width="60px">{{ __('Status') }}</th>
                  <th width="60px">{{ __('Action') }}</th>
                </tr>
              </thead>
              <tbody>
                @foreach ( $profirmaInvoices as $invoice )
                  <tr>
                    <td>{{ $loop->iteration }}</td>
                    @if (Auth::guard('web')->user())
                      <td>{{ $invoice->buyer->name }}</td>
                    @endif
                    <td>{{ $invoice->pi_number }}</td>
                    <td>{{ $invoice->order->style_no }}</td>
                    <td>{{ $invoice->order->po_number }}</td>
                    <td>{{ $invoice->order->created_at->format('d-m-Y') }}</td>
                    <td>{{ number_format($invoice->order->amount, 2) . '/-' }}</td>
                    <td>
                      @if (!Auth::guard('buyer')->user() || Auth::guard('buyer')->user() && $invoice->order->status == 'Confirmed' )
                        <span class="badge bg-{{ $invoice->order->status == 'Pending' ? 'secondary' : 'success' }}">{{ $invoice->order->status }}</span>
                      @else
                        <input class="status_row form-controm form-controls-sm" status_route="{{ route('buyer.proforma.invoice.status', [$invoice->id, 'Confirmed']) }}"  id="toggle-demo" type="checkbox" name="my-checkbox"  data-bootstrap-switch data-off-color="danger" data-on-color="success" >
                      @endif
                    </td>
                    
                    <td class="d-flex">
                      @if (!Auth::guard('buyer')->user())
                        <a href="{{ route('proforma.invoice.edit', $invoice->id) }}" class="btn btn-sm btn-info px-2 py-1 mr-1" >
                          <i class="fas fa-edit"></i>
                        </a>
                        <div class="dropdown">
                          <button class="btn btn-sm btn-secondary dropdown-toggle px-2 pb-1" style="padding-left: 0.8rem !important; padding-right: 0.8rem !important;" type="button" data-toggle="dropdown" aria-expanded="false" ></button>
                          <div class="dropdown-menu">
                            <button type="button" class="dropdown-item" redirect="{{ route('project.project.index') }}" data-toggle="modal" data-target="#generatePI" data-pi-id="{{ $invoice->id }}" data-pi-number="{{ $invoice->pi_number }}" data-order-id="{{ $invoice->order_id }}" data-buyer-id="{{ $invoice->buyer->id }}" data-buyer-name="{{ $invoice->buyer->name }}" data-style-no="{{ $invoice->order->style_no }}" data-po-number="{{ $invoice->order->po_number }}" {{ $invoice->project ? 'disabled' : '' }} >
                              <i class="fas fa-file-invoice" style="width: 1rem !important;" ></i>
                              <span class="ml-1">{{ __('Generate Project') }}</span>
                            </button>
                            <a href="{{ route('order.show', $invoice->order_id) }}" class="dropdown-item" >
                              <i class="fas fa-eye"></i>
                              <span class="ml-1">{{ __('View Invoice') }}</span>
                            </a>
                          </div>
                        </div>
                      @endif
                      @if (!Auth::guard('web')->user())
                        <a href="{{ route('buyer.proforma.invoice.show', $invoice->id) }}" class="btn btn-sm btn-primary" >
                          <i class="fas fa-eye"></i>
                        </a>
                        @if ($invoice->order->status == 'Confirmed')
                          <button class="btn btn-sm btn-warning" disabled >
                            <i class="fas fa-check"></i>
                          </button>
                        @endif
                      @endif
                    </td>
                  </tr>
                @endforeach
              </tbody>
              <tfoot>
                <tr>
                  <th>{{ __('SL') }}</th>
                  @if (Auth::guard('web')->user())
                    <th>{{ __('Buyer Name') }}</th>
                    @endif
                  <th>{{ __('PI Number') }}</th>
                  <th>{{ __('Style No.') }}</th>
                  <th>{{ __('PO Number') }}</th>
                  <th>{{ __('Order Date') }}</th>
                  <th>{{ __('Amount') }}</th>
                  <th>{{ __('Status') }}</th>
                  <th>{{ __('Action') }}</th>
                </tr>
              </tfoot>
            </table>
          </div>
        </div><!-- /.card-body -->
        <div class="card-footer"></div>
      </div>
    </div><!-- /.col-->
    <form action="" method="post">
      @method('delete')
    </form>
  </section>

  <!-- Modal -->
  <section class="modal fade" id="generatePI" tabindex="-1" aria-labelledby="generatePILabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
      <div class="modal-content">
        <form id="generatePIForm" action="{{ route('project.project.generate')}}" method="POST" >
          @csrf
          <div class="modal-header py-2">
            <h5 class="modal-title" id="generatePILabel">{{ __('Generate Project') }}</h5>
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
              <span aria-hidden="true">&times;</span>
            </button>
          </div>
          <div class="modal-body">
            <div class="row">
              <input type="hidden" name="projectCode" value="{{ $projectCode }}" />
              <input type="hidden" name="invoice_id" id="pInvoiceId" />
              <div class="col-md-12 mb-3">
                <label for="name">{{ __('Project Name') }}</label>
                <input type="text" name="name" class="form-control form-control-sm" id="name" placeholder="Project Name" value="{{ $projectCode }}" required />
                @error('name')
                  <span class=" error text-red text-bold">{{ $message }}</span>
                @enderror
              </div>
              <div class="col-md-12 mb-3">
                <label for="orderId">{{ __('Order') }}</label>
                <select name="order_id" class="form-control form-control-sm" id="orderId" required readonly ></select>
              </div>
              <div class="col-md-6 mb-3">
                <label for="piNumber">{{ __('PI Number') }}</label>
                <input type="text" class="form-control form-control-sm" id="piNumber" readonly />
              </div>
              <div class="col-md-6 mb-3">
                <label for="managerId">{{ __('Manager Name') }}</label>
                <select name="manager_id" class="form-control select2" id="managerId" required >
                  @foreach ($managers as $key => $value)
                    <option value="{{ $value->id }}">{{ $value->branchCode . ' - ' . $value->name }}</option>
                  @endforeach
                </select>
              </div>

              <div class="col-md-6 mb-3">
                <label for="budget">{{ __('Project Value') }}</label>
                <input type="number" name="budget" class="form-control form-control-sm" id="amount"  placeholder="Budget" required />
            </div>
              <div class="col-md-6 mb-3">
                <label for="amount">{{ __('Estimate Amount') }}</label>
                <input type="text" name="estimate_profit" class="form-control form-control-sm" id="estimateAmount"  placeholder="Estimate Amount" required />
            </div>
            
              {{-- <div class="col-md-6 mb-3">
                <label for="estimateProfit">{{ __('Estimate Profit') }}</label>
                <input type="number" name="estimate_profit" class="form-control form-control-sm" id="estimateProfit" placeholder="Estimate Profit" required />
              </div> --}}
              <div class="col-md-6 mb-3">
                <label for="startDate">{{ __('Start Date * :') }}</label>
                <div class="input-group input-group-sm date" id="reservationdate1" data-target-input="nearest">
                  <input type="text" id="startDate" name="start_date" data-toggle="datetimepicker" value="{{ old('pi_date', date('Y-m-d')) }}" class="form-control datetimepicker-input" data-target="#reservationdate1" required />
                  <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('start_date')
                  <span class=" error text-red text-bold">{{ $message }}</span>
                @enderror
              </div>
              <div class="col-md-6 mb-3">
                <label for="endDate">{{ __('Complete Date * :') }}</label>
                <div class="input-group input-group-sm date" id="reservationdate1" data-target-input="nearest">
                  <input type="text" id="endDate" name="end_date" data-toggle="datetimepicker" value="{{ old('pi_date', date('Y-m-d')) }}" class="form-control datetimepicker-input" data-target="#reservationdate1" required />
                  <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('end_date')
                  <span class=" error text-red text-bold">{{ $message }}</span>
                @enderror
              </div>
              <div class="col-md-12 mb-3">
                <label for="poNumber">{{ __('Address') }}</label>
                <textarea type="text" rows="1" name="address" class="form-control form-control-sm" id="validationCustom01" placeholder="Project Address">{{ old('address') }}</textarea>
              </div>
            </div>
          </div>
          <div class="modal-footer py-1">
            <button type="button" class="btn btn-primary generate" id="generate">{{ __('Generate') }}</button>
          </div>
        </form>
      </div>
    </div>
  </section>
@endsection

@section('scripts')
  <script>
   
   $(document).ready(function () {
  var table = $('#systemDatatable').DataTable({
    // DataTable configuration options go here
  });

  var buttons = new $.fn.dataTable.Buttons(table, {
    buttons: [
      'copyHtml5',
      'excelHtml5',
      'csvHtml5',
      'pdfHtml5',
      'print'
    ]
  }).container().appendTo($('#buttons'));

  $('#generatePI').on('show.bs.modal', function (event) {
    var button = $(event.relatedTarget);
    var redirect = button.attr('redirect');
    var invoiceId = button.data('pi-id');
    var piNumber = button.data('pi-number');
    var amount = button.data('amount');
    var orderID = button.data('order-id');
    var buyerID = button.data('buyer-id');
    var buyerName = button.data('buyer-name');
    var styleNo = button.data('style-no');
    var poNumber = button.data('po-number');
    var option = '<option value="' + orderID + '">(' + poNumber + ') ' + buyerName + ' [' + styleNo + ']' + '</option>';
    
    // Populate fields with data
    $('#pInvoiceId').val(invoiceId);
    $('#piNumber').val(piNumber);
    $('#orderID').val(orderID);
    $('#amount').val(amount);
    $('#styleNo').val(styleNo);
    $('#poNumber').val(poNumber);
    $('#orderId').html(option);
    $('#orderId').html(option);

    $('#generate').click(function() {
      if(validateForm()) {
        // $('#generatePIForm').submit();
        // window.location.href = redirect;
        $.ajax({
          url: $('#generatePIForm').attr('action'),
          method: 'POST',
          data: $('#generatePIForm').serialize(),
          success: function(response) {
            // If successful, redirect to the specified URL
            window.location.href = redirect;
          },
          error: function(xhr, status, error) {
            // Handle error if necessary
            console.error(error);
          }
        });
      }
    });

    function validateForm() {
      var name = $('#name').val();
      var orderId = $('#orderId').val();
      var managerId = $('#managerId').val();
      var budget = $('#budget').val();
      var estimateAmount = $('#estimateAmount').val(); // Add this line
      var startDate = $('#startDate').val();
      var endDate = $('#endDate').val();
      var address = $('#validationCustom01').val();

      if(name.trim() === '') {
        alert('Please enter Project Name.');
        return false;
      }
      if(orderId.trim() === '') {
        alert('Please select an order.');
        return false;
      }
      if(managerId.trim() === '') {
        alert('Please select a manager.');
        return false;
      }
      // if(budget.trim() === '') {
      //   alert('Please enter Project Value.');
      //   return false;
      // }
      if(estimateAmount.trim() === '') { // Add this condition
        alert('Please enter Estimate Amount.'); // Add this message
        return false;
      }
      if(startDate.trim() === '') {
        alert('Please select a Start Date.');
        return false;
      }
      if(endDate.trim() === '') {
        alert('Please select a Complete Date.');
        return false;
      }
      if(address.trim() === '') {
        alert('Please enter Project Address.');
        return false;
      }

      return true;
    }
  });
});

  </script>
@endsection