@extends('layout.admin')
@section('title', 'Broadcast Email')

@section('content')
<style>
.box{max-width:920px;margin:0 auto;background:#fff;border:1px solid #e5e7eb;border-radius:12px;padding:16px;box-shadow:0 8px 20px rgba(2,6,23,.06)}
.grid{display:grid;gap:12px}
.field{width:100%;border:1px solid #e5e7eb;border-radius:10px;padding:10px;font-weight:800}
.btn{background:#f97316;color:#fff;border:0;border-radius:10px;padding:12px 16px;font-weight:900;cursor:pointer}
.alert{padding:10px;border-radius:10px;margin-bottom:10px}
.alert.ok{background:#ecfdf5;border:1px solid #86efac;color:#065f46}
.alert.err{background:#fff1f2;border:1px solid #fecaca;color:#b91c1c}
.muted{color:#64748b;font-weight:700}
.count-box{border:1px solid #cbd5e1;background:#f8fafc;border-radius:10px;padding:10px 12px;font-weight:900;color:#0f172a}
.filters{border:1px solid #e2e8f0;background:#f8fafc;border-radius:12px;padding:12px}
</style>

<div class="box">
  <h2 style="margin:0 0 10px">📧 Broadcast Email</h2>

  @if(session('ok'))
    <div class="alert ok">{{ session('ok') }}</div>
  @endif
  @if($errors->any())
    <div class="alert err">{{ implode(' | ', $errors->all()) }}</div>
  @endif

  <form method="POST" action="{{ route('admin.email.store') }}" id="broadcastForm">
    @csrf
    <div class="grid">
      <div>
        <label>Subject</label>
        <input type="text" name="subject" class="field" value="{{ old('subject') }}" required>
      </div>

      <div>
        <label>Message (HTML allowed)</label>
        <textarea name="message" rows="10" class="field" required>{{ old('message') }}</textarea>
      </div>

      <div class="filters">
        <div style="font-weight:900;margin-bottom:8px;">Recipients Filter</div>

        @php
          $oldFilters = old('recipient_filters', ['verified', 'unverified']);
          if (!is_array($oldFilters)) {
            $oldFilters = ['verified', 'unverified'];
          }
        @endphp

        <div style="display:flex;gap:8px;flex-wrap:wrap;margin-bottom:10px;">
          <button type="button" class="btn btn-sm btn-outline-success" id="recipientSelectAll">✓ সব টিক</button>
          <button type="button" class="btn btn-sm btn-outline-secondary" id="recipientUnselectAll">✕ সব আনটিক</button>
        </div>

        <div style="display:flex;gap:14px;flex-wrap:wrap;margin-bottom:10px;">
          <label>
            <input type="checkbox" name="recipient_filters[]" value="verified" class="recipient-filter-checkbox"
              {{ in_array('verified', $oldFilters, true) ? 'checked' : '' }}>
            শুধু ভেরিফাইড মেম্বার
          </label>
          <label>
            <input type="checkbox" name="recipient_filters[]" value="unverified" class="recipient-filter-checkbox"
              {{ in_array('unverified', $oldFilters, true) ? 'checked' : '' }}>
            শুধু আনভেরিফাইড মেম্বার
          </label>
        </div>

        <div>
          <label>রেফার কোড (শুধু এই কোডের ইউজারকে পাঠাতে)</label>
          <input type="text"
                 name="referral_code"
                 id="referral_code"
                 class="field"
                 value="{{ old('referral_code') }}"
                 placeholder="যেমন: ABC12345">
          <div class="muted" style="margin-top:6px;">রেফার কোড দিলে শুধু ওই ইউজারই টার্গেট হবে।</div>
          <div class="muted" style="margin-top:4px;">যদি উপরের filter-এ কোনো টিক না থাকে, তাহলে Referral Code দিয়ে পাঠাতে পারবেন।</div>
        </div>
      </div>

      <div class="count-box">
        এই মেসেজ যাবে:
        <span id="recipientCount">{{ (int) ($initialRecipientCount ?? 0) }}</span> জনের কাছে
      </div>
    </div>

    <div style="margin-top:10px">
      <label><input type="checkbox" name="test_mode" value="1" {{ old('test_mode') ? 'checked' : '' }}> Test mode (শুধু এডমিনের ইমেইলে যাবে)</label>
    </div>

    <div style="margin-top:12px">
      <button class="btn" type="submit">Queue Emails</button>
    </div>
  </form>
</div>

<script>
(() => {
  const form = document.getElementById('broadcastForm');
  const countEl = document.getElementById('recipientCount');
  if (!form || !countEl) return;

  const endpoint = "{{ route('admin.email.recipient-count') }}";
  let timer = null;

  const recipientBoxes = Array.from(form.querySelectorAll('input[name="recipient_filters[]"]'));
  const selectAllBtn = document.getElementById('recipientSelectAll');
  const unselectAllBtn = document.getElementById('recipientUnselectAll');

  const updateCount = async () => {
    const selectedFilters = recipientBoxes.filter((box) => box.checked).map((box) => box.value);
    const referral = form.querySelector('#referral_code')?.value || '';

    const params = new URLSearchParams();
    params.set('referral_code', referral);
    selectedFilters.forEach((val) => params.append('recipient_filters[]', val));

    try {
      const res = await fetch(endpoint + '?' + params.toString(), { headers: { 'Accept': 'application/json' } });
      if (!res.ok) return;
      const data = await res.json();
      countEl.textContent = Number(data.count || 0).toLocaleString();
    } catch (_) {
      // keep existing count
    }
  };

  const debounceUpdate = () => {
    if (timer) clearTimeout(timer);
    timer = setTimeout(updateCount, 250);
  };

  recipientBoxes.forEach((el) => {
    el.addEventListener('change', debounceUpdate);
  });
  form.querySelector('#referral_code')?.addEventListener('input', debounceUpdate);

  selectAllBtn?.addEventListener('click', () => {
    recipientBoxes.forEach((box) => box.checked = true);
    debounceUpdate();
  });

  unselectAllBtn?.addEventListener('click', () => {
    recipientBoxes.forEach((box) => box.checked = false);
    debounceUpdate();
  });
})();
</script>
@endsection
