@extends('layout.admin')

@section('content')
  <style>
    .page-wrap {
      max-width: 860px;
      margin: 8px auto 24px;
      padding: 0 12px;
    }

    .page-title {
      margin: 8px 0 14px;
      font-weight: 700;
      font-size: 22px;
      color: #0f172a
    }

    .card-clean {
      background: #fff;
      border: 1px solid #e6e8ef;
      border-radius: 14px;
      box-shadow: 0 4px 12px rgba(15, 23, 42, .08);
      padding: 18px;
    }

    label {
      font-size: 13px;
      color: #475569;
      margin-bottom: 6px
    }

    .form-control,
    .form-select {
      background: #fff;
      border: 1px solid #d6d9e4;
      border-radius: 10px;
      padding: 10px 12px;
    }

    .form-control:focus,
    .form-select:focus {
      border-color: #3b82f6
    }

    .row-gap {
      row-gap: 14px
    }

    .btn-primary {
      border-radius: 10px;
      padding: 10px 16px;
      font-weight: 600
    }

    .alert {
      border-radius: 10px
    }

    .user-card {
      display: flex;
      align-items: center;
      gap: 16px;
      margin-bottom: 16px;
      padding: 12px 16px;
      border: 1px solid #e6e8ef;
      border-radius: 12px;
      background: #f8fafc;
    }

    .user-card img {
      width: 64px;
      height: 64px;
      object-fit: cover;
      border-radius: 50%;
    }

    .user-card h5 {
      margin: 0;
      font-size: 18px;
      font-weight: 600;
    }

    .user-card small {
      color: #64748b;
    }

    .history-wrap {
      margin-top: 22px;
    }

    .history-title {
      margin: 0 0 12px;
      font-size: 18px;
      font-weight: 700;
      color: #0f172a;
    }

    .history-table-wrap {
      overflow-x: auto;
      border: 1px solid #e6e8ef;
      border-radius: 14px;
      background: #fff;
    }

    .history-table {
      width: 100%;
      min-width: 980px;
      border-collapse: collapse;
    }

    .history-table th,
    .history-table td {
      padding: 12px 14px;
      border-bottom: 1px solid #eef2f7;
      vertical-align: top;
      font-size: 13px;
    }

    .history-table th {
      background: #f8fafc;
      color: #334155;
      font-weight: 700;
      white-space: nowrap;
    }

    .history-table tbody tr:hover {
      background: #f8fbff;
    }

    .wallet-badge,
    .action-badge {
      display: inline-flex;
      align-items: center;
      border-radius: 999px;
      padding: 4px 10px;
      font-size: 12px;
      font-weight: 700;
    }

    .wallet-badge {
      background: #eff6ff;
      color: #1d4ed8;
    }

    .action-badge.plus {
      background: #dcfce7;
      color: #166534;
    }

    .action-badge.minus {
      background: #fee2e2;
      color: #b91c1c;
    }

    .balance-stack {
      display: flex;
      flex-direction: column;
      gap: 2px;
      min-width: 130px;
    }

    .balance-stack .label {
      font-size: 11px;
      color: #64748b;
    }

    .balance-stack .value {
      font-weight: 700;
      color: #0f172a;
    }
  </style>

  <div class="page-wrap">
    <h2 class="page-title">Balance / Voucher Update</h2>

    {{-- Alerts --}}
    @if(session('success'))
      <div class="alert alert-success mb-3">{{ session('success') }}</div>
    @endif
    @if(session('error'))
      <div class="alert alert-danger mb-3">{{ session('error') }}</div>
    @endif

    {{-- User info preview --}}
    <div id="user-preview" style="display:none;">
      <div class="user-card">
        <img id="u-photo" src="" alt="">
        <div>
          <h5 id="u-name"></h5>
          <small>Referral: <span id="u-referral"></span></small><br>
          <small>Balance: <b id="u-balance"></b> | Voucher: <b id="u-voucher"></b></small>
        </div>
      </div>
    </div>

    <form action="{{ route('admin.balance.update') }}" method="POST" class="card-clean">
      @csrf

      <div class="row row-gap">
        <div class="col-md-8">
          <label>User Identifier</label>
          <input type="text" name="identifier" id="identifier" class="form-control"
            placeholder="email / mobile / referral / user_id" value="{{ old('identifier') }}" required>
        </div>
        <div class="col-md-4">
          <label>Identifier Type</label>
          <select name="id_type" id="id_type" class="form-select" required>
            <option value="auto">Auto</option>
            <option value="email">Email</option>
            <option value="mobile">Mobile</option>
            <option value="referral_code">Referral</option>
            <option value="user_id">User ID</option>
          </select>
        </div>

        <div class="col-md-4">
          <label>Wallet</label>
          <select name="wallet" class="form-select" required>
            <option value="balance">Income Balance</option>
            <option value="voucher_balance">Voucher</option>
          </select>
        </div>
        <div class="col-md-4">
          <label>Action</label>
          <select name="action" class="form-select" required>
            <option value="increment">Increase (+)</option>
            <option value="decrement">Decrease (-)</option>
          </select>
        </div>
        <div class="col-md-4">
          <label>Amount</label>
          <input type="number" step="0.01" min="0.01" name="amount" class="form-control" required>
        </div>

        <div class="col-md-8">
          <label>Reason (optional)</label>
          <input type="text" name="reason" class="form-control" placeholder="Note / Reason">
        </div>
        <div class="col-md-4">
          <label>Update PIN</label>
          <input type="password" name="pin" class="form-control" required>
        </div>
      </div>

      <div class="mt-3">
        <button type="submit" class="btn btn-primary">Submit</button>
      </div>
    </form>

    <div class="history-wrap">
      <h3 class="history-title">Recent Balance History</h3>

      <div class="history-table-wrap">
        <table class="history-table">
          <thead>
            <tr>
              <th>Date</th>
              <th>User</th>
              <th>Wallet</th>
              <th>Action</th>
              <th>Change</th>
              <th>Previous Balance</th>
              <th>New Balance</th>
              <th>Admin</th>
              <th>Reason</th>
            </tr>
          </thead>
          <tbody>
            @forelse(($recentTransactions ?? collect()) as $transaction)
              <tr>
                <td>
                  {{ \Illuminate\Support\Carbon::parse($transaction->created_at)->format('d M Y') }}<br>
                  <small>{{ \Illuminate\Support\Carbon::parse($transaction->created_at)->format('h:i A') }}</small>
                </td>
                <td>
                  <strong>{{ $transaction->user_name ?? 'N/A' }}</strong><br>
                  <small>{{ $transaction->user_referral_code ?? 'No referral' }}</small>
                </td>
                <td>
                  <span class="wallet-badge">
                    {{ $transaction->wallet === 'voucher_balance' ? 'Voucher' : 'Balance' }}
                  </span>
                </td>
                <td>
                  <span class="action-badge {{ $transaction->action === 'increment' ? 'plus' : 'minus' }}">
                    {{ $transaction->action === 'increment' ? 'Increase' : 'Decrease' }}
                  </span>
                </td>
                <td>{{ number_format((float) $transaction->amount, 2) }} ৳</td>
                <td>
                  <div class="balance-stack">
                    <span class="label">আগের ব্যালেন্স</span>
                    <span class="value">{{ number_format((float) $transaction->before_amount, 2) }} ৳</span>
                  </div>
                </td>
                <td>
                  <div class="balance-stack">
                    <span class="label">নতুন ব্যালেন্স</span>
                    <span class="value">{{ number_format((float) $transaction->after_amount, 2) }} ৳</span>
                  </div>
                </td>
                <td>{{ $transaction->admin_name ?? 'System/Admin' }}</td>
                <td>{{ $transaction->reason ?: 'Manual adjustment' }}</td>
              </tr>
            @empty
              <tr>
                <td colspan="9" class="text-center text-muted">No balance history found yet.</td>
              </tr>
            @endforelse
          </tbody>
        </table>
      </div>
    </div>
  </div>

  <script>
    document.addEventListener('DOMContentLoaded', function () {
      const input = document.getElementById('identifier');
      let timer;
      input.addEventListener('input', function () {
        clearTimeout(timer);
        const val = this.value.trim();
        if (val.length < 3) { document.getElementById('user-preview').style.display = 'none'; return; }
        timer = setTimeout(() => fetchUser(val), 500);
      });
    });

    function fetchUser(id) {
      fetch('{{ route("admin.balance.fetch") }}?id=' + encodeURIComponent(id))
        .then(res => res.json())
        .then(data => {
          const preview = document.getElementById('user-preview');
          if (!data.found) { preview.style.display = 'none'; return; }
          document.getElementById('u-photo').src = data.photo;
          document.getElementById('u-name').textContent = data.name;
          document.getElementById('u-referral').textContent = data.referral_code;
          document.getElementById('u-balance').textContent = data.balance;
          document.getElementById('u-voucher').textContent = data.voucher_balance;
          preview.style.display = 'block';
        })
        .catch(() => document.getElementById('user-preview').style.display = 'none');
    }
  </script>
@endsection
