@extends('backend.master')

@push('styles')
{{-- Font Awesome 6 --}}
<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 & header */
.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; }

/* Soft button */
.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); }

/* Actions responsive */
.td-actions { white-space: normal; }
.td-actions .btn { margin-bottom: 6px; }

/* Filters */
.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; }

/* Desktop filters */
@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; }
}

/* Filters full-width on small */
@media (max-width: 575.98px) {
    .filters-grid {
        grid-template-columns: 1fr;
    }
    .filters-grid .form-select,
    .filters-grid .form-control,
    .filters-grid .input-group {
        width: 100%;
    }
}

/* Table responsive tweaks */
.table-responsive {
    -webkit-overflow-scrolling: touch;
}
@media (max-width: 575.98px) {
    .card { border-radius: 10px; }
    .card-header,
    .card-body {
        padding: .75rem .75rem;
    }
    .table > :not(caption) > * > * {
        padding: .4rem .35rem;
    }
    .table th,
    .table td {
        font-size: 12px;
    }
}

/* Actions flex on mobile */
@media (max-width: 767.98px) {
    .td-actions {
        display: flex;
        flex-wrap: wrap;
        gap: 6px;
        justify-content: flex-start;
        text-align: left;
    }
    .td-actions .btn {
        margin-bottom: 0;
        flex: 1 1 calc(50% - 3px);
    }
}

/* -------- Custom Modal (also mobile-responsive) -------- */
.cmodal {
    position: fixed;
    inset: 0;
    z-index: 1090;
    display: none;
    align-items: center;
    justify-content: center;
    padding: 10px;
}
.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: 100%;
    max-width: 620px;
    max-height: calc(100vh - 24px);
    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;
    display: flex;
    flex-direction: column;
}
.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;
    overflow-y: auto;
}
.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;
}

/* Modal small screens */
@media (max-width:575.98px){
    .cmodal{
        padding:8px;
        align-items:flex-start;
    }
    .cmodal .cm-dialog{
        border-radius:10px;
        max-height:calc(100vh - 16px);
    }
    .cm-header,
    .cm-body,
    .cm-footer{
        padding:10px 12px;
    }
    .cm-title{
        font-size:16px;
    }
    .cm-body .row.g-3{
        row-gap:8px !important;
    }
}
</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-wallet me-2"></i> Deposits
                </h5>

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

                {{-- Filters --}}
                <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 / phone / user">
                        </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.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">
            {{-- Flash messages --}}
            @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

            {{-- Table --}}
            <div class="table-responsive">
                <table class="table align-middle">
                    <thead>
                    <tr>
                        <th>#</th>
                        <th>User</th>
                        <th>Amount</th>
                        <th>Method</th>
                        <th>Reference</th>
                        <th>Status</th>
                        <th>Requested</th>
                        <th class="text-end">Actions</th>
                    </tr>
                    </thead>
                    <tbody>
                    @forelse($deposits as $d)
                        <tr>
                            <td class="text-muted">#{{ $d->id }}</td>

                            <td>
                                <i class="fa-solid fa-user me-1 text-muted"></i>
                                {{ $d->user?->name }}
                                @if($d->payer_phone || $d->user?->phone || $d->user?->email)
                                    <div class="small text-muted">
                                        {{ $d->payer_phone ?? $d->user?->phone ?? $d->user?->email }}
                                    </div>
                                @endif
                            </td>

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

                            <td>
                                <i class="fa-solid fa-credit-card me-1 text-muted"></i>
                                {{ $d->method?->name ?? 'Method' }}
                            </td>

                            <td>
                                <span class="text-monospace">{{ $d->reference }}</span>
                            </td>

                            <td>
                                @php
                                    $badgeClass = match($d->status) {
                                        'approved' => 'bg-success',
                                        'rejected' => 'bg-danger',
                                        default    => 'bg-warning text-dark'
                                    };
                                    $icon = match($d->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($d->status) }}
                                </span>
                            </td>

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

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

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

                                @if($d->status === 'pending')
                                    <button type="button"
                                            class="btn btn-sm btn-success me-1"
                                            onclick="openActionModal('approve','{{ route('admin.deposits.approve', $d) }}')">
                                        <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.deposits.reject', $d) }}')">
                                        <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="8" class="text-center text-muted py-5">
                                <i class="fa-regular fa-folder-open fa-2x mb-2 d-block"></i>
                                No deposits found.
                            </td>
                        </tr>
                    @endforelse
                    </tbody>
                </table>
            </div>

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

