@extends('layout.user')

@section('content')
<div class="max-w-4xl mx-auto px-3 py-3">
  <div class="bg-white rounded-xl border border-slate-200 p-4 sm:p-5 shadow-sm">
    @php
      $toBytes = static function ($value): int {
          $value = trim((string) $value);
          if ($value === '') {
              return 0;
          }
          $unit = strtolower(substr($value, -1));
          $number = (float) $value;

          if ($unit === 'g') {
              return (int) ($number * 1024 * 1024 * 1024);
          }
          if ($unit === 'm') {
              return (int) ($number * 1024 * 1024);
          }
          if ($unit === 'k') {
              return (int) ($number * 1024);
          }

          return (int) $number;
      };

      $uploadMaxBytes = $toBytes(ini_get('upload_max_filesize'));
      $postMaxBytes = $toBytes(ini_get('post_max_size'));
      $maxEachBytes = min($uploadMaxBytes > 0 ? $uploadMaxBytes : (5 * 1024 * 1024), 5 * 1024 * 1024);
      $maxTotalBytes = $postMaxBytes > 0 ? (int) floor($postMaxBytes * 0.9) : (12 * 1024 * 1024);
      $maxEachMb = round($maxEachBytes / 1024 / 1024, 1);
      $maxTotalMb = round($maxTotalBytes / 1024 / 1024, 1);
    @endphp

    <h1 class="text-lg font-extrabold text-slate-900">Edit Product</h1>
    <p class="text-xs text-amber-700 mt-1">
      Upload limit: main image max {{ $maxEachMb }} MB, each category image max {{ $maxEachMb }} MB, total request max ~{{ $maxTotalMb }} MB.
    </p>
    <p class="text-sm text-slate-600 mt-1">Update submit করলে product আবার pending-এ যাবে admin approval-এর জন্য।</p>

    @if($errors->any())
      <div class="mt-3 rounded-lg border border-rose-200 bg-rose-50 px-3 py-2 text-rose-800 text-sm">
        <ul class="list-disc pl-5 space-y-1">
          @foreach($errors->all() as $e)
            <li>{{ $e }}</li>
          @endforeach
        </ul>
      </div>
    @endif

    <div id="upload-limit-error" class="hidden mt-3 rounded-lg border border-rose-200 bg-rose-50 px-3 py-2 text-rose-800 text-sm"></div>

    <form id="vendor-product-edit-form"
          method="POST"
          action="{{ route('vendor-ship.products.update', $product->id) }}"
          enctype="multipart/form-data"
          data-max-each-bytes="{{ $maxEachBytes }}"
          data-max-total-bytes="{{ $maxTotalBytes }}"
          class="mt-4 grid grid-cols-1 md:grid-cols-2 gap-3">
      @csrf
      @method('PUT')

      <div class="md:col-span-2">
        <label class="block text-sm font-bold text-slate-700 mb-1">Current Main Image</label>
        <img src="{{ $product->main_image_url }}" alt="" class="w-20 h-20 rounded-lg object-cover border border-slate-200">
      </div>

      <div class="md:col-span-2">
        <label class="block text-sm font-bold text-slate-700 mb-1">Replace Main Image</label>
        <input id="main_image" type="file" name="main_image" accept=".jpg,.jpeg,.png,.webp" class="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm">
      </div>

      <div class="md:col-span-2">
        <label class="block text-sm font-bold text-slate-700 mb-1">Add Category Images (Multiple)</label>
        <input id="category_images" type="file" name="category_images[]" multiple accept=".jpg,.jpeg,.png,.webp" class="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm">
      </div>

      <div class="md:col-span-2">
        <label class="block text-sm font-bold text-slate-700 mb-1">Title <span class="text-rose-600">*</span></label>
        <input type="text" name="title" value="{{ old('title', $product->title) }}" required class="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm">
      </div>

      <div class="md:col-span-2">
        <label class="block text-sm font-bold text-slate-700 mb-1">Description</label>
        <textarea name="description" rows="4" class="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm" placeholder="Product description...">{{ old('description', $product->description) }}</textarea>
      </div>

      <div>
        <label class="block text-sm font-bold text-slate-700 mb-1">Admin Price <span class="text-rose-600">*</span></label>
        <input type="number" step="0.01" min="0" name="admin_price" value="{{ old('admin_price', $product->admin_price) }}" required class="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm">
      </div>

      <div>
        <label class="block text-sm font-bold text-slate-700 mb-1">Seller Price <span class="text-rose-600">*</span></label>
        <input type="number" step="0.01" min="0" name="seller_price" value="{{ old('seller_price', $product->seller_price) }}" required class="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm">
      </div>

      <div>
        <label class="block text-sm font-bold text-slate-700 mb-1">Category <span class="text-rose-600">*</span></label>
        <select name="pd_category_id" required class="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm bg-white">
          <option value="">Select category</option>
          @foreach($categories as $c)
            <option value="{{ $c->id }}" @selected(old('pd_category_id', $product->pd_category_id) == $c->id)>{{ $c->name }}</option>
          @endforeach
        </select>
      </div>

      <div>
        @php
          $selectedSizes = old('sizes', $product->sizes_list);
        @endphp
        <label class="block text-sm font-bold text-slate-700 mb-1">Bangladeshi Sizes (Optional)</label>
        <select id="vendor-sizes-edit" name="sizes[]" multiple data-dbl-toggle
                class="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm bg-white h-[130px]">
          @foreach($sizes as $size)
            <option value="{{ $size }}" @selected(in_array($size, (array) $selectedSizes, true))>{{ $size }}</option>
          @endforeach
        </select>
        <p class="text-xs text-slate-500 mt-1">You can select multiple sizes. Double-click a selected size to unselect it.</p>
      </div>

      <div class="md:col-span-2 flex flex-wrap gap-2 mt-1">
        <button type="submit" class="inline-flex items-center rounded-lg bg-indigo-600 px-4 py-2 text-white font-bold hover:bg-indigo-700">
          Update Product
        </button>
        <a href="{{ route('vendor-ship.products.index') }}" class="inline-flex items-center rounded-lg bg-slate-700 px-4 py-2 text-white font-bold hover:bg-slate-800">
          Back
        </a>
      </div>
    </form>
  </div>
