@extends('unit-admin.layout')
@section('title', 'Members')
@section('page_title', 'Members')

@section('content')

{{-- FILTER BAR --}}
<div class="card">
  <form method="GET" action="{{ route('unit-admin.members') }}">
    <div style="display:flex;gap:10px;flex-wrap:wrap;align-items:flex-end;padding:14px 18px;">
      <div class="fg" style="margin:0;flex:1;min-width:120px;">
        <label>Status</label>
        <select name="status">
          <option value="">All Status</option>
          <option value="PENDING"  {{ ($status ?? '') === 'PENDING'  ? 'selected' : '' }}>Pending</option>
          <option value="APPROVED" {{ ($status ?? '') === 'APPROVED' ? 'selected' : '' }}>Approved</option>
          <option value="ACTIVE"   {{ ($status ?? '') === 'ACTIVE'   ? 'selected' : '' }}>Active</option>
          <option value="REJECTED" {{ ($status ?? '') === 'REJECTED' ? 'selected' : '' }}>Rejected</option>
        </select>
      </div>
      <div class="fg" style="margin:0;flex:1;min-width:120px;">
        <label>Membership</label>
        <select name="membership_type">
          <option value="">All Types</option>
          <option value="LIFE"   {{ ($membership_type ?? '') === 'LIFE'   ? 'selected' : '' }}>Life</option>
          <option value="ANNUAL" {{ ($membership_type ?? '') === 'ANNUAL' ? 'selected' : '' }}>Annual</option>
        </select>
      </div>
      <div style="display:flex;gap:6px;">
        <button type="submit" class="btn bp bsm"><i class="fas fa-filter"></i> Filter</button>
        <a href="{{ route('unit-admin.members') }}" class="btn bo bsm"><i class="fas fa-times"></i> Clear</a>
      </div>
    </div>
  </form>
</div>

{{-- MEMBERS TABLE --}}
<div class="card">
  <div class="ch">
    <div class="ct">
      <i class="fas fa-users"></i>
      Unit Members
      <span style="font-size:10px;color:var(--text-dim);font-weight:400;">({{ $members->count() }})</span>
    </div>
    {{-- ADD MEMBER BUTTON --}}
    <button class="btn bp bsm" onclick="om('addMemberM')">
      <i class="fas fa-plus"></i> Add Member
    </button>
  </div>

  @if($members->isEmpty())
    <div class="empty-state">
      <i class="fas fa-users"></i>
      <p>No members found</p>
      <button class="btn bp bsm" style="margin-top:10px;" onclick="om('addMemberM')">
        <i class="fas fa-plus"></i> Add First Member
      </button>
    </div>
  @else
    <div class="tw">
      <table>
        <thead>
          <tr>
            <th>Member</th>
            <th>Phone</th>
            <th class="hide-mobile">Organization</th>
            <th class="hide-mobile">Designation</th>
            <th>Membership</th>
            <th>Status</th>
            <th class="hide-mobile">Joined</th>
            <th>Actions</th>
          </tr>
        </thead>
        <tbody>
          @foreach($members as $m)
          <tr>
            <td>
              <div class="mc2">
                @if($m->photo)
                  <img src="{{ Storage::url($m->photo) }}"
                       style="width:28px;height:28px;border-radius:6px;object-fit:cover;flex-shrink:0;">
                @else
                  <div class="av2" style="background:rgba(79,142,247,0.15);color:#7eb8ff;">
                    {{ strtoupper(substr($m->user->name, 0, 1)) }}
                  </div>
                @endif
                <div>
                  <div class="mn">{{ $m->user->name }}</div>
                  <div class="me">{{ $m->user->email }}</div>
                </div>
              </div>
            </td>
            <td style="color:var(--text-dim);">{{ $m->user->phone }}</td>
            <td class="hide-mobile">{{ Str::limit($m->organization, 20) }}</td>
            <td class="hide-mobile" style="color:var(--text-dim);">{{ Str::limit($m->designation, 18) }}</td>
            <td>
              @if($m->membership_type === 'LIFE')
                <span class="badge bli">LIFE</span>
              @else
                <span class="badge ban">ANNUAL</span>
              @endif
            </td>
            <td>
              @if($m->status === 'PENDING')
                <span class="badge bpe">PENDING</span>
              @elseif($m->status === 'APPROVED')
                <span class="badge bap">APPROVED</span>
              @elseif($m->status === 'ACTIVE')
                <span class="badge bap">ACTIVE</span>
              @elseif($m->status === 'REJECTED')
                <span class="badge brj">REJECTED</span>
              @else
                <span class="badge bac">{{ $m->status }}</span>
              @endif
            </td>
            <td class="hide-mobile" style="color:var(--text-dim);">
              {{ $m->created_at->format('d M Y') }}
            </td>
            <td>
              <div class="abr">
                {{-- VIEW --}}
                <button class="ab vw" title="View Details"
                        onclick="viewMember({{ $m->id }})">
                  <i class="fas fa-eye"></i>
                </button>

                {{-- APPROVE --}}
                @if(in_array($m->status, ['PENDING', 'REJECTED']))
                  <form method="POST" action="{{ route('unit-admin.members.approve') }}" style="display:inline;">
                    @csrf
                    <input type="hidden" name="id" value="{{ $m->id }}">
                    <button type="submit" class="ab app" title="Approve"
                            onclick="return confirm('Approve {{ addslashes($m->user->name) }}?')">
                      <i class="fas fa-check"></i>
                    </button>
                  </form>
                @endif

                {{-- REJECT --}}
                @if(in_array($m->status, ['PENDING', 'APPROVED', 'ACTIVE']))
                  <form method="POST" action="{{ route('unit-admin.members.reject') }}" style="display:inline;">
                    @csrf
                    <input type="hidden" name="id" value="{{ $m->id }}">
                    <button type="submit" class="ab rej" title="Reject"
                            onclick="return confirm('Reject {{ addslashes($m->user->name) }}?')">
                      <i class="fas fa-times"></i>
                    </button>
                  </form>
                @endif
              </div>
            </td>
          </tr>
          @endforeach
        </tbody>
      </table>
    </div>
  @endif
