@extends('admin.layout.template')
@section('title', 'Manage Events')
@section('content')

<div class="page-content">
    <div class="container-xxl">

        <!-- Add Event -->
        <div class="card">
            <div class="card-header"><h4 class="card-title">Add New Event</h4></div>
            <div class="card-body">
                <form id="addEventForm" enctype="multipart/form-data">
                    @csrf
                    <div class="row">
                        <div class="col-lg-4 mb-3">
                            <label class="form-label">Event Name</label>
                            <input type="text" name="name" class="form-control" required>
                        </div>
                        <div class="col-lg-4 mb-3">
                            <label class="form-label">Type</label>
                            <select name="type" class="form-select">
                                <option value="cricket">Cricket</option>
                                <option value="football">Football</option>
                                <option value="concert">Concert</option>
                                <option value="other">Other</option>
                            </select>
                        </div>
                        <div class="col-lg-4 mb-3">
                            <label class="form-label">Stadium</label>
                            <select name="stadium_id" class="form-select">
                                <option value="">-- Select Stadium --</option>
                                @foreach(App\Models\Stadium::all() as $s)
                                    <option value="{{ $s->id }}">{{ $s->name }}</option>
                                @endforeach
                            </select>
                        </div>

                        <div class="col-lg-4 mb-3">
                            <label class="form-label">Team A</label>
                            <select name="team_a_id" class="form-select">
                                <option value="">-- Select Team --</option>
                                @foreach(App\Models\Team::all() as $t)
                                    <option value="{{ $t->id }}">{{ $t->name }}</option>
                                @endforeach
                            </select>
                        </div>
                        <div class="col-lg-4 mb-3">
                            <label class="form-label">Team B</label>
                            <select name="team_b_id" class="form-select">
                                <option value="">-- Select Team --</option>
                                @foreach(App\Models\Team::all() as $t)
                                    <option value="{{ $t->id }}">{{ $t->name }}</option>
                                @endforeach
                            </select>
                        </div>
                        <div class="col-lg-4 mb-3">
                            <label class="form-label">Match Format</label>
                            <input type="text" name="match_format" class="form-control" placeholder="e.g. T20, ODI">
                        </div>
                        <div class="col-lg-4 mb-3">
                            <label class="form-label">Start Time</label>
                            <input type="datetime-local" name="start_time" class="form-control" required>
                        </div>
                        <div class="col-lg-4 mb-3">
                            <label class="form-label">End Time</label>
                            <input type="datetime-local" name="end_time" class="form-control">
                        </div>
                        <div class="col-lg-4 mb-3">
                            <label class="form-label">Status</label>
                            <select name="status" class="form-select">
                                <option value="scheduled">Scheduled</option>
                                <option value="live">Live</option>
                                <option value="completed">Completed</option>
                            </select>
                        </div>
                        <div class="col-lg-6 mb-3">
                            <label class="form-label">Banner Image</label>
                            <input type="file" name="banner_image" class="form-control" accept="image/*">
                        </div>
                        <div class="col-lg-12 mb-3">
                            <label class="form-label">Description</label>
                            <textarea name="description" class="form-control" rows="3"></textarea>
                        </div>
                    </div>
                    <div class="text-end">
                        <button type="submit" class="btn btn-success">Save Event</button>
                    </div>
                </form>
            </div>
        </div>

        <!-- Events Table -->
        <div class="card mt-4">
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table align-middle table-hover table-centered">
                        <thead class="bg-light-subtle">
                            <tr>
                                 <th>#</th>
                <th>Name</th>
                <th>Type</th>
                <th>Stadium</th>
                <th>Team A</th>
                <th>Team B</th>
                <th>Start Time</th>
                <th>End Time</th>
                <th>Status</th>
                <th>Banner</th>
                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody></tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Edit Event Modal -->
<div class="modal fade" id="editEventModal" tabindex="-1">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header bg-primary text-white">
        <h5 class="modal-title">Edit Event</h5>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <form id="editEventForm" enctype="multipart/form-data">
          @csrf
          <input type="hidden" name="event_id" id="edit_event_id">

          <div class="row">
            <div class="col-md-6 mb-3">
              <label class="form-label">Event Name</label>
              <input type="text" name="name" id="edit_name" class="form-control" required>
            </div>

            <div class="col-md-6 mb-3">
              <label class="form-label">Event Type</label>
              <select name="type" id="edit_type" class="form-select" required>
                <option value="cricket">Cricket</option>
                <option value="football">Football</option>
                <option value="concert">Concert</option>
                <option value="other">Other</option>
              </select>
            </div>

            <div class="col-md-6 mb-3">
              <label class="form-label">Stadium</label>
              <select name="stadium_id" id="edit_stadium_id" class="form-select">
                <option value="">-- Select Stadium --</option>
                @foreach(App\Models\Stadium::all() as $s)
                  <option value="{{ $s->id }}">{{ $s->name }}</option>
                @endforeach
              </select>
            </div>

            <div class="col-md-6 mb-3">
              <label class="form-label">Team A</label>
              <select name="team_a_id" id="edit_team_a_id" class="form-select">
                <option value="">-- Select Team A --</option>
                @foreach(App\Models\Team::all() as $t)
                  <option value="{{ $t->id }}">{{ $t->name }}</option>
                @endforeach
              </select>
            </div>

            <div class="col-md-6 mb-3">
              <label class="form-label">Team B</label>
              <select name="team_b_id" id="edit_team_b_id" class="form-select">
                <option value="">-- Select Team B --</option>
                @foreach(App\Models\Team::all() as $t)
                  <option value="{{ $t->id }}">{{ $t->name }}</option>
                @endforeach
              </select>
            </div>

            <div class="col-md-6 mb-3">
              <label class="form-label">Match Format</label>
              <input type="text" name="match_format" id="edit_match_format" class="form-control" placeholder="T20, ODI, Test, etc.">
            </div>

            <div class="col-md-6 mb-3">
              <label class="form-label">Start Time</label>
              <input type="datetime-local" name="start_time" id="edit_start_time" class="form-control" required>
            </div>

            <div class="col-md-6 mb-3">
              <label class="form-label">End Time</label>
              <input type="datetime-local" name="end_time" id="edit_end_time" class="form-control">
            </div>

            <div class="col-md-6 mb-3">
              <label class="form-label">Status</label>
              <select name="status" id="edit_status" class="form-select">
                <option value="scheduled">Scheduled</option>
                <option value="live">Live</option>
                <option value="completed">Completed</option>
              </select>
            </div>

            <div class="col-md-12 mb-3">
              <label class="form-label">Description</label>
              <textarea name="description" id="edit_description" class="form-control" rows="3"></textarea>
            </div>

            <div class="col-md-12 mb-3">
              <label class="form-label">Banner Image</label>
              <input type="file" name="banner_image" class="form-control">
              <img id="current_banner" src="" class="mt-2" width="120" style="display:none; border-radius:10px;">
            </div>
          </div>
        </form>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
        <button type="button" class="btn btn-success" id="saveEventChanges">Update Event</button>
      </div>
    </div>
  </div>
