@extends('layouts.admin')
@section('title', 'Events')
@section('page_title', 'Events')

@section('content')

  <div class="card">
    <div class="ch">
      <div class="ct">
        <i class="fas fa-calendar-alt"></i>All Events
      </div>
      <button class="btn bp bsm" onclick="om('addEventM')">
        <i class="fas fa-plus"></i>Create Event
      </button>
    </div>

    <div class="tw">
      <table>
        <thead>
          <tr>
            <th>#</th>
            <th>Event</th>
            <th>Date & Time</th>
            <th>Location</th>
            <th>Ticket</th>
            <th>Seats</th>
            <th>Status</th>
            <th>Actions</th>
          </tr>
        </thead>
        <tbody>
          @forelse($events as $event)
                  <tr>
                    <td style="color:var(--text-dim)">
                      {{ $loop->iteration }}
                    </td>
                    <td>
                      <div>
                        <div class="mn">{{ $event->title }}</div>
                        <div class="me">
                          {{ $event->is_online ? '🌐 Online' : '📍 Physical' }}
                        </div>
                      </div>
                    </td>
                    <td style="color:var(--text-dim)">
                      <div>{{ $event->event_date->format('d M Y') }}</div>
                      <div style="font-size:10px;">
                        {{ $event->event_time }}
                      </div>
                    </td>
                    <td style="color:var(--text-dim)">
                      {{ $event->location ?? 'Online' }}
                    </td>
                    <td>
                      <span class="badge
                        {{ $event->ticket_type == 'FREE' ? 'bap' : 'bpe' }}">
                        {{ $event->ticket_type }}
                        @if($event->ticket_type == 'PAID')
                          ₹{{ number_format($event->ticket_price, 0) }}
                        @endif
                      </span>
                    </td>
                    <td style="color:var(--text-dim)">
                      <div>{{ $event->registered_count }} registered</div>
                      <div style="font-size:10px;">
                        {{ $event->total_seats == 0
              ? 'Unlimited'
              : ($event->total_seats - $event->registered_count)
              . ' left' }}
                      </div>
                    </td>
                    <td>
                      <select onchange="updateStatus({{ $event->id }}, this.value)" style="padding:3px 7px;font-size:10px;
                               border-radius:20px;width:auto;
                               background:transparent;
                               border:1px solid var(--border);
                               color:
                               @if($event->status == 'UPCOMING') var(--accent)
                               @elseif($event->status == 'ONGOING') var(--green)
                               @elseif($event->status == 'COMPLETED') var(--text-dim)
                               @else var(--red) @endif;
                               cursor:pointer;">
                        <option value="UPCOMING" {{ $event->status == 'UPCOMING' ? 'selected' : '' }}>
                          UPCOMING
                        </option>
                        <option value="ONGOING" {{ $event->status == 'ONGOING' ? 'selected' : '' }}>
                          ONGOING
                        </option>
                        <option value="COMPLETED" {{ $event->status == 'COMPLETED' ? 'selected' : '' }}>
                          COMPLETED
                        </option>
                        <option value="CANCELLED" {{ $event->status == 'CANCELLED' ? 'selected' : '' }}>
                          CANCELLED
                        </option>
                      </select>

                      {{-- Hidden form for status update --}}
                      <form id="statusForm{{ $event->id }}" method="POST" action="{{ route('admin.events.status') }}"
                        style="display:none">
                        @csrf
                        <input type="hidden" name="id" value="{{ $event->id }}">
                        <input type="hidden" name="status" id="statusVal{{ $event->id }}">
                      </form>
                    </td>
                    <td>
                      <div class="abr">
                        {{-- VIEW REGISTRATIONS --}}
                        <a href="{{ route(
              'admin.events.registrations',
              $event->id
            ) }}" class="ab vw" title="View Registrations">
                          <i class="fas fa-users"></i>
                        </a>

                        {{-- EDIT --}}
                        <div class="ab ed" onclick="editEvent({{ $event->id }})" title="Edit">
                          <i class="fas fa-edit"></i>
                        </div>

                        {{-- DELETE --}}
                        <form method="POST" action="{{ route('admin.events.delete') }}" style="display:inline" onsubmit="return confirm(
                                'Delete {{ addslashes($event->title) }}?')">
                          @csrf @method('DELETE')
                          <input type="hidden" name="id" value="{{ $event->id }}">
                          <button type="submit" class="ab rej" title="Delete">
                            <i class="fas fa-trash"></i>
                          </button>
                        </form>
                      </div>
                    </td>
                  </tr>
          @empty
            <tr>
              <td colspan="8" style="text-align:center;
                       color:var(--text-dim);
                       padding:40px;">
                <div style="font-size:32px;margin-bottom:10px;">📅</div>
                <div style="font-size:13px;font-weight:600;
                            margin-bottom:6px;">
                  No events yet
                </div>
                <div style="font-size:11px;color:var(--text-dim);
                            margin-bottom:14px;">
                  Create your first event
                </div>
                <button class="btn bp bsm" onclick="om('addEventM')">
                  <i class="fas fa-plus"></i>Create Event
                </button>
              </td>
            </tr>
          @endforelse
        </tbody>
      </table>
    </div>
  </div>

  {{-- ══ ADD EVENT MODAL ══ --}}
  <div id="addEventM" class="mo">
    <div class="md" style="width:600px">
      <div class="mh">
        <span class="mt2">Create New Event</span>
        <div class="mc3" onclick="cm('addEventM')">
          <i class="fas fa-times"></i>
        </div>
      </div>
      <form method="POST" action="{{ route('admin.events.store') }}" enctype="multipart/form-data">
        @csrf

        {{-- BASIC INFO --}}
        <div style="padding:14px 18px 0;font-size:10px;
                    font-weight:700;text-transform:uppercase;
                    letter-spacing:1px;color:var(--accent);">
          Event Info
        </div>
        <div class="fgrid">
          <div class="fg s2">
            <label>Event Title</label>
            <input type="text" name="title" placeholder="Enter event title" required>
          </div>
          <div class="fg s2">
            <label>Description</label>
            <textarea name="description" placeholder="Describe the event..." style="min-height:80px" required></textarea>
          </div>
          <div class="fg">
            <label>Event Date</label>
            <input type="date" name="event_date" required>
          </div>
          <div class="fg">
            <label>Event Time</label>
            <input type="time" name="event_time" required>
          </div>
          <div class="fg s2">
            <label>Image (optional)</label>
            <input type="file" name="image" accept="image/jpg,image/jpeg,image/png" style="padding:6px 11px;">
          </div>
        </div>

        {{-- LOCATION --}}
        <div style="padding:0 18px;font-size:10px;
                    font-weight:700;text-transform:uppercase;
                    letter-spacing:1px;color:var(--accent);">
          Location
        </div>
        <div class="fgrid">
          <div class="fg">
            <label>Event Type</label>
            <select name="is_online" onchange="toggleOnline(this.value)" required>
              <option value="0">Physical Event</option>
              <option value="1">Online Event</option>
            </select>
          </div>
          <div class="fg" id="locationField">
            <label>Venue / Location</label>
            <input type="text" name="location" placeholder="Kozhikode Convention Centre">
          </div>
          <div class="fg s2" id="onlineField" style="display:none">
            <label>Online Link (Zoom/Meet)</label>
            <input type="url" name="online_link" placeholder="https://zoom.us/j/...">
          </div>
        </div>

        {{-- TICKET --}}
        <div style="padding:0 18px;font-size:10px;
                    font-weight:700;text-transform:uppercase;
                    letter-spacing:1px;color:var(--accent);">
          Ticket & Seats
        </div>
        <div class="fgrid">
          <div class="fg">
            <label>Ticket Type</label>
            <select name="ticket_type" onchange="togglePrice(this.value)" required>
              <option value="FREE">Free</option>
              <option value="PAID">Paid</option>
            </select>
          </div>
          <div class="fg" id="priceField" style="display:none">
            <label>Ticket Price (₹)</label>
            <input type="number" name="ticket_price" placeholder="Enter amount" min="0">
          </div>
          <div class="fg">
            <label>Total Seats (0 = Unlimited)</label>
            <input type="number" name="total_seats" placeholder="0" min="0" value="0" required>
          </div>
          <div class="fg">
            <label>Registration Deadline</label>
            <input type="date" name="registration_deadline">
          </div>
        </div>

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

  {{-- ══ EDIT EVENT MODAL ══ --}}
  <div id="editEventM" class="mo">
    <div class="md" style="width:600px">
      <div class="mh">
        <span class="mt2">Edit Event</span>
        <div class="mc3" onclick="cm('editEventM')">
          <i class="fas fa-times"></i>
        </div>
      </div>
      <form method="POST" action="{{ route('admin.events.update') }}" enctype="multipart/form-data">
        @csrf
        <input type="hidden" name="id" id="editEventId">

        <div style="padding:14px 18px 0;font-size:10px;
                    font-weight:700;text-transform:uppercase;
                    letter-spacing:1px;color:var(--accent);">
          Event Info
        </div>
        <div class="fgrid">
          <div class="fg s2">
            <label>Event Title</label>
            <input type="text" name="title" id="editEventTitle" required>
          </div>
          <div class="fg s2">
            <label>Description</label>
            <textarea name="description" id="editEventDesc" style="min-height:80px" required></textarea>
          </div>
          <div class="fg">
            <label>Event Date</label>
            <input type="date" name="event_date" id="editEventDate" required>
          </div>
          <div class="fg">
            <label>Event Time</label>
            <input type="time" name="event_time" id="editEventTime" required>
          </div>
          <div class="fg">
            <label>Location</label>
            <input type="text" name="location" id="editEventLocation">
          </div>
          <div class="fg">
            <label>Ticket Price (₹)</label>
            <input type="number" name="ticket_price" id="editEventPrice" min="0">
          </div>
          <div class="fg">
            <label>Total Seats</label>
            <input type="number" name="total_seats" id="editEventSeats" min="0" required>
          </div>
          <div class="fg">
            <label>Registration Deadline</label>
            <input type="date" name="registration_deadline" id="editEventDeadline">
          </div>
          <div class="fg s2">
            <label>New Image (optional)</label>
            <input type="file" name="image" accept="image/jpg,image/jpeg,image/png" style="padding:6px 11px;">
          </div>
        </div>

        <div class="ff">
          <button type="button" class="btn bo" onclick="cm('editEventM')">Cancel</button>
          <button type="submit" class="btn bp">
            <i class="fas fa-save"></i>Update Event
          </button>
        </div>
      </form>
    </div>
  </div>

