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

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

        <!-- Add Stadium -->
        <div class="row">
            <div class="col-lg-12">
                <div class="card">
                    <div class="card-header">
                        <h4 class="card-title d-flex align-items-center gap-1">
                            <iconify-icon icon="solar:stadium-bold-duotone" class="text-primary fs-20"></iconify-icon>
                            Add Stadium
                        </h4>
                    </div>
                    <div class="card-body">
                        <form id="addStadiumForm" enctype="multipart/form-data">
                            @csrf
                            <div class="row">
                                <div class="col-lg-6">
                                    <div class="mb-3">
                                        <label class="form-label">Stadium Name</label>
                                        <input type="text" name="name" class="form-control" placeholder="Enter stadium name" required>
                                    </div>
                                </div>
                                <div class="col-lg-6">
                                    <div class="mb-3">
                                        <label class="form-label">City</label>
                                        <input type="text" name="city" class="form-control" placeholder="Enter city name">
                                    </div>
                                </div>
                                <div class="col-lg-6">
                                    <div class="mb-3">
                                        <label class="form-label">Country</label>
                                        <input type="text" name="country" class="form-control" placeholder="Enter country">
                                    </div>
                                </div>
                                <div class="col-lg-6">
                                    <div class="mb-3">
                                        <label class="form-label">Layout Image</label>
                                        <input type="file" name="photo" class="form-control" accept="image/*">
                                    </div>
                                </div>
                            </div>
                            <div class="text-end">
                                <button type="submit" class="btn btn-success">Save Stadium</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>

        <!-- Stadium Table -->
        <div class="row">
            <div class="col-xl-12">
                <div class="card">
                    <div class="card-body p-0">
                        <div class="table-responsive">
                            <table class="table align-middle mb-0 table-hover table-centered">
                                <thead class="bg-light-subtle">
                                    <tr>
                                        <th>SL.NO</th>
                                        <th>Stadium Name</th>
                                        <th>City</th>
                                        <th>Country</th>
                                        <th>Layout Image</th>
                                        <th>Action</th>
                                    </tr>
                                </thead>
                                <tbody></tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>

    </div>
</div>

<script>
$(document).ready(function(){
    var table = $('.table').DataTable({
        processing: true,
        serverSide: true,
        ajax: "{{ route('get-stadiums') }}",
        columns: [
            { data: 'DT_RowIndex', name: 'DT_RowIndex', orderable: false, searchable: false },
            { data: 'name', name: 'name' },
            { data: 'city', name: 'city' },
            { data: 'country', name: 'country' },
            { data: 'layout_image', name: 'layout_image', orderable: false, searchable: false },
            { data: 'action', name: 'action', orderable: false, searchable: false },
        ]
    });

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

    // Delete
    $(document).on('click', '.deleteStadium', function(){
        var id = $(this).data('id');
        Swal.fire({
            title:'Are you sure?',
            text:'This will delete the stadium!',
            icon:'warning',
            showCancelButton:true,
            confirmButtonText:'Yes, delete it!'
        }).then(result=>{
            if(result.isConfirmed){
                $.ajax({
                    url: "{{ url('/delete-stadium') }}/"+id,
                    type:'DELETE',
                    data:{_token:'{{ csrf_token() }}'},
                    success:function(response){
                        Swal.fire({ icon:'success', title:'Deleted!', text:response.success, timer:1500, showConfirmButton:false });
                        table.ajax.reload();
                    }
                });
            }
        });
    });

    // Inline Edit (same as Team logic)
    $(document).on('click', '.editStadium', function(){
        var row = $(this).closest('tr');
        var id = $(this).data('id');
        var name = row.find('td:eq(1)').text();
        var city = row.find('td:eq(2)').text();
        var country = row.find('td:eq(3)').text();
        var imgSrc = row.find('td:eq(4) img').attr('src') || '';

        row.find('td:eq(1)').html(`<input type="text" class="form-control form-control-sm" value="${name}">`);
        row.find('td:eq(2)').html(`<input type="text" class="form-control form-control-sm" value="${city}">`);
        row.find('td:eq(3)').html(`<input type="text" class="form-control form-control-sm" value="${country}">`);
        row.find('td:eq(4)').html(`<input type="file" class="form-control form-control-sm" name="photo"><br>${imgSrc ? `<img src="${imgSrc}" height="40">` : ''}`);

        $(this).replaceWith(`<button class="btn btn-sm btn-success saveStadium" data-id="${id}">Save</button> <button class="btn btn-sm btn-secondary cancelEdit">Cancel</button>`);
    });

    $(document).on('click', '.cancelEdit', ()=> table.ajax.reload());

    $(document).on('click', '.saveStadium', function(){
        var id = $(this).data('id');
        var row = $(this).closest('tr');
        var name = row.find('td:eq(1) input').val();
        var city = row.find('td:eq(2) input').val();
        var country = row.find('td:eq(3) input').val();
        var photo = row.find('td:eq(4) input[type=file]')[0].files[0];

        var formData = new FormData();
        formData.append('_token', '{{ csrf_token() }}');
        formData.append('_method', 'POST');
        formData.append('name', name);
        formData.append('city', city);
        formData.append('country', country);
        if(photo) formData.append('photo', photo);

        $.ajax({
            url: "{{ url('/update-stadium') }}/"+id,
            type: 'POST',
            data: formData,
            contentType:false,
            processData:false,
            success:function(response){
                Swal.fire({ icon:'success', title:'Updated!', text:response.success, timer:1500, showConfirmButton:false });
                table.ajax.reload();
            }
        });
    });
});
</script>

@endsection