</div>

<script>
$(function(){
    var table = $('.table').DataTable({
        processing:true,
        serverSide:true,
        ajax:"{{ route('get-events') }}",
        columns:[
            {data:'DT_RowIndex', name:'DT_RowIndex', orderable:false, searchable:false},
            {data:'name', name:'name'},
            {data:'type', name:'type'},
            {data:'stadium_name', name:'stadium_name'},
            {data:'team_a', name:'team_a'},
            {data:'team_b', name:'team_b'},
            {data:'start_time', name:'start_time'},
            {data:'end_time', name:'end_time'},
            {data:'status', name:'status'},
            {data:'banner', name:'banner', orderable:false, searchable:false},
            {data:'action', name:'action', orderable:false, searchable:false},
        ]
    });

   $(document).on('click', '.editEvent', function() {
    var id = $(this).data('id');

    $.ajax({
        url: "/get-event/" + id,
        type: "GET",
        success: function(res) {
            var e = res.event;

            $('#edit_event_id').val(e.id);
            $('#edit_name').val(e.name);
            $('#edit_type').val(e.type);
            $('#edit_stadium_id').val(e.stadium_id);
            $('#edit_team_a_id').val(e.team_a_id);
            $('#edit_team_b_id').val(e.team_b_id);
            $('#edit_start_time').val(e.start_time.replace(' ', 'T'));
            $('#edit_end_time').val(e.end_time ? e.end_time.replace(' ', 'T') : '');
            $('#edit_status').val(e.status);
            $('#edit_match_format').val(e.match_format);
            $('#edit_description').val(e.description);

            if (e.banner_image) {
                $('#current_banner').attr('src', '/' + e.banner_image).show();
            } else {
                $('#current_banner').hide();
            }

            $('#editEventModal').modal('show');
        }
    });
});
  // ADD
    $('#addEventForm').submit(function(e){
        e.preventDefault();
        var formData = new FormData(this);
        $.ajax({
            url: "{{ route('add-event') }}",
            method:'POST',
            data: formData,
            processData:false,
            contentType:false,
            success:function(res){
                Swal.fire({icon:'success', title:'Added!', text:res.success, timer:1500, showConfirmButton:false});
                $('#addEventForm')[0].reset();
                table.ajax.reload();
            },
            error:function(xhr){
                let err = Object.values(xhr.responseJSON.errors).join("\n");
                Swal.fire({icon:'error', title:'Error', text:err});
            }
        });
    });

$('#saveEventChanges').click(function(){
    var id = $('#edit_event_id').val();
    var formData = new FormData($('#editEventForm')[0]);
    formData.append('_method', 'POST');

    $.ajax({
        url: "/update-event/" + id,
        type: "POST",
        data: formData,
        contentType: false,
        processData: false,
        success: function(res){
            Swal.fire({ icon: 'success', title: 'Updated!', text: res.success, timer: 1500 });
            $('#editEventModal').modal('hide');
            $('.table').DataTable().ajax.reload();
        },
        error: function(xhr){
            let errMsg = Object.values(xhr.responseJSON.errors).join("\n");
            Swal.fire({ icon: 'error', title: 'Error', text: errMsg });
        }
    });
});

  
    // CANCEL EDIT
    $(document).on('click','.cancelEdit',function(){
        table.ajax.reload();
    });

    

    // DELETE
    $(document).on('click','.deleteEvent',function(){
        let id=$(this).data('id');
        Swal.fire({title:'Delete?', text:'This will remove the event.', icon:'warning', showCancelButton:true})
        .then(res=>{
            if(res.isConfirmed){
                $.ajax({
                    url:"{{ url('/delete-event') }}/"+id,
                    method:'DELETE',
                    data:{_token:'{{ csrf_token() }}'},
                    success:function(r){
                        Swal.fire({icon:'success', title:'Deleted!', timer:1200, showConfirmButton:false});
                        table.ajax.reload();
                    }
                });
            }
        });
    });

    function formatDateForInput(dt){
        if(!dt) return '';
        const d = new Date(dt);
        const off = d.getTimezoneOffset();
        const local = new Date(d.getTime() - off*60*1000);
        return local.toISOString().slice(0,16);
    }
});
</script>
@endsection
