@extends('layout.user')

@section('content')
@php
  $gs   = \App\Models\GeneralSetting::first();
  $g1   = $gs->icon_color   ?? '#0B5D1E';   // primary
  $g2   = $gs->hover_color  ?? '#0F7A2E';   // secondary
  $g3   = $gs->accent_color ?? '#E4002B';   // accent
  $ink  = $gs->text_color   ?? '#0f172a';   // body text
  $sizeOptions = $product->size_options;
  $insideDhakaCharge = $product->deliveryChargeForZone(\App\Models\Product::DELIVERY_ZONE_DHAKA_CITY);
  $nearDhakaCharge = $product->deliveryChargeForZone(\App\Models\Product::DELIVERY_ZONE_SUB_DHAKA);
  $outsideDhakaCharge = $product->deliveryChargeForZone(\App\Models\Product::DELIVERY_ZONE_OUT_DHAKA);
@endphp

<style>
  /* underline ও ট্যাপ হাইলাইট বন্ধ */
  #checkout a,
  #checkout a:hover,
  #checkout a:active,
  #checkout a:visited { text-decoration: none !important; -webkit-tap-highlight-color: transparent; }
  #checkout a:focus { outline: none; }

  /* ✅ BLUE BORDER SYSTEM (same style everywhere) */
  .blue-border{
    border:1.5px solid #2563eb !important;
  }
  .soft-blue{
    border:1px solid rgba(37,99,235,.35) !important;
  }

  /* নরম শ্যাডো + কার্ড রেডিয়াস ইউনিফর্ম */
  .cardish { border-radius: 18px; box-shadow: 0 8px 24px rgba(0,0,0,.06); }

  /* ✅ ইনপুট/ফিল্ড/বক্স সব জায়গায় নীল বর্ডার */
  .field{
    border:1.5px solid #2563eb !important;
    transition:.15s ease;
    background:#fff;
  }
  .field:focus{
    outline:none;
    border-color:#1d4ed8 !important;
    box-shadow:0 0 0 3px rgba(37,99,235,.18);
  }

  /* Qty wrapper border */
  .qty-wrap{
    border:1.5px solid #2563eb !important;
  }
  .qty-btn{
    border:none;
    background:#f8fafc;
  }
  .qty-mid{
    border-left:1.5px solid #2563eb !important;
    border-right:1.5px solid #2563eb !important;
  }

  .size-radio{
    position:absolute;
    opacity:0;
    pointer-events:none;
  }
  .size-pill{
    display:inline-flex;
    align-items:center;
    justify-content:center;
    min-width:54px;
    padding:6px 12px;
    border-radius:999px;
    border:1.5px solid #2563eb;
    color:#1d4ed8;
    font-weight:700;
    font-size:13px;
    cursor:pointer;
    background:#fff;
    transition:.15s ease;
  }
  .size-radio:checked + .size-pill{
    background:#1d4ed8;
    color:#fff;
    border-color:#1d4ed8;
    box-shadow:0 0 0 2px rgba(37,99,235,.18);
  }
</style>

