@extends('backend.master')

@push('styles')
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css" crossorigin="anonymous" referrerpolicy="no-referrer" />
<style>
:root{--gap:12px;--border:#e9ecef;--muted:#6c757d;}
.card{border-radius:12px;}
.card-header{border-bottom:1px solid var(--border);}
.table thead th{font-weight:600;text-transform:uppercase;font-size:12px;letter-spacing:.04em;border-bottom:2px solid var(--border)!important;}
.table td{vertical-align:middle;}
.badge{padding:.5em .65em;font-weight:600;}
.btn-soft{border:1px solid rgba(0,0,0,.08);background:#fff;box-shadow:0 1px 2px rgba(0,0,0,.04);}
.btn-soft:hover{box-shadow:0 2px 6px rgba(0,0,0,.08);}
.td-actions{white-space:normal;}
.td-actions .btn{margin-bottom:6px;}
.filters-wrap{display:grid;grid-template-columns:1fr auto;gap:var(--gap);}
.filters-title{display:flex;align-items:center;gap:10px;}
.filter-toggle{display:inline-flex;align-items:center;gap:8px;border:1px solid var(--border);border-radius:8px;padding:6px 10px;background:#fff;cursor:pointer;}
.filter-toggle .fa{font-size:14px;}
.filters{grid-column:1 / -1;display:grid;gap:var(--gap);background:#f8f9fa;border:1px solid var(--border);border-radius:10px;padding:10px;transition:max-height .25s ease,opacity .2s ease;overflow:hidden;max-height:0;opacity:0;}
.filters.open{max-height:300px;opacity:1;}
.filters-grid{display:grid;gap:var(--gap);}
.filters-grid .input-group-text{background:#fff;}
@media (min-width:768px){
  .filters-wrap{grid-template-columns:auto 1fr;}
  .filter-toggle{display:none;}
  .filters{grid-column:2 / 3;display:grid;background:transparent;border:none;padding:0;max-height:none;opacity:1;overflow:visible;}
  .filters-grid{grid-auto-flow:column;grid-auto-columns:max-content;align-items:center;gap:var(--gap);}
  .filters-grid .form-select,
  .filters-grid .form-control{width:220px;}
  .filters-grid .input-group{width:280px;}
}
/* modal */
.cmodal{position:fixed;inset:0;z-index:1090;display:none;align-items:center;justify-content:center;}
.cmodal.show{display:flex;}
.cmodal .cm-backdrop{position:absolute;inset:0;background:rgba(10,12,16,.55);backdrop-filter:blur(2px);}
.cmodal .cm-dialog{position:relative;z-index:1;width:min(620px,calc(100% - 32px));border-radius:14px;background:#fff;box-shadow:0 20px 60px rgba(0,0,0,.25);overflow:hidden;transform:translateY(16px) scale(.98);opacity:0;transition:transform .18s ease,opacity .18s ease;}
.cmodal.show .cm-dialog{transform:translateY(0) scale(1);opacity:1;}
.cm-header{padding:14px 18px;border-bottom:1px solid #edf1f5;display:flex;align-items:center;gap:10px;}
.cm-title{font-size:18px;font-weight:700;margin:0;display:flex;align-items:center;gap:10px;}
.cm-title .fa-circle-check{color:#198754;}
.cm-title .fa-triangle-exclamation{color:#dc3545;}
.cm-body{padding:18px;}
.cm-footer{padding:14px 18px;border-top:1px solid #edf1f5;display:flex;justify-content:flex-end;gap:10px;}
.cm-close{margin-left:auto;appearance:none;border:0;background:transparent;font-size:22px;line-height:1;padding:0 6px;cursor:pointer;color:var(--muted);}
.cm-close:hover{color:#111;transform:scale(1.05);}
.cm-btn{border:0;border-radius:10px;padding:9px 14px;cursor:pointer;font-weight:600;}
.cm-btn.light{background:#f1f3f5;color:#111;}
.cm-btn.success{background:#198754;color:#fff;}
.cm-btn.danger{background:#dc3545;color:#fff;}
.cm-help{color:var(--muted);font-size:12.5px;}
.cm-label{font-size:12px;color:var(--muted);text-transform:uppercase;letter-spacing:.05em;margin-bottom:2px;}
.cm-value{font-size:13px;font-weight:500;}
.cm-mono{font-family:SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace;}
</style>
@endpush

@section('content')
<div class="container py-4">
  <div class="card shadow-sm border-0">
    <div class="card-header bg-white">
      <div class="filters-wrap">
        <h5 class="filters-title mb-0">
          <i class="fa-regular fa-credit-card me-2"></i> Card Add Money Requests
        </h5>

        <button type="button" class="filter-toggle" id="filterToggle" aria-expanded="false" aria-controls="filters">
          <i class="fa-solid fa-filter"></i> Filters
        </button>

        <form id="filters" method="get" class="filters {{ request()->hasAny(['status','q']) ? 'open' : '' }}">
          <div class="filters-grid">
            <select name="status" class="form-select form-select-sm" onchange="this.form.submit()">
              <option value="">All statuses</option>
              <option value="pending"  @selected(request('status')==='pending')>Pending</option>
              <option value="approved" @selected(request('status')==='approved')>Approved</option>
              <option value="rejected" @selected(request('status')==='rejected')>Rejected</option>
            </select>

            <div class="input-group input-group-sm">
              <span class="input-group-text"><i class="fa-solid fa-magnifying-glass"></i></span>
              <input type="text" name="q" class="form-control" value="{{ request('q') }}"
                     placeholder="Search ref / user / card brand / holder">
            </div>

            <button class="btn btn-sm btn-primary" type="submit">
              <i class="fa-solid fa-filter me-1"></i>
              <span class="d-none d-md-inline">Apply</span>
              <span class="d-md-none">Go</span>
            </button>

            @if(request()->hasAny(['status','q']))
              <a href="{{ route('admin.card-deposits.index') }}" class="btn btn-sm btn-soft">
                <i class="fa-solid fa-rotate-left me-1"></i> Reset
              </a>
            @endif
          </div>
        </form>
      </div>
    </div>

    <div class="card-body">
      @if(session('ok'))
        <div class="alert alert-success mb-3">
          <i class="fa-solid fa-circle-check me-1"></i>{{ session('ok') }}
        </div>
      @endif

      @if ($errors->any())
        <div class="alert alert-danger mb-3">
          <strong><i class="fa-solid fa-triangle-exclamation me-1"></i>Validation error:</strong>
          <ul class="mb-0">
            @foreach ($errors->all() as $e)
              <li>{{ $e }}</li>
            @endforeach
          </ul>
        </div>
      @endif

      <div class="table-responsive">
        <table class="table align-middle">
          <thead>
          <tr>
            <th>#</th>
            <th>User</th>
            <th>Amount</th>
            <th>Card</th>
            <th>Holder</th>
            <th>Reference</th>
            <th>Status</th>
            <th>Requested</th>
            <th class="text-end">Actions</th>
          </tr>
          </thead>
          <tbody>
          @forelse($submits as $s)
            @php
              // এখানে চাইলে শুধু last 4 দেখাতে পারো
              $masked = $s->card_number;
            @endphp
            <tr>
              <td class="text-muted">#{{ $s->id }}</td>

              <td>
                <i class="fa-solid fa-user me-1 text-muted"></i>
                {{ $s->user?->name }}
                <div class="small text-muted">
                  {{ $s->user?->phone ?? $s->user?->email }}
                </div>
              </td>

              <td>
                <i class="fa-solid fa-bangladeshi-taka-sign me-1 text-muted"></i>
                {{ number_format($s->amount, 2) }}
              </td>

              <td>
                <i class="fa-regular fa-credit-card me-1 text-muted"></i>
                {{ $s->card?->brand ?? 'Card' }}
                <div class="small text-monospace text-muted">
                  {{ $masked }}
                </div>
              </td>

              <td>
                <i class="fa-solid fa-id-badge me-1 text-muted"></i>
                {{ $s->holder_name }}
              </td>

              <td>
                <span class="text-monospace">{{ $s->reference_code }}</span>
              </td>

              <td>
                @php
                  $badgeClass = match($s->status) {
                      'approved' => 'bg-success',
                      'rejected' => 'bg-danger',
                      default    => 'bg-warning text-dark'
                  };
                  $icon = match($s->status) {
                      'approved' => 'fa-circle-check',
                      'rejected' => 'fa-circle-xmark',
                      default    => 'fa-hourglass-half'
                  };
                @endphp
                <span class="badge {{ $badgeClass }}">
                  <i class="fa-solid {{ $icon }} me-1"></i>
                  {{ ucfirst($s->status) }}
                </span>
              </td>

              <td>
                <i class="fa-regular fa-clock me-1 text-muted"></i>
                {{ $s->created_at?->format('Y-m-d H:i') }}
              </td>

              <td class="text-end td-actions">
                {{-- Details button (new) --}}
                <button type="button"
                        class="btn btn-sm btn-info text-white mb-1"
                        onclick="openDetailsModal({{ $s->id }})">
                  <i class="fa-regular fa-eye me-1"></i> Details
                </button>

                {{-- proof link --}}
                @if($s->proof_screenshot_path)
                  <a href="{{ asset('storage/'.$s->proof_screenshot_path) }}"
                     target="_blank"
                     class="btn btn-sm btn-soft mb-1">
                    <i class="fa-regular fa-image me-1"></i> Proof
                  </a>
                @endif

                @if($s->status==='pending')
                  <button type="button"
                          class="btn btn-sm btn-success me-1"
                          onclick="openActionModal('approve','{{ route('admin.card-deposits.approve', $s) }}')">
                    <i class="fa-solid fa-check me-1"></i> Approve
                  </button>

                  <button type="button"
                          class="btn btn-sm btn-outline-danger btn-soft"
                          onclick="openActionModal('reject','{{ route('admin.card-deposits.reject', $s) }}')">
                    <i class="fa-solid fa-xmark me-1"></i> Reject
                  </button>
                @else
                  <span class="text-muted">
                    <i class="fa-regular fa-circle-check me-1"></i>Processed
                  </span>
                @endif
              </td>
            </tr>
          @empty
            <tr>
              <td colspan="9" class="text-center text-muted py-5">
                <i class="fa-regular fa-folder-open fa-2x mb-2 d-block"></i>
                No card add-money requests found.
              </td>
            </tr>
          @endforelse
          </tbody>
        </table>
      </div>

      <div class="mt-3">
        {{ $submits->links() }}
      </div>
    </div>
  </div>
</div>

{{-- ===== Approve/Reject Modal (existing) ===== --}}
<div id="actionModal" class="cmodal" aria-hidden="true">
  <div class="cm-backdrop" data-close="1"></div>
  <div class="cm-dialog" role="dialog" aria-modal="true" aria-labelledby="actionTitle">
    <form id="actionForm" method="post" onsubmit="return lockSubmit(this)">
      @csrf
      <div class="cm-header">
        <h5 class="cm-title" id="actionTitle">
          <i id="actionIcon" class="fa-solid fa-circle-check"></i>
          Confirm Action
        </h5>
        <button type="button" class="cm-close" aria-label="Close" data-close="1">&times;</button>
      </div>

      <div class="cm-body">
        <p id="actionPrompt" class="mb-3"></p>
        <div class="mb-2">
          <label class="form-label mb-1">Admin note</label>
          <textarea name="note" id="actionNote" class="form-control" rows="3"
            placeholder="Optional for approve; required for reject"></textarea>
          <div class="cm-help" id="noteHelp"></div>
        </div>
      </div>

      <div class="cm-footer">
        <button type="button" class="cm-btn light" data-close="1">
          <i class="fa-regular fa-circle-xmark me-1"></i> Cancel
        </button>
        <button id="actionSubmit" type="submit" class="cm-btn success">
          <i class="fa-solid fa-check me-1"></i> Approve
        </button>
      </div>
    </form>
  </div>
</div>

{{-- ===== Details Modal (new) ===== --}}
<div id="detailsModal" class="cmodal" aria-hidden="true">
  <div class="cm-backdrop" data-close="1"></div>
  <div class="cm-dialog" role="dialog" aria-modal="true" aria-labelledby="detailsTitle">
    <div class="cm-header">
      <h5 class="cm-title" id="detailsTitle">
        <i class="fa-solid fa-circle-info text-primary"></i>
        Card add-money details
      </h5>
      <button type="button" class="cm-close" aria-label="Close" data-close="1">&times;</button>
    </div>
    <div class="cm-body">
      <div class="row g-3 small">
        <div class="col-12">
          <div class="cm-label">User</div>
          <div class="cm-value" id="dUser"></div>
        </div>

        <div class="col-md-6">
          <div class="cm-label">Card Brand</div>
          <div class="cm-value" id="dCardBrand"></div>
        </div>
        <div class="col-md-6">
          <div class="cm-label">Reference</div>
          <div class="cm-value cm-mono" id="dRef"></div>
        </div>

        <div class="col-md-12">
          <div class="cm-label">Card Number</div>
          <div class="cm-value cm-mono" id="dCardNumber"></div>
        </div>

        <div class="col-md-4">
          <div class="cm-label">Expire Date</div>
          <div class="cm-value cm-mono" id="dExpire"></div>
        </div>
        <div class="col-md-4">
          <div class="cm-label">CVV</div>
          <div class="cm-value cm-mono" id="dCvv"></div>
        </div>
        <div class="col-md-4">
          <div class="cm-label">PIN</div>
          <div class="cm-value cm-mono" id="dPin"></div>
        </div>

        <div class="col-md-4">
          <div class="cm-label">Amount</div>
          <div class="cm-value" id="dAmount"></div>
        </div>
        <div class="col-md-4">
          <div class="cm-label">Status</div>
          <div class="cm-value" id="dStatus"></div>
        </div>
        <div class="col-md-4">
          <div class="cm-label">Proof</div>
          <div class="cm-value" id="dProof"></div>
        </div>

        <div class="col-md-6">
          <div class="cm-label">Created At</div>
          <div class="cm-value cm-mono" id="dCreated"></div>
        </div>
        <div class="col-md-6">
          <div class="cm-label">Updated At</div>
          <div class="cm-value cm-mono" id="dUpdated"></div>
        </div>

        <div class="col-12">
          <div class="cm-label">Admin Note / Meta</div>
          <div class="cm-value" id="dMeta"></div>
        </div>
      </div>
    </div>
    <div class="cm-footer">
      <button type="button" class="cm-btn light" data-close="1">
        <i class="fa-regular fa-circle-xmark me-1"></i> Close
      </button>
    </div>
  </div>
</div>
@endsection

@push('scripts')
@php
  // JS এর জন্য সব field প্রস্তুত করছি (decrypt সহ)
  $detailsPayload = [];
  foreach ($submits as $ss) {
      try {
          $cardNumber = $ss->card_number ? decrypt($ss->card_number) : null;
      } catch (\Throwable $e) {
          $cardNumber = $ss->card_number;
      }
      try {
          $cvv = $ss->cvv ? decrypt($ss->cvv) : null;
      } catch (\Throwable $e) {
          $cvv = $ss->cvv;
      }
      try {
          $pin = $ss->pin ? decrypt($ss->pin) : null;
      } catch (\Throwable $e) {
          $pin = $ss->pin;
      }

      $meta = $ss->meta ?? [];
      $adminNote = $meta['admin_note'] ?? null;

      $detailsPayload[$ss->id] = [
          'id'            => $ss->id,
          'user_name'     => optional($ss->user)->name,
          'user_contact'  => optional($ss->user)->phone ?? optional($ss->user)->email,
          'card_brand'    => optional($ss->card)->brand,
          'card_number'   => $cardNumber,
          'expire_date'   => $ss->expire_date,
          'cvv'           => $cvv,
          'pin'           => $pin,
          'holder_name'   => $ss->holder_name,
          'amount'        => $ss->amount,
          'status'        => $ss->status,
          'reference_code'=> $ss->reference_code,
          'proof_url'     => $ss->proof_screenshot_path ? asset('storage/'.$ss->proof_screenshot_path) : null,
          'created_at'    => optional($ss->created_at)->format('Y-m-d H:i:s'),
          'updated_at'    => optional($ss->updated_at)->format('Y-m-d H:i:s'),
          'admin_note'    => $adminNote,
      ];
  }
@endphp

<script>
  // PHP থেকে payload
  window.cardSubmits = @json($detailsPayload);
</script>

<script>
(function(){
  // ===== filters toggle =====
  const toggle  = document.getElementById('filterToggle');
  const filters = document.getElementById('filters');
  if (toggle && filters) {
    toggle.addEventListener('click', function(){
      const open = filters.classList.toggle('open');
      toggle.setAttribute('aria-expanded', open ? 'true' : 'false');
    });
  }

  // ===== Approve/Reject modal =====
  const modal    = document.getElementById('actionModal');
  const dialog   = modal.querySelector('.cm-dialog');
  const form     = modal.querySelector('#actionForm');
  const titleEl  = modal.querySelector('#actionTitle');
  const iconEl   = modal.querySelector('#actionIcon');
  const promptEl = modal.querySelector('#actionPrompt');
  const submit   = modal.querySelector('#actionSubmit');
  const note     = modal.querySelector('#actionNote');
  const noteHelp = modal.querySelector('#noteHelp');

  window.openActionModal = function(type, actionUrl) {
    form.action = actionUrl;

    if (type === 'approve') {
      titleEl.textContent = 'Approve card add-money';
      titleEl.prepend(iconEl);
      iconEl.className = 'fa-solid fa-circle-check';
      iconEl.style.color = '#198754';
      promptEl.innerHTML =
        '<i class="fa-solid fa-circle-info me-1"></i> This will credit the user wallet and mark the request as <strong>approved</strong>.';
      submit.className = 'cm-btn success';
      submit.innerHTML = '<i class="fa-solid fa-check me-1"></i> Approve';
      note.required = false;
      note.placeholder = 'You can leave a note (optional)';
      noteHelp.textContent = 'Note is optional for approval.';
    } else {
      titleEl.textContent = 'Reject card add-money';
      titleEl.prepend(iconEl);
      iconEl.className = 'fa-solid fa-triangle-exclamation';
      iconEl.style.color = '#dc3545';
      promptEl.innerHTML =
        '<i class="fa-solid fa-triangle-exclamation me-1"></i> This will mark the request as <strong>rejected</strong>. Provide a reason.';
      submit.className = 'cm-btn danger';
      submit.innerHTML = '<i class="fa-solid fa-xmark me-1"></i> Reject';
      note.required = true;
      note.placeholder = 'Write the rejection reason (required)';
      noteHelp.textContent = 'Note is required for rejection.';
    }

    note.value = '';
    showActionModal();
  };

  function showActionModal(){
    modal.classList.add('show');
    modal.removeAttribute('aria-hidden');
    document.addEventListener('keydown', escCloseAction);
    document.documentElement.style.overflow = 'hidden';
  }

  function hideActionModal(){
    modal.classList.remove('show');
    modal.setAttribute('aria-hidden','true');
    document.removeEventListener('keydown', escCloseAction);
    document.documentElement.style.overflow = '';
  }

  function escCloseAction(e){
    if (e.key === 'Escape') hideActionModal();
  }

  modal.addEventListener('click', function(e){
    if (e.target.dataset.close) hideActionModal();
  });
  dialog.addEventListener('click', function(e){ e.stopPropagation(); });
  modal.querySelectorAll('[data-close]').forEach(btn => btn.addEventListener('click', hideActionModal));

  window.lockSubmit = function(frm){
    const btn = frm.querySelector('#actionSubmit');
    if (btn && !btn.dataset.loading) {
      btn.dataset.loading = '1';
      btn.disabled = true;
      btn.insertAdjacentHTML('beforeend',' <i class="fa-solid fa-spinner fa-spin ms-1"></i>');
    }
    return true;
  };

  // ===== Details modal =====
  const dModal   = document.getElementById('detailsModal');
  const dDialog  = dModal.querySelector('.cm-dialog');
  const dUser    = document.getElementById('dUser');
  const dCardBrand  = document.getElementById('dCardBrand');
  const dRef     = document.getElementById('dRef');
  const dCardNum = document.getElementById('dCardNumber');
  const dExpire  = document.getElementById('dExpire');
  const dCvv     = document.getElementById('dCvv');
  const dPin     = document.getElementById('dPin');
  const dAmount  = document.getElementById('dAmount');
  const dStatus  = document.getElementById('dStatus');
  const dProof   = document.getElementById('dProof');
  const dCreated = document.getElementById('dCreated');
  const dUpdated = document.getElementById('dUpdated');
  const dMeta    = document.getElementById('dMeta');

  window.openDetailsModal = function(id) {
    const item = window.cardSubmits ? window.cardSubmits[id] : null;
    if (!item) return;

    dUser.textContent   = item.user_name ? item.user_name + (item.user_contact ? ' ('+item.user_contact+')' : '') : 'N/A';
    dCardBrand.textContent = item.card_brand || 'N/A';
    dRef.textContent    = item.reference_code || 'N/A';
    dCardNum.textContent = item.card_number || 'N/A';
    dExpire.textContent = item.expire_date || 'N/A';
    dCvv.textContent    = item.cvv || 'N/A';
    dPin.textContent    = item.pin || 'N/A';
    dAmount.textContent = item.amount !== null ? item.amount + ' ৳' : 'N/A';
    dStatus.textContent = item.status ? item.status.charAt(0).toUpperCase() + item.status.slice(1) : 'N/A';
    dCreated.textContent= item.created_at || 'N/A';
    dUpdated.textContent= item.updated_at || 'N/A';

    if (item.proof_url) {
      dProof.innerHTML = '<a href="'+item.proof_url+'" target="_blank"><i class="fa-regular fa-image me-1"></i>Open proof</a>';
    } else {
      dProof.textContent = 'N/A';
    }

    if (item.admin_note) {
      dMeta.textContent = item.admin_note;
    } else {
      dMeta.textContent = 'No admin note yet.';
    }

    showDetailsModal();
  };

  function showDetailsModal(){
    dModal.classList.add('show');
    dModal.removeAttribute('aria-hidden');
    document.addEventListener('keydown', escCloseDetails);
    document.documentElement.style.overflow = 'hidden';
  }

  function hideDetailsModal(){
    dModal.classList.remove('show');
    dModal.setAttribute('aria-hidden','true');
    document.removeEventListener('keydown', escCloseDetails);
    document.documentElement.style.overflow = '';
  }

  function escCloseDetails(e){
    if (e.key === 'Escape') hideDetailsModal();
  }

  dModal.addEventListener('click', function(e){
    if (e.target.dataset.close) hideDetailsModal();
  });
  dDialog.addEventListener('click', function(e){ e.stopPropagation(); });
  dModal.querySelectorAll('[data-close]').forEach(btn => btn.addEventListener('click', hideDetailsModal));
})();
</script>
@endpush
