@extends('layouts.app')
@section('title','History')

@push('styles')
    {{-- Same fonts & blob animation as অন্য পেজগুলো --}}
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Hind+Siliguri:wght@400;500;600;700&family=Poppins:wght@400;500;600&display=swap" rel="stylesheet">

    <style>
        body {
            font-family: "Hind Siliguri", system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
        }

        @keyframes blobFloat {
            0%   { transform: translate3d(-10%, -10%, 0) scale(1); }
            50%  { transform: translate3d(15%, 10%, 0) scale(1.08); }
            100% { transform: translate3d(40%, -5%, 0) scale(1); }
        }

        @keyframes blobFloat2 {
            0%   { transform: translate3d(40%, 20%, 0) scale(1); }
            50%  { transform: translate3d(5%, 0, 0) scale(1.04); }
            100% { transform: translate3d(-20%, 10%, 0) scale(1); }
        }
    </style>
@endpush

@section('content')
@php
    $authUser = auth()->user();
@endphp

<div class="min-h-screen bg-gradient-to-b from-slate-950 via-slate-900 to-slate-950 flex justify-center items-start px-3 sm:px-4 py-8 relative overflow-hidden">

    {{-- animated blobs --}}
    <svg class="pointer-events-none absolute -top-32 -left-32 w-80 h-80 text-emerald-500/20"
         viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg"
         style="animation: blobFloat 18s ease-in-out infinite alternate;">
        <path fill="currentColor"
              d="M45.1,-62C58.8,-54.8,69.1,-39.4,73.4,-22.5C77.7,-5.7,75.9,12.7,67.4,26.8C58.8,40.9,43.4,50.7,27.2,58.2C11,65.7,-6,70.9,-20.4,66.3C-34.7,61.6,-46.4,47.1,-55.3,31.5C-64.3,15.9,-70.4,-0.7,-68.1,-16.7C-65.8,-32.7,-55.1,-48.1,-41.2,-55.6C-27.3,-63.1,-10.1,-62.6,5.7,-69C21.5,-75.3,43,-88.4,45.1,-62Z"/>
    </svg>

    <svg class="pointer-events-none absolute bottom-0 -right-24 w-72 h-72 text-cyan-400/10"
         viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg"
         style="animation: blobFloat2 22s ease-in-out infinite alternate;">
        <path fill="currentColor"
              d="M35.8,-54.7C46.3,-47.4,54,-38,60.9,-27.1C67.7,-16.2,73.7,-4.1,71.9,6.8C70.1,17.7,60.5,27.3,50.4,36.6C40.4,46,29.9,55.3,17.3,60.4C4.6,65.6,-10.1,66.6,-24.4,62.4C-38.7,58.3,-52.6,49.1,-59.8,36.3C-66.9,23.4,-67.3,7,-64.6,-8.3C-61.9,-23.6,-56.1,-37.9,-45.7,-45.9C-35.2,-53.9,-20.1,-55.7,-5.2,-49.9C9.7,-44,19.3,-30.5,35.8,-54.7Z"/>
    </svg>

    <main class="mx-auto w-full max-w-[720px] relative z-10 pb-24">

        {{-- top nav + All Statement button --}}
        <div class="mb-4 flex items-center justify-between text-xs text-slate-300">
            <button type="button"
                    onclick="window.history.back()"
                    class="inline-flex items-center gap-1 text-slate-300 hover:text-emerald-400 transition">
                <svg class="h-4 w-4" viewBox="0 0 24 24" fill="currentColor">
                    <path d="M15.75 4.75 9.5 11l6.25 6.25-1.5 1.5L6.5 11l7.75-7.75 1.5 1.5Z"/>
                </svg>
                Back
            </button>

            <div class="flex items-center gap-2">
                <a href="{{ route('statement.form') }}"
                   class="inline-flex items-center gap-1 rounded-full border border-emerald-500/50 bg-emerald-500/10 px-3 py-1.5 text-[11px] font-semibold text-emerald-200
                          shadow-[0_10px_30px_-18px_rgba(16,185,129,0.9)] hover:bg-emerald-500/20 transition">
                    <span class="h-1.5 w-1.5 rounded-full bg-emerald-400"></span>
                    All Statement
                </a>
                <span class="tracking-[0.18em] uppercase text-emerald-400 font-semibold text-[11px]">
                    History
                </span>
            </div>
        </div>

        {{-- glass card --}}
        <div class="rounded-3xl bg-slate-900/80 border border-emerald-500/25 shadow-[0_25px_70px_-35px_rgba(16,185,129,.7)] backdrop-blur-sm p-4 sm:p-6">

            {{-- Filters --}}
            <form method="get" class="grid grid-cols-1 gap-3 sm:grid-cols-3">
                <div class="relative sm:col-span-3">
                    <span class="pointer-events-none absolute left-4 top-1/2 -translate-y-1/2 text-slate-400">🔎</span>
                    <input
                        name="q" value="{{ $q }}"
                        placeholder="সার্চ (amount / type)"
                        class="w-full rounded-2xl border border-slate-800 bg-slate-950/70 pl-10 pr-12 py-2.5 text-sm text-slate-100 outline-none
                               shadow-[0_20px_60px_-28px_rgba(15,23,42,.9)]
                               ring-1 ring-emerald-500/20 focus:ring-2 focus:ring-emerald-500/40 placeholder-slate-500">
                    @if($q)
                        <button type="button" onclick="location.href='{{ route('history.index') }}'"
                                class="absolute right-3 top-1/2 -translate-y-1/2 rounded-xl bg-slate-800 px-2 py-1 text-xs text-slate-200 hover:bg-slate-700">
                            ক্লিয়ার
                        </button>
                    @endif
                </div>

                <div class="relative">
                    <select name="type"
                        class="w-full appearance-none rounded-2xl border border-slate-800 bg-slate-950/70 px-4 py-2.5 text-sm text-slate-100 outline-none
                               shadow-[0_18px_45px_-20px_rgba(15,23,42,.9)] ring-1 ring-emerald-500/20 focus:ring-2 focus:ring-emerald-500/40">
                        <option value="" class="text-slate-900">টাইপ: All</option>
                        <option value="credit" @selected($type==='credit') class="text-slate-900">ক্রেডিট</option>
                        <option value="debit"  @selected($type==='debit')  class="text-slate-900">ডেবিট</option>
                    </select>
                    <span class="pointer-events-none absolute right-3 top-1/2 -translate-y-1/2 text-slate-400">▾</span>
                </div>

                <div class="relative">
                    <select name="kind"
                        class="w-full appearance-none rounded-2xl border border-slate-800 bg-slate-950/70 px-4 py-2.5 text-sm text-slate-100 outline-none
                               shadow-[0_18px_45px_-20px_rgba(15,23,42,.9)] ring-1 ring-emerald-500/20 focus:ring-2 focus:ring-emerald-500/40">
                        @foreach($kinds as $key => $label)
                            <option value="{{ $key==='all'?'':$key }}" @selected($kind===$key) class="text-slate-900">{{ $label }}</option>
                        @endforeach
                    </select>
                    <span class="pointer-events-none absolute right-3 top-1/2 -translate-y-1/2 text-slate-400">▾</span>
                </div>

                <div class="flex items-stretch gap-2">
                    <button
                        class="flex-1 rounded-2xl bg-gradient-to-r from-emerald-500 to-cyan-500 px-4 py-2.5 text-sm font-semibold text-slate-950
                               shadow-[0_22px_55px_-25px_rgba(16,185,129,.9)] hover:from-emerald-400 hover:to-cyan-400">
                        ফিল্টার প্রয়োগ
                    </button>
                    @if(request()->hasAny(['q','type','kind']) && (request('q') || request('type') || request('kind')))
                        <a href="{{ route('history.index') }}"
                           class="rounded-2xl bg-slate-900/80 px-4 py-2.5 text-sm font-semibold text-slate-100 hover:bg-slate-800
                                  shadow-[0_18px_45px_-20px_rgba(15,23,42,.9)] ring-1 ring-emerald-500/20">
                            রিসেট
                        </a>
                    @endif
                </div>
            </form>

            {{-- List --}}
            <div class="mt-4 space-y-3">
                @forelse($tx as $t)
                    @php
                        $rt  = class_basename($t->related_type);
                        $rel = $t->related;
                        $isCredit = method_exists($t, 'isCredit') ? $t->isCredit() : ($t->type === 'credit');

                        // -------- meta safely decode --------
                        $rawMeta = $t->meta ?? [];
                        if (is_string($rawMeta)) {
                            $decoded = json_decode($rawMeta, true);
                            $meta = is_array($decoded) ? $decoded : [];
                        } elseif (is_array($rawMeta)) {
                            $meta = $rawMeta;
                        } else {
                            $meta = [];
                        }

                        $title    = 'লেনদেন';
                        $subtitle = '';
                        $icon     = '💸';

                        switch ($rt) {
                            case 'Deposit':
                                $title    = 'ডিপোজিট';
                                $subtitle = $rel ? ('রেফ: '.$rel->reference.' • '.$rel->status) : '';
                                $icon     = '📊';
                                break;

                            case 'Transfer':
                                $title = 'ট্রান্সফার';
                                $icon  = '📤';
                                if ($rel) {
                                    $who = $isCredit
                                        ? ($rel->fromUser->name ?? 'Unknown')
                                        : ($rel->toUser->name ?? 'Unknown');
                                    $subtitle = ($isCredit ? 'From: ' : 'To: ').$who;
                                }
                                break;

                            case 'Purchase':
                                $title = 'অফার পারচেজ';
                                $subtitle = $rel
                                    ? (($rel->offer->title ?? '').($rel->msisdn ? ' • '.$rel->msisdn : ''))
                                    : '';
                                $icon = '🛒';
                                break;

                            case 'Recharge':
                                $title    = 'মোবাইল রিচার্জ';
                                $subtitle = $rel ? ($rel->service_type.' • '.$rel->msisdn) : '';
                                $icon     = '📶';
                                break;

                            case 'BillPayment':
                                $title    = 'বিল পেমেন্ট';
                                $subtitle = $rel ? (($rel->biller->name ?? '').' • '.$rel->account_no) : '';
                                $icon     = '🧾';
                                break;

                            case 'RewardConversion':
                                $title    = 'রিওয়ার্ড';
                                $subtitle = $rel ? ('পয়েন্ট: '.$rel->points) : '';
                                $icon     = '🏅';
                                break;

                            case 'MobileTransaction':
                                $title    = 'মোবাইল ট্রান্সাকশন';
                                $subtitle = $rel ? ($rel->channel.' • '.$rel->account_number) : '';
                                $icon     = '📲';
                                break;

                            case 'BankTransfer':
                                $title    = 'ব্যাংক ট্রান্সফার';
                                $subtitle = $rel ? (($rel->bank->name ?? '').' • '.$rel->account_number) : '';
                                $icon     = '🏦';
                                break;

                            case 'LoanApplication':
                                $title    = 'লোন';
                                $subtitle = $rel ? ('মেয়াদ: '.$rel->loan_period.'মাস • '.$rel->status) : '';
                                $icon     = '💳';
                                break;
                        }

                        // meta override / extras
                        $trxType     = $meta['trx_type']    ?? null;
                        $title       = $trxType ?: $title;
                        $statusText  = $meta['status']      ?? ($rel->status ?? 'Success');

                        // এখানে ফিক্স: admin_note আগে নিয়ে আসছি
                        $adminNote   = $meta['admin_note']  ?? ($rel->admin_note ?? '');

                        $charge      = $meta['charge']      ?? 0;

                        // Last Number এ admin note দেখাবো; admin note না থাকলে পুরনো last_number/fallback
                        $lastNumber  = $adminNote ?: ($meta['last_number'] ?? null);

                        $listDetails = $meta['details']     ?? (trim($subtitle) ?: 'N/A');
                        $duration    = $meta['duration']    ?? '00:16';

                        // meta key/value গুলো string বানাচ্ছি (Details এর জন্য)
                        $metaPairs = [];
                        foreach ($meta as $k => $v) {
                            if ($v === null || $v === '') {
                                continue;
                            }
                            $label = ucwords(str_replace('_',' ', $k));
                            if (is_scalar($v)) {
                                $metaPairs[] = $label . ': ' . $v;
                            } else {
                                $metaPairs[] = $label . ': ' . json_encode($v, JSON_UNESCAPED_UNICODE);
                            }
                        }
                        // সব meta না থাকলে কমপক্ষে listDetails থাকুক
                        $metaText = $metaPairs ? implode(' • ', $metaPairs) : $listDetails;

                        // fallback last number (admin note না থাকলে + meta তেও না থাকলে)
                        if (!$lastNumber) {
                            if ($rt === 'BankTransfer' && $rel?->account_number) {
                                $digits     = preg_replace('/\D/', '', $rel->account_number);
                                $lastNumber = $digits ? '****'.substr($digits, -4) : 'N/A';
                            } elseif ($rt === 'MobileTransaction' && $rel?->account_number) {
                                $digits     = preg_replace('/\D/', '', $rel->account_number);
                                $lastNumber = $digits ? '****'.substr($digits, -4) : 'N/A';
                            } elseif ($rt === 'Recharge' && $rel?->msisdn) {
                                $digits     = preg_replace('/\D/', '', $rel->msisdn);
                                $lastNumber = $digits ? '****'.substr($digits, -4) : 'N/A';
                            } else {
                                $lastNumber = 'N/A';
                            }
                        }

                        $rightBadge      = $isCredit ? 'ক্রেডিট' : 'ডেবিট';
                        $rightBadgeClass = $isCredit ? 'bg-emerald-500/15 text-emerald-200'
                                                     : 'bg-rose-500/15 text-rose-200';

                        $accountNo = $authUser?->phone ?? $authUser?->email ?? 'N/A';

                        $newBalance  = $t->balance_after ?? 0;
                        $oldBalance  = $newBalance;
                        if ($t->balance_after !== null) {
                            $oldBalance = $isCredit
                                ? $t->balance_after - $t->amount
                                : $t->balance_after + $t->amount;
                        }
                    @endphp

                    {{-- LIST ITEM --}}
                    <button type="button"
                            class="w-full text-left flex items-center justify-between rounded-2xl bg-slate-900/80 p-3
                                   shadow-[0_26px_70px_-26px_rgba(15,23,42,.9)]
                                   ring-1 ring-emerald-500/15 js-tx-open hover:ring-emerald-400/40 hover:shadow-[0_30px_80px_-30px_rgba(16,185,129,0.9)] transition"
                            data-title="{{ $title }}"
                            data-amount="{{ number_format($t->amount,2) }}"
                            data-sign="{{ $isCredit ? '+' : '-' }}"
                            data-type="{{ $isCredit ? 'credit' : 'debit' }}"
                            data-status="{{ $statusText }}"
                            data-account="{{ $accountNo }}"
                            data-trx="{{ $meta['reference_code'] ?? ('TX-'.$t->id) }}"
                            data-time="{{ $t->created_at->format('d M Y  H:i') }}"
                            data-oldbalance="{{ number_format($oldBalance,2) }}"
                            data-newbalance="{{ number_format($newBalance,2) }}"
                            data-balance="{{ number_format($newBalance,2) }}"
                            data-details="{{ $metaText }}"
                            data-charge="{{ number_format($charge,2) }}"
                            data-lastnumber="{{ $lastNumber }}"
                            data-duration="{{ $duration }}"
                            data-adminnote="{{ $adminNote }}"
                    >
                        <div class="flex items-center gap-3 min-w-0">
                            <div class="grid h-11 w-11 place-items-center rounded-2xl bg-emerald-500/10 text-lg ring-1 ring-emerald-500/30 text-emerald-300">
                                {{ $icon }}
                            </div>
                            <div class="min-w-0">
                                <div class="truncate text-[15px] font-bold text-slate-50">{{ $title }}</div>
                                <div class="truncate text-[11px] text-slate-400">
                                    {{ $listDetails }}
                                    <span class="mx-1 text-slate-600">•</span>
                                    <span>{{ $t->created_at->format('d M, h:i A') }}</span>
                                </div>
                            </div>
                        </div>
                        <div class="shrink-0 text-right">
                            <div class="text-sm font-extrabold {{ $isCredit ? 'text-emerald-300' : 'text-rose-300' }}">
                                {{ $isCredit ? '+' : '-' }}৳{{ number_format($t->amount,2) }}
                            </div>
                            <div class="mt-1 inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-[10px] font-semibold {{ $rightBadgeClass }}">
                                <span class="inline-block h-1.5 w-1.5 rounded-full {{ $isCredit ? 'bg-emerald-400' : 'bg-rose-400' }}"></span>
                                {{ $rightBadge }}
                            </div>
                        </div>
                    </button>
                @empty
                    <div class="rounded-2xl bg-slate-900/80 p-6 text-center text-slate-400
                                shadow-[0_26px_70px_-26px_rgba(15,23,42,.9)] ring-1 ring-emerald-500/15">
                        এখনো কোনো হিস্টোরি নেই।
                    </div>
                @endforelse
            </div>

            <div class="mt-4 text-slate-300">
                {{ $tx->links() }}
            </div>
        </div>
    </main>
