@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 */
.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; }
.td-actions .btn{ margin-bottom:6px; }
/* Filters (mobile-first) */
.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;}
.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:360px; opacity:1; }
.filters-grid{ display:grid; gap:var(--gap); }
.filters-grid .input-group-text{ background:#fff; }
/* Desktop */
@media (min-width:768px){
  .filters-wrap{ grid-template-columns:auto 1fr; }
  .filter-toggle{ display:none; }
  .filters{ grid-column:2/3; 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:200px; }
  .filters-grid .input-group{ width:280px; }
}
/* Buttons */
.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); }
/* Custom modal (centered) */
.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(560px, 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-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;}
.text-mono { font-family: ui-monospace, 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-solid fa-mobile-screen-button me-2"></i> Mobile Transactions
        </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','channel','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>

            <select name="channel" class="form-select form-select-sm" onchange="this.form.submit()">
              <option value="">All channels</option>
              <option value="agent"    @selected(request('channel')==='agent')>Agent</option>
              <option value="personal" @selected(request('channel')==='personal')>Personal</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 account / ref / user / gateway">
            </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','channel','q']))
              <a href="{{ route('admin.mobile_tx.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>Gateway</th>
              <th>Account</th>
              <th>Amount</th>
              <th>Channel</th>
              <th>Reference</th>
              <th>Commission</th>
              <th>Status</th>
              <th>Created</th>
              <th class="text-end">Actions</th>
            </tr>
          </thead>
          <tbody>
          @forelse($transactions as $t)
            <tr>
              <td class="text-muted">#{{ $t->id }}</td>
              <td><i class="fa-solid fa-user me-1 text-muted"></i>{{ $t->user?->name }}</td>
              <td><i class="fa-solid fa-sitemap me-1 text-muted"></i>{{ $t->gateway?->name ?? ('Gateway #'.$t->gateway_id) }}</td>
              <td class="text-mono">{{ $t->account_number }}</td>
              <td><i class="fa-solid fa-bangladeshi-taka-sign me-1 text-muted"></i>{{ number_format($t->amount,2) }}</td>
              <td>
                @php
                  $chipClass = $t->channel === 'agent' ? 'bg-primary' : 'bg-info';
                  $chipIcon  = $t->channel === 'agent' ? 'fa-user-tie' : 'fa-user';
                @endphp
                <span class="badge {{ $chipClass }}"><i class="fa-solid {{ $chipIcon }} me-1"></i>{{ ucfirst($t->channel) }}</span>
              </td>
              <td class="text-mono">{{ $t->reference }}</td>
              <td><i class="fa-solid fa-coins me-1 text-muted"></i>{{ number_format($t->commission_amount,2) }}</td>
              <td>
                @php
                  $badgeClass = match($t->status) {
                      'approved' => 'bg-success',
                      'rejected' => 'bg-danger',
                      default    => 'bg-warning text-dark'
                  };
                  $icon = match($t->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($t->status) }}</span>
              </td>
              <td><i class="fa-regular fa-clock me-1 text-muted"></i>{{ $t->created_at?->format('Y-m-d H:i') }}</td>
              <td class="text-end td-actions">
                @if($t->status==='pending')
                  <button type="button" class="btn btn-sm btn-success me-1"
                          onclick="openTxModal('approve','{{ route('admin.mobile_tx.approve', $t) }}', '{{ $t->commission_amount }}', `{{ $t->admin_note }}`)">
                    <i class="fa-solid fa-check me-1"></i> Approve
                  </button>
                  <button type="button" class="btn btn-sm btn-outline-danger btn-soft"
                          onclick="openTxModal('reject','{{ route('admin.mobile_tx.reject', $t) }}', '{{ $t->commission_amount }}', `{{ $t->admin_note }}`)">
                    <i class="fa-solid fa-xmark me-1"></i> Reject
                  </button>
                @else
                  <span class="text-muted">—</span>
                @endif
              </td>
            </tr>
          @empty
            <tr>
              <td colspan="11" class="text-center text-muted py-5">
                <i class="fa-regular fa-folder-open fa-2x mb-2 d-block"></i>
                No mobile transactions found.
              </td>
            </tr>
          @endforelse
          </tbody>
        </table>
      </div>

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