<div id="checkout" class="mx-auto max-w-3xl px-2 sm:px-3 md:px-4 mt-2 pb-10">

  {{-- Header --}}
  <div class="flex items-center justify-between gap-2 mb-3">
    <h1 class="text-lg font-extrabold" style="color:{{ $ink }}">🛒 চেকআউট</h1>
    <a href="{{ url()->previous() }}"
       class="inline-flex items-center gap-1.5 rounded-lg px-3 py-1.5 text-sm transition blue-border"
       style="background:rgba(37,99,235,.08); color:#2563eb;">
      <i class="fa-solid fa-arrow-left text-[12px]"></i> Back
    </a>
  </div>

  {{-- Alerts --}}
  @if(session('success'))
    <div class="mb-2 rounded-lg px-3 py-2 text-sm shadow-sm blue-border"
         style="background:#10b98122;color:#065f46;">
      <i class="fa-solid fa-circle-check mr-1.5"></i> {{ session('success') }}
    </div>
  @endif

  @if($errors->any())
    <div class="mb-2 rounded-lg px-3 py-2 text-sm shadow-sm blue-border"
         style="background:#f43f5e22;color:#7f1d1d;">
      <ul class="list-disc pl-4 space-y-0.5">
        @foreach ($errors->all() as $e)<li>{{ $e }}</li>@endforeach
      </ul>
    </div>
  @endif

  <div class="cardish blue-border p-4 space-y-4 bg-white">

    {{-- শিরোনাম + পাইকারি মূল্য --}}
    <div class="flex items-start justify-between gap-2">
      <div class="text-[16px] font-semibold" style="color:{{ $ink }}">{{ $product->title }}</div>
      <div class="text-right">
        <div class="text-[12px] text-gray-500">পাইকারি মূল্য</div>
        <div id="wholesale" class="text-[16px] font-black"
             data-admin="{{ (float) $product->admin_price }}"
             style="background:linear-gradient(90deg,{{ $g1 }},{{ $g2 }});-webkit-background-clip:text;background-clip:text;color:transparent;">
          ৳{{ number_format($product->admin_price,2) }}
        </div>
      </div>
    </div>

    {{-- 2-column: ইমেজ + Qty --}}
    <div class="grid sm:grid-cols-2 gap-4">

      <div>
        @if($product->banner_photo_url)
          <div class="rounded-xl overflow-hidden blue-border bg-gray-50 shadow-sm">
            <img src="{{ $product->banner_photo_url }}" alt="Banner" class="w-full h-auto block">
          </div>
        @else
          <div class="rounded-xl blue-border bg-gray-50 p-6 text-center text-gray-400">
            No image
          </div>
        @endif
      </div>

      {{-- Qty + size + color --}}
      <div class="grid gap-3">

        <div>
          <label class="text-sm font-semibold" style="color:{{ $ink }}">পরিমাণ</label>

          <div class="mt-1 inline-flex items-stretch rounded-lg overflow-hidden w-full max-w-[240px] shadow-sm qty-wrap">
            <button type="button" id="qtyMinus" class="px-3 text-lg leading-none qty-btn">−</button>

            <input type="number" inputmode="numeric" pattern="[0-9]*"
                   name="qty" id="qty" min="1" value="1"
                   class="w-24 text-center field qty-mid" form="checkoutForm">

            <button type="button" id="qtyPlus" class="px-3 text-lg leading-none qty-btn">+</button>
          </div>

          <p class="text-xs text-gray-500 mt-0.5">কমপক্ষে ১টি</p>
        </div>

        <div>
          @if(!empty($sizeOptions))
            <label class="text-sm font-semibold" style="color:{{ $ink }}">Select Size <span style="color:#ef4444">*</span></label>
            <div class="mt-1 flex flex-wrap gap-2">
              @foreach($sizeOptions as $size)
                <label class="relative">
                  <input type="radio"
                         name="size"
                         form="checkoutForm"
                         value="{{ $size }}"
                         class="size-radio"
                         @checked(old('size') == $size)
                         required>
                  <span class="size-pill">{{ $size }}</span>
                </label>
              @endforeach
            </div>
            <p class="text-xs text-gray-500 mt-1">Select one size to continue.</p>
          @else
            <label class="text-sm font-semibold" style="color:{{ $ink }}">Size (optional)</label>
            <input type="text" name="size" form="checkoutForm"
                   value="{{ old('size') }}"
                   class="mt-1 w-full rounded-lg px-3 py-2 shadow-sm field">
          @endif
        </div>

        <div>
          <label class="text-sm font-semibold" style="color:{{ $ink }}">Color (ঐচ্ছিক)</label>
          <input type="text" name="color" form="checkoutForm"
                 value="{{ old('color') }}"
                 class="mt-1 w-full rounded-lg px-3 py-2 shadow-sm field">
        </div>

      </div>
    </div>

    {{-- বিক্রয় মূল্য + আপনার আয় --}}
    <div class="grid sm:grid-cols-2 gap-4">

      <div>
        <label class="text-sm font-semibold" style="color:{{ $ink }}">বিক্রয় মূল্য (প্রতি আইটেম)</label>
        <div class="relative mt-1">
          <input type="number" step="0.01" min="0" name="sale_price" id="sale_price" form="checkoutForm"
                 value="{{ old('sale_price', number_format($product->admin_price,2,'.','')) }}"
                 class="w-full rounded-lg pl-8 pr-3 py-2 shadow-sm field">
          <span class="absolute left-2 top-1/2 -translate-y-1/2 text-gray-500">৳</span>
        </div>

        <p class="text-xs mt-1 text-gray-500">
          সীমা:
          <span class="font-semibold" style="color:{{ $g1 }}">৳{{ number_format($product->admin_price,2) }}</span> —
          <span class="font-semibold" style="color:#059669">৳{{ number_format($product->reseller_price,2) }}</span>
        </p>

        <div id="saleWarn" class="hidden text-xs mt-0.5" style="color:#b91c1c">
          এমাউন্ট সঠিকভাবে লিখুন (পাইকারি ও সর্বোচ্চ বিক্রয় মূল্যের মধ্যে)।
        </div>
      </div>

      <div>
        <label class="text-sm font-semibold" style="color:{{ $ink }}">আপনার আয় (প্রতি পিস)</label>
        <div class="mt-1 rounded-lg px-3 py-2 font-semibold shadow-sm blue-border"
             style="background:#10b9811a;color:#065f46">
          ৳<span id="earnPerItem">0.00</span>
        </div>
      </div>
    </div>

    {{-- Totals --}}
    <div class="grid sm:grid-cols-3 gap-3">

      <div class="rounded-xl p-3 shadow-sm blue-border" style="background:#f8fafc">
        <div class="text-[12px] text-gray-500">প্রোডাক্ট মোট</div>
        <div class="text-[16px] font-black" style="color:{{ $ink }}">৳<span id="totalWholesale">0.00</span></div>
      </div>

      <div class="rounded-xl p-3 shadow-sm blue-border"
           style="background:#10b9811a;color:#065f46">
        <div class="text-[12px]">আপনার মোট আয়</div>
        <div class="text-[16px] font-black">৳<span id="totalEarn">0.00</span></div>
      </div>

      <div class="rounded-xl p-3 shadow-sm blue-border"
           style="background:rgba(37,99,235,.08);color:#2563eb">
        <div class="text-[12px]">সর্বমোট মূল্য</div>
        <div class="text-[16px] font-black">৳<span id="grandTotal">0.00</span></div>
      </div>
    </div>

    {{-- ডেলিভারি নোট --}}
    <div class="mt-2 text-[13px] font-medium rounded-lg px-3 py-2 blue-border" style="color:#92400e;background:#f59e0b1a;">
      পরের ধাপে জেলা/থানা অনুযায়ী চার্জ হবে: ঢাকা সিটি = ৳{{ number_format($insideDhakaCharge, 2) }},
      সাব ঢাকা = ৳{{ number_format($nearDhakaCharge, 2) }}, আউট ঢাকা = ৳{{ number_format($outsideDhakaCharge, 2) }}।
      {{ (int) $product->delivery_payment_type === 1 ? 'এই চার্জ ভাউচার ব্যালেন্স থেকে কাটা হবে।' : 'এই চার্জ ডেলিভারির সময় মোট টাকার সাথে দিতে হবে।' }}
    </div>

    {{-- Submit --}}
    <form id="checkoutForm" action="{{ route('order.store', $product->id) }}" method="POST" class="pt-3">
      @csrf
      <button
  class="w-full inline-flex items-center justify-center gap-2 rounded-xl px-4 py-3 text-white text-base font-bold shadow-md transition blue-border"
  style="background:linear-gradient(90deg,#2563eb,#1d4ed8); border-color:#2563eb !important;">
  পরবর্তী
  <i class="fa-solid fa-arrow-right-long text-[13px]"></i>