</div>

{{-- Backdrop --}}
<div id="tx-modal-backdrop"
     class="fixed inset-0 z-40 hidden bg-black/40 backdrop-blur-[1px]"></div>

{{-- Bottom-sheet / Center modal (responsive) --}}
<div style="margin-bottom: 70px;" id="tx-modal"
     class="fixed inset-0 z-50 hidden flex items-end sm:items-center justify-center px-2 sm:px-4 pb-2 sm:pb-6">
  <div class="w-full max-w-[720px]">
    <div class="rounded-t-3xl sm:rounded-3xl bg-white shadow-[0_-18px_60px_-24px_rgba(15,23,42,.55)]
                max-h-[85vh] flex flex-col overflow-hidden">

      {{-- Header --}}
      <div class="flex items-center justify-between px-4 pt-3 pb-2 border-b border-slate-300 flex-none">
        <span id="tx-modal-title" class="text-sm font-semibold text-slate-900">Transaction</span>
        <button id="tx-modal-close" class="text-xs font-semibold text-rose-500 hover:text-rose-600">
          Cancel
        </button>
      </div>

      {{-- Body --}}
      <div class="relative px-3 sm:px-4 pb-4 pt-3 text-xs sm:text-sm text-slate-900 overflow-y-auto flex-1">
        <div class="grid grid-cols-1 sm:grid-cols-2 border border-slate-300 text-[11px] sm:text-xs">
          {{-- Row 1 --}}
          <div class="border-b sm:border-r border-slate-300 px-3 py-2">
            <p class="text-[10px] text-slate-500 mb-1">Account</p>
            <p id="tx-modal-account" class="text-sm font-semibold text-slate-900 break-all">N/A</p>
          </div>
          <div class="border-b border-slate-300 px-3 py-2 text-left sm:text-right">
            <p class="text-[10px] text-slate-500 mb-1">Balance</p>
            <p id="tx-modal-balance" class="text-sm font-semibold text-slate-900">৳0.00</p>
          </div>

          {{-- Row 2 --}}
          <div class="border-b sm:border-r border-slate-300 px-3 py-2">
            <p class="text-[10px] text-slate-500 mb-1">Transaction ID</p>
            <p id="tx-modal-trx" class="font-semibold text-slate-900 break-all">N/A</p>
          </div>
          <div class="border-b border-slate-300 px-3 py-2 text-left sm:text-right">
            <p class="text-[10px] text-slate-500 mb-1">Old Balance</p>
            <p id="tx-modal-oldbalance" class="font-semibold text-slate-900">৳0.00</p>
          </div>

          {{-- Row 3 --}}
          <div class="border-b sm:border-r border-slate-300 px-3 py-2">
            <p class="text-[10px] text-slate-500 mb-1">Time</p>
            <p id="tx-modal-time" class="font-semibold text-slate-900">N/A</p>
          </div>
          <div class="border-b border-slate-300 px-3 py-2 text-left sm:text-right">
            <p class="text-[10px] text-slate-500 mb-1">Charge</p>
            <p id="tx-modal-charge" class="font-semibold text-slate-900">0</p>
          </div>

          {{-- Row 4 --}}
          <div class="border-b sm:border-r border-slate-300 px-3 py-2">
            <p class="text-[10px] text-slate-500 mb-1">Last Number</p>
            <p id="tx-modal-lastnumber" class="font-semibold text-slate-900 break-all">N/A</p>
          </div>
          <div class="border-b border-slate-300 px-3 py-2 text-left sm:text-right">
            <p class="text-[10px] text-slate-500 mb-1">New Balance</p>
            <p id="tx-modal-newbalance" class="font-semibold text-slate-900">৳0.00</p>
          </div>

          {{-- Row 5 --}}
          <div class="border-b sm:border-r border-slate-300 px-3 py-2">
            <p class="text-[10px] text-slate-500 mb-1">Details (Meta)</p>
            <p id="tx-modal-details" class="font-semibold text-slate-900 whitespace-pre-line break-words">N/A</p>
          </div>
          <div class="border-b border-slate-300 px-3 py-2 text-left sm:text-right">
            <p class="text-[10px] text-slate-500 mb-1">Status</p>
            <p id="tx-modal-status" class="font-semibold text-emerald-600">Success</p>
          </div>

          {{-- Row 6 - Admin Note (full width) --}}
          <div class="px-3 py-2 border-t border-slate-300 col-span-1 sm:col-span-2">
            <p class="text-[10px] text-slate-500 mb-1">Admin Note</p>
            <p id="tx-modal-admin-note" class="font-semibold text-slate-900 whitespace-pre-line break-words">N/A</p>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