{{-- ===== Custom Modal (Approve/Reject) ===== --}}
<div id="txModal" class="cmodal" aria-hidden="true">
  <div class="cm-backdrop" data-close="1"></div>
  <div class="cm-dialog" role="dialog" aria-modal="true" aria-labelledby="txTitle">
    <form id="txForm" method="post" onsubmit="return lockSubmit(this)">
      @csrf
      <div class="cm-header">
        <h5 class="cm-title" id="txTitle"><i id="txIcon" class="fa-solid"></i> <span id="txTitleText">Confirm</span></h5>
        <button type="button" class="cm-close" aria-label="Close" data-close="1">&times;</button>
      </div>
      <div class="cm-body">
        <p id="txPrompt" class="mb-3"></p>

        <div class="row g-2">
          <div class="col-6">
            <label class="form-label mb-1">Commission (optional)</label>
            <input type="number" step="0.01" min="0" name="commission_amount" id="txCommission" class="form-control" placeholder="e.g., 5.00">
            <div class="cm-help">Empty রাখলে বর্তমান কমিশনই থাকবে।</div>
          </div>
          <div class="col-12">
            <label class="form-label mb-1">Admin note <span id="noteReq" class="cm-help">(optional)</span></label>
            <textarea name="admin_note" id="txNote" class="form-control" rows="3" placeholder="Write a note…"></textarea>
          </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="txSubmit" type="submit" class="cm-btn success">
          <i class="fa-solid fa-check me-1"></i> Confirm
        </button>
      </div>
    </form>
  </div>
</div>

@push('scripts')
<script>
(function(){
  // Mobile 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');
    });
  }

  // Modal logic
  const modal   = document.getElementById('txModal');
  const dialog  = modal.querySelector('.cm-dialog');
  const form    = modal.querySelector('#txForm');
  const titleEl = modal.querySelector('#txTitleText');
  const iconEl  = modal.querySelector('#txIcon');
  const prompt  = modal.querySelector('#txPrompt');
  const submit  = modal.querySelector('#txSubmit');
  const noteIpt = modal.querySelector('#txNote');
  const noteReq = modal.querySelector('#noteReq');
  const commIpt = modal.querySelector('#txCommission');

  window.openTxModal = function(type, actionUrl, commission='', note=''){
    form.action = actionUrl;
    commIpt.value = commission || '';
    noteIpt.value = note || '';

    if (type === 'approve') {
      titleEl.textContent = 'Approve transaction';
      iconEl.className = 'fa-solid fa-circle-check';
      iconEl.style.color = '#198754';
      prompt.innerHTML = '<i class="fa-solid fa-circle-info me-1"></i> This will set status to <strong>approved</strong>. Optionally override commission & add a note.';
      submit.className = 'cm-btn success';
      submit.innerHTML = '<i class="fa-solid fa-check me-1"></i> Approve';
      noteIpt.required = false; noteReq.textContent = '(optional)';
    } else {
      titleEl.textContent = 'Reject transaction';
      iconEl.className = 'fa-solid fa-triangle-exclamation';
      iconEl.style.color = '#dc3545';
      prompt.innerHTML = '<i class="fa-solid fa-triangle-exclamation me-1"></i> This will set status to <strong>rejected</strong>. A note is required.';
      submit.className = 'cm-btn danger';
      submit.innerHTML = '<i class="fa-solid fa-xmark me-1"></i> Reject';
      noteIpt.required = true; noteReq.textContent = '(required)';
    }

    showModal();
  };

  function showModal(){
    modal.classList.add('show');
    modal.removeAttribute('aria-hidden');
    document.addEventListener('keydown', escClose);
    document.documentElement.style.overflow = 'hidden';
  }
  function hideModal(){
    modal.classList.remove('show');
    modal.setAttribute('aria-hidden','true');
    document.removeEventListener('keydown', escClose);
    document.documentElement.style.overflow = '';
  }
  function escClose(e){ if (e.key === 'Escape') hideModal(); }
  modal.addEventListener('click', function(e){ if (e.target.dataset.close) hideModal(); });
  dialog.addEventListener('click', function(e){ e.stopPropagation(); });
  modal.querySelectorAll('[data-close]').forEach(btn => btn.addEventListener('click', hideModal));

  // Double submit guard
  window.lockSubmit = function(frm){
    const btn = frm.querySelector('#txSubmit');
    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;
  };
})();
</script>
@endpush
@endsection
