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

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

        <!-- Add Block -->
        <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 Block
                </h4>
            </div>
            <div class="card-body">
                <form id="addBlockForm" enctype="multipart/form-data">
                    @csrf
                    <div class="row">
                        <div class="col-lg-4">
                            <div class="mb-3">
                                <label class="form-label">Select Stadium</label>
                                <select name="stadium_id" class="form-select" required>
                                    <option value="">-- Choose Stadium --</option>
                                    @foreach(App\Models\Stadium::all() as $s)
                                        <option value="{{ $s->id }}">{{ $s->name }}</option>
                                    @endforeach
                                </select>
                            </div>
                        </div>

                        <div class="col-lg-4">
                            <div class="mb-3">
                                <label class="form-label">Block Name</label>
                                <input type="text" name="name" class="form-control" placeholder="e.g. BLOCK A, VIP" required>
                            </div>
                        </div>

                        <div class="col-lg-4">
                            <div class="mb-3">
                                <label class="form-label">Position</label>
                                <input type="text" name="position" class="form-control" placeholder="e.g. North Wing, East Gallery">
                            </div>
                        </div>

                        <div class="col-lg-4">
                            <div class="mb-3">
                                <label class="form-label">Capacity</label>
                                <input type="number" name="capacity" class="form-control" placeholder="e.g. 5000" required>
                            </div>
                        </div>

                        <div class="col-lg-4">
                            <div class="mb-3">
                                <label class="form-label">Base Price</label>
                                <input type="number" name="base_price" step="0.01" class="form-control" placeholder="e.g. 1500.00" required>
                            </div>
                        </div>

                        <div class="col-lg-4">
                            <div class="mb-3">
                                <label class="form-label">Block 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 Block</button>
                    </div>
                </form>
            </div>
        </div>

        <!-- Block 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>SL.NO</th>
                                <th>Stadium</th>
                                <th>Block Name</th>
                                <th>Position</th>
                                <th>Capacity</th>
                                <th>Base Price</th>
                                <th>Image</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody></tbody>
                    </table>
                </div>
            </div>
        </div>

    </div>
</div>

<script>
$(document).ready(function(){
    var table = $('.table').DataTable({
        processing: true,
        serverSide: true,
        ajax: "{{ route('get-blocks') }}",
        columns: [
            { data: 'DT_RowIndex', name: 'DT_RowIndex', orderable:false, searchable:false },
            { data: 'stadium_name', name: 'stadium_name' },
            { data: 'name', name: 'name' },
            { data: 'position', name: 'position' },
            { data: 'capacity', name: 'capacity' },
            { data: 'base_price', name: 'base_price' },
            { data: 'image', name: 'image', orderable:false, searchable:false },
            { data: 'action', name: 'action', orderable:false, searchable:false },
        ]
    });

    // Add
    $('#addBlockForm').submit(function(e){
        e.preventDefault();
        var formData = new FormData(this);
        $.ajax({
            url: "{{ route('add-block') }}",
            type: "POST",
            data: formData,
            contentType: false,
            processData: false,
            success: function(res){
                Swal.fire({ icon:'success', title:'Added!', text:res.success, timer:1500, showConfirmButton:false });
                $('#addBlockForm')[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', '.deleteBlock', function(){
        var id = $(this).data('id');
        Swal.fire({
            title:'Are you sure?',
            text:'This will delete the block!',
            icon:'warning',
            showCancelButton:true,
            confirmButtonText:'Yes, delete!'
        }).then(result=>{
            if(result.isConfirmed){
                $.ajax({
                    url: "{{ url('/delete-block') }}/"+id,
                    type:'DELETE',
                    data:{_token:'{{ csrf_token() }}'},
                    success:function(res){
                        Swal.fire({ icon:'success', title:'Deleted!', text:res.success, timer:1500, showConfirmButton:false });
                        table.ajax.reload();
                    }
                });
            }
        });
    });

    // Inline Edit (simple pattern)
    $(document).on('click', '.editBlock', function(){
        var row = $(this).closest('tr');
        var id = $(this).data('id');
        var stadium = row.find('td:eq(1)').text();
        var name = row.find('td:eq(2)').text();
        var position = row.find('td:eq(3)').text();
        var capacity = row.find('td:eq(4)').text();
        var base_price = row.find('td:eq(5)').text();
        var imgSrc = row.find('td:eq(6) img').attr('src') || '';

        row.find('td:eq(2)').html(`<input type="text" class="form-control form-control-sm" value="${name}">`);
        row.find('td:eq(3)').html(`<input type="text" class="form-control form-control-sm" value="${position}">`);
        row.find('td:eq(4)').html(`<input type="number" class="form-control form-control-sm" value="${capacity}">`);
        row.find('td:eq(5)').html(`<input type="number" step="0.01" class="form-control form-control-sm" value="${base_price}">`);
        row.find('td:eq(6)').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 saveBlock" 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', '.saveBlock', function(){
        var id = $(this).data('id');
        var row = $(this).closest('tr');
        var stadiumId = row.find('select[name=stadium_id]').val() || $('select[name=stadium_id]').val();
        var name = row.find('td:eq(2) input').val();
        var position = row.find('td:eq(3) input').val();
        var capacity = row.find('td:eq(4) input').val();
        var base_price = row.find('td:eq(5) input').val();
        var photo = row.find('td:eq(6) input[type=file]')[0].files[0];

        var formData = new FormData();
        formData.append('_token', '{{ csrf_token() }}');
        formData.append('_method', 'PUT');
        formData.append('stadium_id', stadiumId);
        formData.append('name', name);
        formData.append('position', position);
        formData.append('capacity', capacity);
        formData.append('base_price', base_price);
        if(photo) formData.append('photo', photo);

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

@endsection