{{-- JS --}}
<script>
document.addEventListener('DOMContentLoaded', function () {
    const modal     = document.getElementById('tx-modal');
    const backdrop  = document.getElementById('tx-modal-backdrop');
    const closeBtn  = document.getElementById('tx-modal-close');

    const fields = {
        title:       document.getElementById('tx-modal-title'),
        account:     document.getElementById('tx-modal-account'),
        balance:     document.getElementById('tx-modal-balance'),
        trx:         document.getElementById('tx-modal-trx'),
        time:        document.getElementById('tx-modal-time'),
        charge:      document.getElementById('tx-modal-charge'),
        lastnumber:  document.getElementById('tx-modal-lastnumber'),
        oldbalance:  document.getElementById('tx-modal-oldbalance'),
        newbalance:  document.getElementById('tx-modal-newbalance'),
        details:     document.getElementById('tx-modal-details'),
        status:      document.getElementById('tx-modal-status'),
        adminNote:   document.getElementById('tx-modal-admin-note'),
    };

    function openModal(el) {
        if (!el) return;
        const d = el.dataset;

        fields.title.textContent      = d.title || 'Transaction';
        fields.account.textContent    = d.account || 'N/A';
        fields.balance.textContent    = d.balance ? '৳' + d.balance : '৳0.00';
        fields.trx.textContent        = d.trx || 'N/A';
        fields.time.textContent       = d.time || 'N/A';
        fields.charge.textContent     = d.charge ?? '0';
        fields.lastnumber.textContent = d.lastnumber || 'N/A';
        fields.oldbalance.textContent = d.oldbalance ? '৳' + d.oldbalance : '৳0.00';
        fields.newbalance.textContent = d.newbalance ? '৳' + d.newbalance : '৳0.00';
        fields.details.textContent    = d.details || 'N/A';

        const s = (d.status || 'Success').toLowerCase();
        fields.status.textContent = d.status || 'Success';
        let cls = 'font-semibold ';
        if (s === 'success' || s === 'approved' || s === 'succeeded') {
            cls += 'text-emerald-600';
        } else if (s === 'pending') {
            cls += 'text-amber-500';
        } else {
            cls += 'text-rose-500';
        }
        fields.status.className = cls;

        // Admin note (special)
        fields.adminNote.textContent = d.adminnote && d.adminnote.trim() !== '' ? d.adminnote : 'N/A';

        modal.classList.remove('hidden');
        backdrop.classList.remove('hidden');
    }

    function closeModal() {
        modal.classList.add('hidden');
        backdrop.classList.add('hidden');
    }

    document.querySelectorAll('.js-tx-open').forEach(btn => {
        btn.addEventListener('click', () => openModal(btn));
    });

    closeBtn.addEventListener('click', closeModal);
    backdrop.addEventListener('click', closeModal);

    // ESC press to close
    document.addEventListener('keydown', (e) => {
        if (e.key === 'Escape') {
            closeModal();
        }
    });
});
</script>
@endsection