</button>

      {{-- Hidden helpers --}}
      <input type="hidden" id="admin_price" value="{{ (float) $product->admin_price }}">
      <input type="hidden" id="reseller_price" value="{{ (float) $product->reseller_price }}">
    </form>

  </div>
</div>

{{-- Qty & Price JS (same logic) --}}
<script>
(function(){
  const $ = (s)=>document.querySelector(s);

  const qtyInput  = $('#qty');
  const minusBtn  = $('#qtyMinus');
  const plusBtn   = $('#qtyPlus');
  const saleInp   = $('#sale_price');
  const saleWarn  = $('#saleWarn');

  const admin = parseFloat($('#admin_price').value || '0');
  const maxRes = parseFloat($('#reseller_price').value || '0');

  const earnPerItem   = $('#earnPerItem');
  const totalWholesale= $('#totalWholesale');
  const totalEarn     = $('#totalEarn');
  const grandTotal    = $('#grandTotal');

  function clampQty(){
    let q = parseInt(qtyInput.value || '1', 10);
    if(isNaN(q) || q < 1) q = 1;
    qtyInput.value = q;
    return q;
  }

  function getSale(){
    let v = parseFloat(saleInp.value || '0');
    if(isNaN(v)) v = 0;

    if(v < admin || v > maxRes) saleWarn.classList.remove('hidden');
    else saleWarn.classList.add('hidden');

    return v;
  }

  function recalc(){
    const q    = clampQty();
    const sale = getSale();

    const perEarn = Math.max(0, sale - admin);
    earnPerItem.textContent = perEarn.toFixed(2);

    totalWholesale.textContent = (admin * q).toFixed(2);
    totalEarn.textContent      = (perEarn * q).toFixed(2);

    grandTotal.textContent = (sale * q).toFixed(2);
  }

  minusBtn.addEventListener('click', () => {
    let q = clampQty();
    if(q > 1){ qtyInput.value = q - 1; recalc(); }
  });

  plusBtn.addEventListener('click', () => {
    let q = clampQty();
    qtyInput.value = q + 1;
    recalc();
  });

  qtyInput.addEventListener('input', recalc);
  saleInp.addEventListener('input', recalc);
  saleInp.addEventListener('blur', recalc);

  recalc();
})();
</script>
@endsection


