@extends('layouts.app')

@section('content')
<div class="container-xxl flex-grow-1 container-p-y">
  <div class="card mb-4">
    <div class="card-body">
      <form class="row g-2" method="GET" action="{{ route('messages.index') }}">
        <div class="col-md-9">
          <select name="subscription_id" class="form-select">
            <option value="">All subscriptions</option>
            @foreach($subscriptions as $subscription)
              <option value="{{ $subscription->id }}" @selected((string)$subscriptionId === (string)$subscription->id)>
                {{ $subscription->title ?: ($subscription->service->name . ' - ' . $subscription->servicePlan->name) }}
              </option>
            @endforeach
          </select>
        </div>
        <div class="col-md-3 d-grid"><button class="btn btn-outline-primary">Filter</button></div>
      </form>
    </div>
  </div>

  <div class="row g-4">
    <div class="col-md-5">
      <div class="card">
        <div class="card-header"><h6 class="mb-0">Send Message</h6></div>
        <div class="card-body">
          <form method="POST" action="{{ route('messages.store') }}" class="row g-2">
            @csrf
            <div class="col-12"><input type="number" name="shared_subscription_id" class="form-control" placeholder="Subscription ID (optional)"></div>
            <div class="col-12"><input type="number" name="receiver_id" class="form-control" placeholder="Receiver User ID (optional)"></div>
            <div class="col-12"><textarea name="message" rows="4" class="form-control" placeholder="Write message..." required></textarea></div>
            <div class="col-12 d-grid"><button class="btn btn-primary">Send</button></div>
          </form>
        </div>
      </div>
    </div>

    <div class="col-md-7">
      <div class="card">
        <div class="card-header"><h5 class="mb-0">Messages</h5></div>
        <div class="list-group list-group-flush">
          @forelse($messages as $msg)
          <div class="list-group-item">
            <div class="d-flex justify-content-between">
              <strong>{{ $msg->sender->name ?? 'Unknown' }}</strong>
              <small>{{ $msg->created_at->format('Y-m-d H:i') }}</small>
            </div>
            <div>{{ $msg->message }}</div>
            <small class="text-muted">Sub #{{ $msg->shared_subscription_id ?? 'N/A' }} | To: {{ $msg->receiver->name ?? 'Group' }}</small>
          </div>
          @empty
          <div class="list-group-item text-center py-4">No messages found.</div>
          @endforelse
        </div>
        <div class="card-body">{{ $messages->links() }}</div>
      </div>
    </div>
  </div>
</div>
@endsection
