@extends('layout.app')


<title>Add Edit Delete Table Row Example using JQuery - ItSolutionStuff.com</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@9"></script>
<meta name="csrf-token" content="{{ csrf_token() }}">

@section('left-menu')
    @parent
    <ul>
        <a href="sprzet/add"><li>Dodaj<img src="../img/left_menu_icon/add.png"></li></a>
        <li>Edytuj<img src="../img/left_menu_icon/edit.png"></li>
        <li>Usuń<img src="../img/left_menu_icon/delete.png"></li>
    </ul>
@stop


@section('center-area')
    @parent

    @if( auth()->check())
        @if( auth()->user()->fireStationID == NULL)
            Jednostka nie istnieje
        @else
            <center><h1>{{$training->trainingName}}</h1></center>
            <table id="editableTable" class='table table-bordered'>

                <thead>
                    <td>Imię i Nazwisko</td>
                    <td>Ważne od:</td>
                    <td>Ważne do:</td>
                    <td>Akcje</td>
                </thead>

                <tbody>
                @foreach($fireFighters as $fireFighter)
                    <tr id="{{$fireFighter->userID}}">
                        <td>{{$fireFighter->name}} {{$fireFighter->surname}}</td>
                        <td>{{$fireFighter->dateOfComplete}}</td>
                        <td>{{$fireFighter->dateOfExpiry}}</td>
                        <td><button class="btn btn-warning" type="submit" style="display:none" id="{{$fireFighter->userID}}" onclick="cancelButton('{{$fireFighter->userID}}', '{{$fireFighter->dateOfComplete}}', '{{$fireFighter->dateOfExpiry}}')">Anuluj</button> <button class="btn btn-success" type="submit" style="display:none" id="{{$fireFighter->userID}}" onclick="updateButton('{{$fireFighter->userID}}', '{{$fireFighter->dateOfComplete}}', '{{$fireFighter->dateOfExpiry}}')">Zapisz</button> <button class="btn btn-info" type="submit" id="{{$fireFighter->userID}}" onclick="editButton('{{$fireFighter->userID}}')">Edytuj</button> <button class="btn btn-danger btn-delete" type="submit" id="{{$fireFighter->userID}}" onclick="deleteButton('{{$fireFighter->userID}}')">Usuń</button></td>
                    </tr>
                @endforeach
                </tbody>
            </table>


        @endif
    @else
        Brak autoryzacji
    @endif

@stop

<script type="text/javascript">

    function editButton(firefighterID){
        $('.btn-info', '#'+firefighterID).css('display', 'none');
        $('.btn-warning', '#'+firefighterID).css('display', 'inline');
        $('.btn-success', '#'+firefighterID).css('display', 'inline');
        $('.btn-info', '#'+firefighterID).parents("tr").find("td:eq(1)").html('<input type="date" name="dateOfComplete">');
        $('.btn-info', '#'+firefighterID).parents("tr").find("td:eq(2)").html('<input type="date" name="dateOfExpiry">');
    }


    function cancelButton(firefighterID, dateOfComplete, dateOfExpiry){
        $('.btn-info', '#'+firefighterID).css('display', 'inline');
        $('.btn-warning', '#'+firefighterID).css('display', 'none');
        $('.btn-success', '#'+firefighterID).css('display', 'none');

        $('.btn-info', '#'+firefighterID).parents("tr").find("td:eq(1)").html(dateOfComplete);
        $('.btn-info', '#'+firefighterID).parents("tr").find("td:eq(2)").html(dateOfExpiry);
    }

    function updateButton(firefighterID, dateOfComplete, dateOfExpiry){
        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });


        $.ajax({
            type: 'post',
            url: '/szkolenia/addTrainingsFireFighters/',
            data: {
                'firefighterID': firefighterID,
                'trainingID': '{{$training->id}}',
                'dateOfComplete': $('input[name=dateOfComplete]').val(),
                'dateOfExpiry': $('input[name=dateOfExpiry]').val()
            },
            success: function(data) {
                    $('.btn-info', '#'+firefighterID).parents("tr").find("td:eq(1)").html($('input[name=dateOfComplete]').val());
                    $('.btn-info', '#'+firefighterID).parents("tr").find("td:eq(2)").html($('input[name=dateOfExpiry]').val());

                    $('.btn-info', '#'+firefighterID).css('display', 'inline');
                    $('.btn-warning', '#'+firefighterID).css('display', 'none');
                    $('.btn-success', '#'+firefighterID).css('display', 'none');
                    console.log('sukces')
            },
            error: function(jqXhr, json, errorThrown){// this are default for ajax errors
                var errors = jqXhr.responseJSON;
                var errorsHtml = '';
                $.each(errors['errors'], function (index, value) {
                    errorsHtml += '<ul class="list-group"><li class="list-group-item alert alert-danger">' + value + '</li></ul>';
                });
                //I use SweetAlert2 for this
                swal.fire({
                    title: "Error " + jqXhr.status + ': ' + errorThrown,// this will output "Error 422: Unprocessable Entity"
                    html: errorsHtml,
                    width: 'auto',
                    confirmButtonText: 'Spróbuj ponownie',
                    cancelButtonText: 'Anuluj Edycję',
                    showCancelButton: true,
                }).then((result) => {
                    if(result.value){
                        console.log('spróbuj')
                    } else if(result.dismiss === Swal.DismissReason.cancel){
                       console.log('anuluj');
                       cancelButton(firefighterID, dateOfComplete, dateOfExpiry);
                    }
                })
            },

        });


    }


    function deleteButton(firefighterID){
        swal.fire({
            title: "Czy chcesz wyczyścić?",
            width: 'auto',
            confirmButtonText: 'Tak',
            cancelButtonText: 'Nie',
            showCancelButton: true,
        }).then((result) => {
            if(result.value){

                $.ajaxSetup({
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                    }
                });

                $.ajax({
                    type: 'post',
                    url: '/szkolenia/addTrainingsFireFighters/delete/',
                    data: {
                        'firefighterID': firefighterID,
                        'trainingID': '{{$training->id}}',
                    },
                    success: function(data) {
                        $('.btn-info', '#'+firefighterID).parents("tr").find("td:eq(1)").html('');
                        $('.btn-info', '#'+firefighterID).parents("tr").find("td:eq(2)").html('');
                    }
                });
            }
        })

    }
</script>