@endsection

@section('scripts')
<script>
function toggleOnline(val) {
  document.getElementById('locationField').style.display =
    val == '1' ? 'none' : 'block';
  document.getElementById('onlineField').style.display =
    val == '1' ? 'block' : 'none';
}

function togglePrice(val) {
  document.getElementById('priceField').style.display =
    val == 'PAID' ? 'block' : 'none';
}

// ── FETCH EVENT DATA AND OPEN MODAL ──
function editEvent(id) {
  fetch(`/admin/events/${id}/detail`)
    .then(r => r.json())
    .then(e => {
      document.getElementById('editEventId').value       = id;
      document.getElementById('editEventTitle').value    = e.title;
      document.getElementById('editEventDesc').value     = e.description;
      document.getElementById('editEventDate').value     = e.event_date_raw;
      document.getElementById('editEventTime').value     = e.event_time;
      document.getElementById('editEventLocation').value = e.location ?? '';
      document.getElementById('editEventPrice').value    = e.ticket_price;
      document.getElementById('editEventSeats').value    = e.total_seats;
      document.getElementById('editEventDeadline').value = e.deadline_raw ?? '';
      om('editEventM');
    })
    .catch(err => {
      alert('Failed to load event data!');
      console.error(err);
    });
}

function updateStatus(id, status) {
  if (!confirm('Change status to ' + status + '?')) {
    location.reload();
    return;
  }
  document.getElementById('statusVal' + id).value = status;
  document.getElementById('statusForm' + id).submit();
}
</script>
@endsection