</div>

{{-- ══ ADD MEMBER MODAL ══ --}}
<div id="addMemberM" class="mo">
  <div class="md" style="width:580px">
    <div class="mh">
      <span class="mt2"><i class="fas fa-user-plus" style="color:var(--accent);margin-right:6px;"></i>Add New Member</span>
      <div class="mc3" onclick="cm('addMemberM')"><i class="fas fa-times"></i></div>
    </div>
    <form method="POST" action="{{ route('unit-admin.members.store') }}" enctype="multipart/form-data">
      @csrf

      {{-- PERSONAL INFO --}}
      <div style="padding:14px 18px 0;font-size:10px;font-weight:700;text-transform:uppercase;letter-spacing:1px;color:var(--accent);">
        Personal Info
      </div>
      <div class="fgrid">
        <div class="fg">
          <label>Full Name</label>
          <input type="text" name="name" placeholder="Rajesh Kumar" required>
        </div>
        <div class="fg">
          <label>Email</label>
          <input type="email" name="email" placeholder="rajesh@gmail.com" required>
        </div>
        <div class="fg">
          <label>Phone</label>
          <input type="text" name="phone" placeholder="9845002001" required>
        </div>
        <div class="fg">
          <label>Password</label>
          <input type="password" name="password" placeholder="Min 8 characters" required>
        </div>
        <div class="fg">
          <label>Date of Birth</label>
          <input type="date" name="dob" required>
        </div>
        <div class="fg">
          <label>Gender</label>
          <select name="gender" required>
            <option value="">Select Gender</option>
            <option value="male">Male</option>
            <option value="female">Female</option>
            <option value="other">Other</option>
          </select>
        </div>
        <div class="fg s2">
          <label>Photo (optional)</label>
          <input type="file" name="photo" accept="image/jpg,image/jpeg,image/png" style="padding:6px 11px;">
        </div>
      </div>

      {{-- PROFESSIONAL INFO --}}
      <div style="padding:6px 18px 0;font-size:10px;font-weight:700;text-transform:uppercase;letter-spacing:1px;color:var(--accent);">
        Professional Info
      </div>
      <div class="fgrid">
        <div class="fg">
          <label>Organization</label>
          <input type="text" name="organization" placeholder="Bangalore Public School" required>
        </div>
        <div class="fg">
          <label>Designation</label>
          <input type="text" name="designation" placeholder="Principal / Teacher" required>
        </div>
        <div class="fg">
          <label>Experience (years)</label>
          <input type="number" name="experience" placeholder="0" min="0" max="50" required>
        </div>
        <div class="fg">
          <label>Website (optional)</label>
          <input type="url" name="website" placeholder="https://example.com">
        </div>
      </div>

      {{-- ADDRESS --}}
      <div style="padding:6px 18px 0;font-size:10px;font-weight:700;text-transform:uppercase;letter-spacing:1px;color:var(--accent);">
        Address
      </div>
      <div class="fgrid">
        <div class="fg s2">
          <label>Full Address</label>
          <input type="text" name="address" placeholder="12 MG Road, Bangalore" required>
        </div>
        <div class="fg">
          <label>Pincode</label>
          <input type="text" name="pincode" placeholder="560001" required>
        </div>
      </div>

      {{-- MEMBERSHIP PLAN --}}
      <div style="padding:6px 18px 0;font-size:10px;font-weight:700;text-transform:uppercase;letter-spacing:1px;color:var(--accent);">
        Membership Plan
      </div>
      <div class="fgrid">
        <div class="fg s2">
          <label>Select Plan</label>
          <select name="plan_id" required>
            <option value="">Choose a plan</option>
            @foreach($plans as $plan)
              <option value="{{ $plan->id }}">
                {{ $plan->name }} ({{ $plan->type }}) — ₹{{ number_format($plan->amount, 0) }}
              </option>
            @endforeach
          </select>
        </div>
      </div>

      {{-- Unit, district, state are auto-assigned from unit admin's unit --}}
      <div style="margin:8px 18px 14px;padding:10px 12px;background:rgba(79,142,247,0.07);border-radius:8px;font-size:11px;color:var(--text-dim);">
        <i class="fas fa-info-circle" style="color:var(--accent)"></i>
        Member will be automatically assigned to <b style="color:var(--accent)">{{ $myUnit->name }}</b> unit
        and created with <b style="color:var(--orange)">PENDING</b> status.
      </div>

      <div class="ff">
        <button type="button" class="btn bo" onclick="cm('addMemberM')">Cancel</button>
        <button type="submit" class="btn bp">
          <i class="fas fa-user-plus"></i> Create Member
        </button>
      </div>
    </form>
  </div>
</div>

{{-- MEMBER DETAIL MODAL --}}
<div class="mo" id="memberModal">
  <div class="md md-lg">
    <div class="mh">
      <span class="mt2"><i class="fas fa-user" style="color:var(--accent);margin-right:6px;"></i>Member Details</span>
      <div class="mc3" onclick="cm('memberModal')"><i class="fas fa-times"></i></div>
    </div>
    <div id="memberModalBody">
      <div style="padding:32px;text-align:center;color:var(--text-dim);">
        <i class="fas fa-spinner fa-spin" style="font-size:20px;"></i>
      </div>
    </div>
  </div>
</div>

@endsection

@section('scripts')
<script>
function viewMember(id) {
  om('memberModal');
  document.getElementById('memberModalBody').innerHTML =
    '<div style="padding:32px;text-align:center;color:var(--text-dim);"><i class="fas fa-spinner fa-spin" style="font-size:20px;"></i></div>';

  fetch(`/unit-admin/members/${id}/detail`)
    .then(r => r.json())
    .then(d => {
      document.getElementById('memberModalBody').innerHTML = `
        <div class="dg">
          <div class="df"><div class="dl">Full Name</div><div class="dv">${d.name}</div></div>
          <div class="df"><div class="dl">Email</div><div class="dv">${d.email}</div></div>
          <div class="df"><div class="dl">Phone</div><div class="dv">${d.phone}</div></div>
          <div class="df"><div class="dl">Gender</div><div class="dv">${capitalize(d.gender)}</div></div>
          <div class="df"><div class="dl">Date of Birth</div><div class="dv">${d.dob}</div></div>
          <div class="df"><div class="dl">Experience</div><div class="dv">${d.experience} years</div></div>
          <div class="df s2"><div class="dl">Organization</div><div class="dv">${d.organization}</div></div>
          <div class="df"><div class="dl">Designation</div><div class="dv">${d.designation}</div></div>
          <div class="df"><div class="dl">Unit</div><div class="dv">${d.unit_name}</div></div>
          <div class="df"><div class="dl">District</div><div class="dv">${d.district_name}</div></div>
          <div class="df"><div class="dl">State</div><div class="dv">${d.state_name}</div></div>
          <div class="df s2"><div class="dl">Address</div><div class="dv">${d.address}, ${d.pincode}</div></div>
          <div class="df"><div class="dl">Membership Type</div><div class="dv">${d.membership_type}</div></div>
          <div class="df"><div class="dl">Membership ID</div><div class="dv">${d.membership_id}</div></div>
          <div class="df"><div class="dl">Status</div><div class="dv">${d.status}</div></div>
          <div class="df"><div class="dl">Registered On</div><div class="dv">${d.registered_on}</div></div>
          ${d.joined_date && d.joined_date !== '—' ? `<div class="df"><div class="dl">Joined Date</div><div class="dv">${d.joined_date}</div></div>` : ''}
          ${d.expiry_date && d.expiry_date !== '—' ? `<div class="df"><div class="dl">Expiry Date</div><div class="dv">${d.expiry_date}</div></div>` : ''}
          ${d.website && d.website !== '—' ? `<div class="df s2"><div class="dl">Website</div><div class="dv"><a href="${d.website}" target="_blank" style="color:var(--accent);">${d.website}</a></div></div>` : ''}
        </div>
      `;
    })
    .catch(() => {
      document.getElementById('memberModalBody').innerHTML =
        '<div style="padding:24px;text-align:center;color:var(--red);">Failed to load member details.</div>';
    });
}

function capitalize(str) {
  return str ? str.charAt(0).toUpperCase() + str.slice(1) : '—';
}
</script>

@endsection