</div>
@endsection

@push('scripts')
<script>
document.addEventListener('DOMContentLoaded', function () {
  document.querySelectorAll('select[data-dbl-toggle]').forEach(function (select) {
    select.addEventListener('dblclick', function (e) {
      const option = e.target;
      if (!option || option.tagName !== 'OPTION') return;
      if (option.selected) {
        option.selected = false;
        e.preventDefault();
      }
    });
  });

  const form = document.getElementById('vendor-product-edit-form');
  const errorBox = document.getElementById('upload-limit-error');
  const mainInput = document.getElementById('main_image');
  const categoryInput = document.getElementById('category_images');
  if (!form || !errorBox || !mainInput || !categoryInput) {
    return;
  }

  const maxEach = Number(form.dataset.maxEachBytes || 0);
  const maxTotal = Number(form.dataset.maxTotalBytes || 0);

  const formatMb = function (bytes) {
    return (bytes / 1024 / 1024).toFixed(2);
  };

  form.addEventListener('submit', function (e) {
    let totalBytes = 0;
    const files = [];

    if (mainInput.files && mainInput.files.length > 0) {
      files.push(mainInput.files[0]);
    }

    if (categoryInput.files && categoryInput.files.length > 0) {
      Array.from(categoryInput.files).forEach(function (f) {
        files.push(f);
      });
    }

    for (const file of files) {
      totalBytes += file.size;
      if (maxEach > 0 && file.size > maxEach) {
        e.preventDefault();
        errorBox.textContent = '"' + file.name + '" is too large (' + formatMb(file.size) + ' MB). Max allowed is ' + formatMb(maxEach) + ' MB per file.';
        errorBox.classList.remove('hidden');
        return;
      }
    }

    if (maxTotal > 0 && totalBytes > maxTotal) {
      e.preventDefault();
      errorBox.textContent = 'Total selected file size is ' + formatMb(totalBytes) + ' MB. Please keep it below about ' + formatMb(maxTotal) + ' MB to avoid upload/session failure (419).';
      errorBox.classList.remove('hidden');
      return;
    }

    errorBox.classList.add('hidden');
    errorBox.textContent = '';
  });
});
</script>
@endpush
