@extends('frontend.layout_2')
@section('title', 'কিস্তি পরিশোধ')

@push('styles')
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css"/>

<style>
@media (prefers-reduced-motion:no-preference){ .press:active{ transform: translateY(1px); } }

/* layout */
.method-card{transition: box-shadow .18s ease, transform .18s ease, border-color .18s ease;cursor:pointer;    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;}
.method-card:hover{transform:translateY(-1px);box-shadow:0 10px 26px rgba(15,23,42,.10);}
.method-card.selected{border-color:#fb7185;box-shadow:0 14px 30px rgba(248,113,113,.25);}
.method-logo{width:46px;height:46px;border-radius:14px;background:#fff;display:flex;align-items:center;justify-content:center;overflow:hidden;box-shadow:inset 0 0 0 1px rgba(15,23,42,.06);}
.method-logo img{width:100%;height:100%;object-fit:contain}

/* Inputs */
.input{width:100%;border-radius:12px;border:1px solid #e5e7eb;background:#fff;padding:.65rem .9rem;font-size:15px;transition: box-shadow .15s ease, border-color .15s ease;}
.input:focus{outline:0;border-color:#fb7185;box-shadow:0 0 0 3px rgba(248,113,113,.18);}

/* taka icon */
.taka-icon{position:absolute;inset-block:0;left:.75rem;display:flex;align-items:center;color:#64748b;}
.taka-icon i{font-size:17px;}
.input.has-taka{padding-left:2.4rem;}

/* button */
.btn-primary{width:100%;border:none;border-radius:999px;background:linear-gradient(90deg,#e11d48,#f97373);color:#fff;font-weight:700;font-size:15px;padding:12px;margin-top:16px;box-shadow:0 12px 30px rgba(248,113,113,.35);transition:filter .18s ease,box-shadow .18s ease;}
.btn-primary:hover{filter:brightness(1.05);}
.btn-disabled{opacity:.55;cursor:not-allowed;box-shadow:none!important;}

.hint{font-size:12px;color:#6b7280;margin-top:4px;}
.err{font-size:12px;color:#dc2626;margin-top:4px;}
.copy-toast{position:fixed;left:50%;bottom:18px;transform:translateX(-50%) translateY(8px);opacity:0;pointer-events:none;transition:opacity .18s ease,transform .18s ease;}
.copy-toast.show{opacity:1;transform:translateX(-50%) translateY(0);}
</style>
@endpush

@section('sub_layout')
@php
    $oldMethod = old('method');

    $headerData = null;
    if ($oldMethod && str_starts_with($oldMethod, 'mobile:')) {
        $slug = substr($oldMethod, 7);
        $pm   = $mobileMethods->firstWhere('slug', $slug);
        if ($pm) {
            $headerData = [
                'type'    => 'mobile',
                'name'    => $pm->name,
                'logo'    => $pm->logo ?? null,
                'account' => $pm->account_number,
                'holder'  => null,
                'branch'  => null,
            ];
        }
    } elseif ($oldMethod && str_starts_with($oldMethod, 'bank:')) {
        $slug = substr($oldMethod, 5);
        $pm   = $bankMethods->firstWhere('slug', $slug);
        if ($pm) {
            $headerData = [
                'type'    => 'bank',
                'name'    => $pm->bank_name,
                'logo'    => $pm->logo ?? null,
                'account' => $pm->account_number,
                'holder'  => $pm->account_holder,
                'branch'  => $pm->branch_name,
            ];
        }
    }

    $headerLogo = '';
    if($headerData && !empty($headerData['logo'])){
        $headerLogo = preg_match('/^(https?:\/\/|\/)/i', $headerData['logo'])
            ? $headerData['logo']
            : asset('storage/'.$headerData['logo']);
    }
@endphp

<div class="mx-auto max-w-2xl px-4 py-6" style="margin-bottom: 100px;">
  <div class="rounded-2xl bg-white/90 backdrop-blur p-6 shadow-lg ring-1 ring-black/5">

    {{-- Loan summary --}}
    <div class="grid grid-cols-1 gap-3 sm:grid-cols-2 mb-5">
      <div class="flex items-center gap-3 rounded-xl border border-slate-100 bg-white p-3 shadow-sm">
        <span class="inline-flex h-10 w-10 items-center justify-center rounded-xl bg-sky-100 text-sky-600">
          <i class="fa-solid fa-hashtag"></i>
        </span>
        <div>
          <div class="text-xs text-slate-500">Loan</div>
          <div class="text-[15px] font-bold text-slate-900">#{{ $loan->id }}</div>
        </div>
      </div>
      <div class="flex items-center gap-3 rounded-xl border border-slate-100 bg-white p-3 shadow-sm">
        <span class="inline-flex h-10 w-10 items-center justify-center rounded-xl bg-emerald-100 text-emerald-600">
          <i class="fa-solid fa-sack-dollar"></i>
        </span>
        <div>
          <div class="text-xs text-slate-500">Installment Amount</div>
          <div class="text-[15px] font-bold text-slate-900">৳ {{ number_format($amount) }}</div>
        </div>
      </div>
      <div class="flex items-center gap-3 rounded-xl border border-slate-100 bg-white p-3 shadow-sm sm:col-span-2">
        <span class="inline-flex h-10 w-10 items-center justify-center rounded-xl bg-violet-100 text-violet-600">
          <i class="fa-regular fa-calendar"></i>
        </span>
        <div>
          <div class="text-xs text-slate-500">Due date</div>
          <div class="text-[15px] font-bold text-slate-900">{{ $installment->due_date->format('d M Y') }}</div>
        </div>
      </div>
    </div>

    

    {{-- নির্দেশনা --}}
    <div class="mt-3 rounded-xl border border-amber-200 bg-amber-50 px-3 py-3 text-[13px] text-amber-800">
      <span class="inline-flex items-center gap-2 font-semibold">
        <i class="fa-solid fa-circle-info"></i> নির্দেশনা
      </span>
      <div class="mt-1">
        প্রথমে নির্বাচিত Mobile / Bank মেথডে <strong>Send Money / Bank Transfer</strong> করুন, তারপর নিচে Transaction ID ও Amount দিন।
      </div>
    </div>


    {{-- HEADER: selected method + account info (deposit-style) --}}
    <div class="flex items-center gap-3 mb-3 mt-4">
      <span class="inline-flex h-12 w-12 items-center justify-center overflow-hidden rounded-xl ring-1 ring-slate-200 bg-white">
        @if($headerLogo)
          <img id="header-logo" src="{{ $headerLogo }}" alt="{{ $headerData['name'] ?? 'Method' }}" class="h-full w-full object-contain">
        @else
          <i id="header-logo-icon" class="fa-regular fa-credit-card text-slate-300 text-xl"></i>
        @endif
      </span>
      <div>
        <div class="text-xs text-slate-500">Payment Method</div>
        <div id="header-method-name" class="text-lg font-extrabold text-slate-900">
          {{ $headerData['name'] ?? 'একটি পেমেন্ট মেথড নির্বাচন করুন' }}
        </div>
      </div>
      <span class="ms-auto inline-flex items-center gap-1 rounded-full bg-emerald-50 px-2.5 py-1 text-[11px] font-semibold text-emerald-700 ring-1 ring-emerald-100">
        <i class="fa-solid fa-shield-halved"></i> Secure
      </span>
    </div>

    {{-- account card --}}
    <div id="account-card"
         class="mt-2 rounded-xl border border-slate-200 bg-gradient-to-r from-slate-50 to-slate-100/70 p-3 shadow-sm"
         style="{{ $headerData ? '' : 'display:none;' }}">
      <div class="flex items-start gap-2">
        <div class="flex-1 min-w-0">
          <div id="account-type-label" class="text-xs text-slate-500">
            @if($headerData)
              {{ $headerData['type'] === 'bank' ? 'Bank Account' : 'Mobile Account' }}
            @else
              Account
            @endif
          </div>

          <div class="mt-0.5 flex items-center gap-2">
            <div id="account-number" class="truncate text-[17px] font-extrabold tracking-wide text-slate-900">
              {{ $headerData['account'] ?? '' }}
            </div>
          </div>

          <div id="account-holder-row"
               class="mt-1 text-[12px] text-slate-700"
               style="{{ $headerData && $headerData['type']==='bank' && $headerData['holder'] ? '' : 'display:none;' }}">
            <i class="fa-solid fa-user text-[11px] mr-1 text-slate-400"></i>
            <span class="font-medium">Account holder:</span>
            <span id="account-holder">{{ $headerData['holder'] ?? '' }}</span>
          </div>

          <div id="branch-row"
               class="mt-0.5 text-[12px] text-slate-700"
               style="{{ $headerData && $headerData['type']==='bank' && $headerData['branch'] ? '' : 'display:none;' }}">
            <i class="fa-solid fa-building-columns text-[11px] mr-1 text-slate-400"></i>
            <span class="font-medium">Branch:</span>
            <span id="branch-name">{{ $headerData['branch'] ?? '' }}</span>
          </div>
        </div>

        <button type="button"
                id="copy-account-btn"
                class="ms-auto inline-flex items-center gap-1.5 rounded-full border border-slate-300 bg-white px-3 py-1.5 text-xs font-semibold text-slate-700 hover:bg-slate-50 focus:outline-none">
          <i class="fa-regular fa-copy"></i> Copy
        </button>
      </div>
    </div>
    {{-- FORM --}}
    <form id="payForm" action="{{ route('loan.installments.pay.store', $installment) }}" method="POST" novalidate>
      @csrf

      {{-- Methods --}}
      <div class="mt-4">
        <div class="text-sm font-semibold text-slate-700 mb-1">পেমেন্ট মেথড সিলেক্ট করুন</div>

        @if($mobileMethods->count())
          <div class="text-xs text-slate-500 mb-1">Mobile Banking</div>
          <div class="grid grid-cols-3 gap-3 mb-3">
            @foreach($mobileMethods as $m)
              @php
                  $value   = 'mobile:'.$m->slug;
                  $logoRaw = $m->logo;
                  $logoUrl = $logoRaw ? (preg_match('/^(https?:\/\/|\/)/i', $logoRaw) ? $logoRaw : asset('storage/'.$logoRaw)) : '';
                  $checked = $oldMethod === $value;
              @endphp
              <label class="method-card rounded-xl border border-slate-200 bg-white p-3 text-center {{ $checked ? 'selected' : '' }}"
                     data-key="{{ $value }}"
                     data-type="mobile"
                     data-name="{{ $m->name }}"
                     data-account="{{ $m->account_number }}"
                     data-holder=""
                     data-branch=""
                     data-logo="{{ $logoUrl }}">
                <span class="method-logo mb-1">
                  @if($logoUrl)
                    <img src="{{ $logoUrl }}" alt="{{ $m->name }}">
                  @else
                    <i class="fa-solid fa-mobile-screen-button" style="font-size:20px;color:#0ea5e9"></i>
                  @endif
                </span>
                <span class="block text-[12.5px] font-semibold text-slate-800">{{ $m->name }}</span>
                <input type="radio" name="method" value="{{ $value }}" style="display:none" {{ $checked ? 'checked' : '' }}>
              </label>
            @endforeach
          </div>
        @endif

        @if($bankMethods->count())
          <div class="text-xs text-slate-500 mb-1 mt-1">Bank Transfer</div>
          <div class="grid grid-cols-3 gap-3">
            @foreach($bankMethods as $b)
              @php
                  $value   = 'bank:'.$b->slug;
                  $logoRaw = $b->logo;
                  $logoUrl = $logoRaw ? (preg_match('/^(https?:\/\/|\/)/i', $logoRaw) ? $logoRaw : asset('storage/'.$logoRaw)) : '';
                  $checked = $oldMethod === $value;
              @endphp
              <label class="method-card rounded-xl border border-slate-200 bg-white p-3 text-center {{ $checked ? 'selected' : '' }}"
                     data-key="{{ $value }}"
                     data-type="bank"
                     data-name="{{ $b->bank_name }}"
                     data-account="{{ $b->account_number }}"
                     data-holder="{{ $b->account_holder }}"
                     data-branch="{{ $b->branch_name }}"
                     data-logo="{{ $logoUrl }}">
                <span class="method-logo mb-1">
                  @if($logoUrl)
                    <img src="{{ $logoUrl }}" alt="{{ $b->bank_name }}">
                  @else
                    <i class="fa-solid fa-building-columns" style="font-size:20px;color:#6366f1"></i>
                  @endif
                </span>
                <span class="block text-[12.5px] font-semibold text-slate-800">{{ $b->bank_name }}</span>
                <input type="radio" name="method" value="{{ $value }}" style="display:none" {{ $checked ? 'checked' : '' }}>
              </label>
            @endforeach
          </div>
        @endif

        @error('method') <div class="err">{{ $message }}</div> @enderror
      </div>

      {{-- Amount --}}
      <div class="mt-4">
        <label class="mb-1 block text-sm font-semibold text-slate-700">Amount (BDT)</label>
        <div class="relative">
          <span class="taka-icon"><i class="fa-solid fa-bangladeshi-taka-sign"></i></span>
          <input type="number"
                 name="amount"
                 class="input has-taka"
                 value="{{ old('amount', $amount) }}"
                 min="{{ $amount }}" step="1" required>
        </div>
        <div class="hint">কমপক্ষে {{ number_format($amount) }} টাকা দিতে হবে।</div>
        @error('amount') <div class="err">{{ $message }}</div> @enderror
      </div>

      {{-- TRX ID --}}
      <div class="mt-3">
        <label class="mb-1 block text-sm font-semibold text-slate-700">Transaction ID</label>
        <div class="relative">
          <span class="taka-icon"><i class="fa-solid fa-barcode"></i></span>
          <input id="trx" type="text" name="transaction_id"
                 class="input has-taka"
                 value="{{ old('transaction_id') }}"
                 placeholder="e.g. 8J3K4L5M6" required>
          <button type="button" id="pasteBtn"
                  class="press absolute right-2 top-1/2 -translate-y-1/2 inline-flex items-center gap-1 rounded-full border border-slate-200 bg-white px-3 py-1.5 text-xs font-semibold text-slate-700 hover:bg-slate-50">
            <i class="fa-solid fa-clipboard"></i> Paste
          </button>
        </div>
        <div class="hint">Mobile / Bank SMS থেকে প্রাপ্ত ট্রানজ্যাকশন আইডি লিখুন।</div>
        @error('transaction_id') <div class="err">{{ $message }}</div> @enderror
      </div>

      @php $hasOldMethod = !empty($oldMethod); @endphp
      <button id="submitBtn"
              type="submit"
              class="btn-primary {{ $hasOldMethod ? '' : 'btn-disabled' }}"
              {{ $hasOldMethod ? '' : 'disabled' }}>
        <i class="fa-solid fa-paper-plane"></i>
        কিস্তি জমা করুন
      </button>
    </form>
  </div>
</div>

<div id="copy-toast" class="copy-toast z-50 rounded-full bg-black/85 px-3 py-2 text-xs font-semibold text-white">
  Copied!
</div>
@endsection

@push('scripts')
<script>
(function(){
  const cards       = document.querySelectorAll('.method-card');
  const submitBtn   = document.getElementById('submitBtn');
  const accCard     = document.getElementById('account-card');
  const accTypeEl   = document.getElementById('account-type-label');
  const accNumEl    = document.getElementById('account-number');
  const holderRow   = document.getElementById('account-holder-row');
  const holderEl    = document.getElementById('account-holder');
  const branchRow   = document.getElementById('branch-row');
  const branchEl    = document.getElementById('branch-name');
  const headerName  = document.getElementById('header-method-name');
  const logoImg     = document.getElementById('header-logo');
  const logoIcon    = document.getElementById('header-logo-icon');
  const copyBtn     = document.getElementById('copy-account-btn');
  const toast       = document.getElementById('copy-toast');

  function enableSubmit(){
    if(!submitBtn) return;
    submitBtn.disabled = false;
    submitBtn.classList.remove('btn-disabled');
  }

  function updateHeader(card){
    if(!card) return;
    const d = card.dataset;
    const type    = d.type || 'mobile';
    const name    = d.name || 'Payment method';
    const account = d.account || '';

    headerName.textContent = name;
    accNumEl.textContent   = account;

    if(type === 'bank'){
      accTypeEl.textContent = 'Bank Account';
      if(d.holder){
        holderEl.textContent  = d.holder;
        holderRow.style.display = 'block';
      }else{
        holderRow.style.display = 'none';
      }

      if(d.branch){
        branchEl.textContent  = d.branch;
        branchRow.style.display = 'block';
      }else{
        branchRow.style.display = 'none';
      }
    }else{
      accTypeEl.textContent = 'Mobile Account';
      holderRow.style.display = 'none';
      branchRow.style.display = 'none';
    }

    if(d.logo){
      if(logoImg){
        logoImg.src = d.logo;
        logoImg.style.display = 'block';
      }
      if(logoIcon){
        logoIcon.style.display = 'none';
      }
    }else{
      if(logoImg){ logoImg.style.display = 'none'; }
      if(logoIcon){ logoIcon.style.display = 'block'; }
    }

    if(accCard){ accCard.style.display = 'block'; }
  }

  cards.forEach(card=>{
    const selectCard = ()=>{
      cards.forEach(c=>c.classList.remove('selected'));
      card.classList.add('selected');
      const radio = card.querySelector('input[type=radio]');
      if(radio){
        radio.checked = true;
      }
      enableSubmit();
      updateHeader(card);
    };
    card.addEventListener('click', selectCard);
    card.addEventListener('keydown', e=>{
      if(e.key==='Enter' || e.key===' '){
        e.preventDefault();
        selectCard();
      }
    });
  });

  // copy account number
  async function copyAccount(){
    if(!accNumEl) return;
    const text = accNumEl.textContent.trim();
    if(!text) return;
    try{
      if(navigator.clipboard && window.isSecureContext){
        await navigator.clipboard.writeText(text);
      }else{
        const ta = document.createElement('textarea');
        ta.value = text;
        document.body.appendChild(ta);
        ta.select();
        document.execCommand('copy');
        ta.remove();
      }
      if(toast){
        toast.textContent = 'Account number copied!';
        toast.classList.add('show');
        clearTimeout(window.__copy_to);
        window.__copy_to = setTimeout(()=>toast.classList.remove('show'), 1200);
      }
    }catch(e){ console.error(e); }
  }
  copyBtn?.addEventListener('click', copyAccount);

  // paste trx id
  document.getElementById('pasteBtn')?.addEventListener('click', async ()=>{
    try{
      if(navigator.clipboard && navigator.clipboard.readText){
        const txt = await navigator.clipboard.readText();
        if(txt){
          const input = document.getElementById('trx');
          if(input){
            input.value = txt.trim();
            if(toast){
              toast.textContent = 'Pasted!';
              toast.classList.add('show');
              clearTimeout(window.__copy_to);
              window.__copy_to = setTimeout(()=>toast.classList.remove('show'), 1200);
            }
          }
        }
      }
    }catch(e){ console.warn('Paste not allowed', e); }
  });

  // safety: prevent submit without method
  document.getElementById('payForm')?.addEventListener('submit', e=>{
    const checked = document.querySelector('input[name="method"]:checked');
    if(!checked){
      e.preventDefault();
      alert('অনুগ্রহ করে একটি পেমেন্ট মেথড সিলেক্ট করুন।');
    }
  });
})();
</script>
@endpush