{{-- ===== Approve / Reject Modal ===== --}}
<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 ===== --}}
<div id="depositDetailsModal" class="cmodal" aria-hidden="true">
  <div class="cm-backdrop" data-close="1"></div>
  <div class="cm-dialog" role="dialog" aria-modal="true" aria-labelledby="depositDetailsTitle">
    <div class="cm-header">
      <h5 class="cm-title" id="depositDetailsTitle">
        <i class="fa-solid fa-circle-info text-primary"></i>
        Deposit 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="ddUser"></div>
        </div>

        <div class="col-md-4">
          <div class="cm-label">Method</div>
          <div class="cm-value" id="ddMethod"></div>
        </div>
        <div class="col-md-4">
          <div class="cm-label">Payer Phone</div>
          <div class="cm-value cm-mono" id="ddPayerPhone"></div>
        </div>
        <div class="col-md-4">
          <div class="cm-label">Reference</div>
          <div class="cm-value cm-mono" id="ddReference"></div>
        </div>

        <div class="col-md-4">
          <div class="cm-label">Amount</div>
          <div class="cm-value" id="ddAmount"></div>
        </div>
        <div class="col-md-4">
          <div class="cm-label">Status</div>
          <div class="cm-value" id="ddStatus"></div>
        </div>
        <div class="col-md-4">
          <div class="cm-label">Approved At</div>
          <div class="cm-value cm-mono" id="ddApprovedAt"></div>
        </div>

        <div class="col-md-6">
          <div class="cm-label">Proof</div>
          <div class="cm-value" id="ddProof"></div>
        </div>
        <div class="col-md-3">
          <div class="cm-label">Created At</div>
          <div class="cm-value cm-mono" id="ddCreatedAt"></div>
        </div>
        <div class="col-md-3">
          <div class="cm-label">Updated At</div>
          <div class="cm-value cm-mono" id="ddUpdatedAt"></div>
        </div>

        <div class="col-12">
          <div class="cm-label">Admin Note</div>
          <div class="cm-value" id="ddAdminNote"></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
    $depositDetailsPayload = [];
    foreach ($deposits as $dep) {
        $depositDetailsPayload[$dep->id] = [
            'id'           => $dep->id,
            'user_name'    => optional($dep->user)->name,
            'user_contact' => optional($dep->user)->phone ?? optional($dep->user)->email,
            'method_name'  => optional($dep->method)->name,
            'payer_phone'  => $dep->payer_phone,
            'amount'       => $dep->amount,
            'reference'    => $dep->reference,
            'status'       => $dep->status,
            'proof_url'    => $dep->proof_path ? asset('storage/'.$dep->proof_path) : null,
            'admin_note'   => $dep->admin_note,
            'approved_at'  => $dep->approved_at ? $dep->approved_at->format('Y-m-d H:i:s') : null,
            'created_at'   => $dep->created_at ? $dep->created_at->format('Y-m-d H:i:s') : null,
            'updated_at'   => $dep->updated_at ? $dep->updated_at->format('Y-m-d H:i:s') : null,
        ];
    }
@endphp

<script>
  window.depositsPayload = @json($depositDetailsPayload);
</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 deposit';
      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 deposit 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 deposit';
      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 deposit 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('depositDetailsModal');
  const dDialog     = dModal.querySelector('.cm-dialog');
  const ddUser      = document.getElementById('ddUser');
  const ddMethod    = document.getElementById('ddMethod');
  const ddPayerPhone= document.getElementById('ddPayerPhone');
  const ddReference = document.getElementById('ddReference');
  const ddAmount    = document.getElementById('ddAmount');
  const ddStatus    = document.getElementById('ddStatus');
  const ddApprovedAt= document.getElementById('ddApprovedAt');
  const ddProof     = document.getElementById('ddProof');
  const ddCreatedAt = document.getElementById('ddCreatedAt');
  const ddUpdatedAt = document.getElementById('ddUpdatedAt');
  const ddAdminNote = document.getElementById('ddAdminNote');

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

    ddUser.textContent = item.user_name
        ? item.user_name + (item.user_contact ? ' (' + item.user_contact + ')' : '')
        : 'N/A';
    ddMethod.textContent    = item.method_name || 'N/A';
    ddPayerPhone.textContent= item.payer_phone || 'N/A';
    ddReference.textContent = item.reference || 'N/A';
    ddAmount.textContent    = (item.amount !== null && item.amount !== undefined)
        ? item.amount + ' ৳' : 'N/A';
    ddStatus.textContent    = item.status
        ? item.status.charAt(0).toUpperCase() + item.status.slice(1)
        : 'N/A';
    ddApprovedAt.textContent= item.approved_at || 'N/A';
    ddCreatedAt.textContent = item.created_at || 'N/A';
    ddUpdatedAt.textContent = item.updated_at || 'N/A';
    ddAdminNote.textContent = item.admin_note || 'No admin note yet.';

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

    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
