<x-admin.admin-layout>
    <x-slot name="title">{{ auth()->user()->tenant_name }} - Booking Slot</x-slot>

    <style>
        .time-slot-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(90px, 1fr));
            gap: 0.5rem;
        }

        .time-slot {
            display: block;
            width: 100%;
            text-align: center;
            border-radius: 8px;
            padding: 6px 0;
            font-size: 14px;
            transition: all 0.2s ease;
        }

        .time-slot:hover {
            background-color: #e3f2fd;
            border-color: #112a80;
            color: #e7e7e7;
        }

        .btn-check:checked+.time-slot {
            background-color: #4a0ab1;
            color: white;
            border-color: #2a0664;
        }
    </style>


    <div class="page-body">
        <div class="container-fluid">
            <div class="page-header">

                <!-- Add Form -->
                <div class="row" id="addContainer" style="display:none;">
                    <div class="col-sm-12">
                        <div class="card">
                            <form class="theme-form" name="addForm" id="addForm" enctype="multipart/form-data">
                                @csrf

                                <div class="card-body">

                                    <div class="mb-3 row">

                                        <div class="col-md-4">
                                            <label class="col-form-label" for="booking_for_id">Service Type <span
                                                    class="text-danger">*</span></label>
                                            <select class="form-select" name="booking_for_id">
                                                <option value="">-- Select Service --</option>
                                                @foreach ($services as $serv)
                                                    <option value="{{ $serv->id }}"> {{ $serv->service }} </option>
                                                @endforeach
                                            </select>
                                            <span class="text-danger error-text booking_for_id_err"></span>
                                        </div>

                                        <div class="col-md-4">
                                            <label class="col-form-label" for="price">Price <span
                                                    class="text-danger">*</span></label>
                                            <input type="number" class="form-control" name="price"
                                                placeholder="Enter Price">
                                            <span class="text-danger error-text price_err"></span>
                                        </div>

                                        <div class="col-md-4">
                                            <label class="col-form-label" for="time">Time <span
                                                    class="text-danger">*</span></label>
                                            <select class="form-control" name="time" id="time" required>
                                                <option value="">-- Select Time --</option>
                                                @for ($i = 0; $i < 24; $i++)
                                                    @php
                                                        $displayHour = $i == 0 ? 12 : ($i > 12 ? $i - 12 : $i);
                                                        $ampm = $i < 12 ? 'AM' : 'PM';
                                                    @endphp
                                                    <option value="{{ sprintf('%02d:00', $i) }}">
                                                        {{ $displayHour }}:00 {{ $ampm }}
                                                    </option>
                                                @endfor
                                            </select>
                                            <span class="text-danger error-text time_err"></span>
                                        </div>

                                        <div class="col-md-4">
                                            <label class="col-form-label" for="date">Date <span
                                                    class="text-danger">*</span></label>
                                            <input type="date" class="form-control" name="date"
                                                min="{{ date('Y-m-d') }}" required>
                                            <span class="text-danger error-text date_err"></span>
                                        </div>

                                    </div>

                                </div>
                                <div class="card-footer">
                                    <button type="submit" class="btn btn-primary" id="addSubmit">Submit</button>
                                    <button type="reset" class="btn btn-warning">Reset</button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>



                {{-- Edit Form --}}
                <div class="row" id="editContainer" style="display:none;">
                    <div class="col">
                        <form class="form-horizontal form-bordered" method="post" id="editForm">
                            @csrf
                            <section class="card">
                                <header class="card-header">
                                    <h4 class="card-title">Edit categorie</h4>
                                </header>

                                <div class="card-body py-2">
                                    <input type="hidden" id="edit_model_id" name="edit_model_id" value="">
                                    <div class="mb-3 row">

                                        <div class="col-md-4">
                                            <label class="col-form-label" for="booking_for_id">Service Type <span
                                                    class="text-danger">*</span></label>
                                            <select class="form-select" name="booking_for_id">
                                                <option value="">-- Select Service --</option>
                                                @foreach ($services as $serv)
                                                    <option value="{{ $serv->id }}"> {{ $serv->service }} </option>
                                                @endforeach
                                            </select>
                                            <span class="text-danger error-text booking_for_id_err"></span>
                                        </div>

                                        <div class="col-md-4">
                                            <label class="col-form-label" for="price">Price <span
                                                    class="text-danger">*</span></label>
                                            <input type="number" class="form-control" name="price"
                                                placeholder="Enter Price">
                                            <span class="text-danger error-text price_err"></span>
                                        </div>

                                        <div class="col-md-4">
                                            <label class="col-form-label" for="time">Time <span
                                                    class="text-danger">*</span></label>
                                            <select class="form-control" name="time" required>
                                                <option value="">-- Select Time --</option>
                                                @for ($i = 0; $i < 24; $i++)
                                                    @php
                                                        $displayHour = $i == 0 ? 12 : ($i > 12 ? $i - 12 : $i);
                                                        $ampm = $i < 12 ? 'AM' : 'PM';
                                                    @endphp
                                                    <option value="{{ sprintf('%02d:00', $i) }}">
                                                        {{ $displayHour }}:00 {{ $ampm }}
                                                    </option>
                                                @endfor
                                            </select>
                                            <span class="text-danger error-text time_err"></span>
                                        </div>

                                        <div class="col-md-4">
                                            <label class="col-form-label" for="date">Date <span
                                                    class="text-danger">*</span></label>
                                            <input type="date" class="form-control" name="date"
                                                min="{{ date('Y-m-d') }}" required>
                                            <span class="text-danger error-text date_err"></span>
                                        </div>

                                    </div>

                                </div>
                                <div class="card-footer">
                                    <button class="btn btn-primary" id="editSubmit">Submit</button>
                                    <button type="reset" class="btn btn-warning">Reset</button>
                                </div>
                            </section>
                        </form>
                    </div>
                </div>


                <div class="row">
                    <div class="col-sm-12">
                        <h3> Special Booking Slot</h3>
                    </div>

                    <div class="col-sm-6">
                    </div>
                </div>
            </div>
        </div>
        <!-- Container-fluid starts-->
        <div class="container-fluid support-ticket">
            <div class="row">

                <div class="col-sm-12">

                    <div class="card">
                        <div class="card-body">
                            <div class="row">
                                <div class="col-sm-6">
                                    <div class="">
                                        <button id="addToTable" class="btn btn-primary">Add <i
                                                class="fa fa-plus"></i></button>
                                        <button id="btnCancel" class="btn btn-danger"
                                            style="display:none;">Cancel</button>
                                    </div>
                                </div>
                            </div>
                            <div class="table-responsive">
                                <table class="table-bordered" id="datatable-tabletools">
                                    <thead>
                                        <tr>
                                            <th>Sr No</th>
                                            <th>Date</th>
                                            <th>Time</th>
                                            <th>Price</th>
                                            <th>Action</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        @foreach ($specialBooking as $special)
                                            <tr>
                                                <td> {{ $loop->iteration }} </td>
                                                <td> {{ Carbon\Carbon::parse($special->date)->format('Y-m-d') }} </td>
                                                <td> {{ Carbon\Carbon::parse($special->time)->format('H:i A') }} </td>
                                                <td> {{ $special->price }} </td>
                                                <td>
                                                    <button class="edit-element btn btn-primary px-2 py-1"
                                                        title="Edit Booking" data-id="{{ $special->id }}"><i
                                                            data-feather="edit"></i></button>
                                                    <button class="btn btn-dark rem-element px-2 py-1"
                                                        title="Delete Booking" data-id="{{ $special->id }}"><i
                                                            data-feather="trash-2"></i> </button>
                                                </td>
                                            </tr>
                                        @endforeach
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>

                </div>

            </div>
        </div>
        <!-- Container-fluid Ends -->
    </div>


</x-admin.admin-layout>

{{-- Add --}}
<script>
    $("#addForm").submit(function(e) {
        e.preventDefault();
        $("#addSubmit").prop('disabled', true);

        var formdata = new FormData(this);
        $.ajax({
            url: '{{ route('special_booking_slots.store') }}',
            type: 'POST',
            data: formdata,
            contentType: false,
            processData: false,
            success: function(data) {
                $("#addSubmit").prop('disabled', false);
                if (!data.error2)
                    swal("Successful!", data.success, "success")
                    .then((action) => {
                        window.location.href = '{{ route('special_booking_slots.index') }}';
                    });
                else
                    swal("Error!", data.error2, "error");
            },
            statusCode: {
                422: function(responseObject, textStatus, jqXHR) {
                    $("#addSubmit").prop('disabled', false);
                    resetErrors();
                    printErrMsg(responseObject.responseJSON.errors);
                },
                500: function(responseObject, textStatus, errorThrown) {
                    $("#addSubmit").prop('disabled', false);
                    swal("Error occured!", "Something went wrong please try again", "error");
                }
            }
        });

        function resetErrors() {
            var form = document.getElementById('addForm');
            var data = new FormData(form);
            for (var [key, value] of data) {
                $('.' + key + '_err').text('');
                $('#' + key).removeClass('is-invalid');
                $('#' + key).addClass('is-valid');
            }
        }

        function printErrMsg(msg) {
            $.each(msg, function(key, value) {
                $('.' + key + '_err').text(value);
                $('#' + key).addClass('is-invalid');
                $('#' + key).removeClass('is-valid');
            });
        }

    });
</script>


<!-- Delete -->
<script>
    $("#datatable-tabletools").on("click", ".rem-element", function(e) {
        e.preventDefault();
        swal({
                title: "Are you sure to delete this booking slot?",
                // text: "Make sure if you have filled Vendor details before proceeding further",
                icon: "info",
                buttons: ["Cancel", "Confirm"]
            })
            .then((justTransfer) => {
                if (justTransfer) {
                    var model_id = $(this).attr("data-id");
                    var url = "{{ route('special_booking_slots.destroy', ':model_id') }}";

                    $.ajax({
                        url: url.replace(':model_id', model_id),
                        type: 'POST',
                        data: {
                            '_method': "DELETE",
                            '_token': "{{ csrf_token() }}"
                        },
                        success: function(data, textStatus, jqXHR) {
                            if (!data.error && !data.error2) {
                                swal("Success!", data.success, "success")
                                    .then((action) => {
                                        window.location.reload();
                                    });
                            } else {
                                if (data.error) {
                                    swal("Error!", data.error, "error");
                                } else {
                                    swal("Error!", data.error2, "error");
                                }
                            }
                        },
                        error: function(error, jqXHR, textStatus, errorThrown) {
                            swal("Error!", "Something went wrong", "error");
                        },
                    });
                }
            });
    });
</script>


<!-- Edit -->
<script>
    $("#datatable-tabletools").on("click", ".edit-element", function(e) {
        e.preventDefault();
        $(".edit-element").show();
        var model_id = $(this).attr("data-id");
        var url = "{{ route('special_booking_slots.edit', ':model_id') }}";

        $.ajax({
            url: url.replace(':model_id', model_id),
            type: 'GET',
            data: {
                '_token': "{{ csrf_token() }}"
            },
            success: function(data, textStatus, jqXHR) {
                $("#addContainer").slideUp();
                $("#btnCancel").show();
                $("#addToTable").hide();
                $("#editContainer").slideDown();

                if (!data.error) {
                    console.log("Date", data.specialSlot.date);
                    const dateValue = data.specialSlot.date.substring(0, 10);

                    console.log("1:", dateValue);
                    // const dateValue = new Date(data.specialSlot.date).toISOString().split('T')[0];
                    // console.log("2", dateValue);
                    $("#editForm input[name='edit_model_id']").val(data.specialSlot.id);
                    $("#editForm select[name='booking_for_id']").val(data.specialSlot
                        .booking_for_id).trigger('change');
                    $("#editForm select[name='time']").val(data.specialSlot.time).trigger('change');
                    $("#editForm input[name='price']").val(data.specialSlot.price);
                    $("#editForm input[name='date']").val(dateValue);
                } else {
                    alert(data.error);
                }
            },
            error: function(error, jqXHR, textStatus, errorThrown) {
                alert("Some thing went wrong");
            },
        });
    });
</script>


<!-- Update -->
<script>
    $(document).ready(function() {
        $("#editForm").submit(function(e) {
            e.preventDefault();
            $("#editSubmit").prop('disabled', true);
            var formdata = new FormData(this);
            formdata.append('_method', 'PUT');
            var model_id = $('#edit_model_id').val();
            var url = "{{ route('special_booking_slots.update', ':model_id') }}";
            $.ajax({
                url: url.replace(':model_id', model_id),
                type: 'POST',
                data: formdata,
                contentType: false,
                processData: false,
                success: function(data) {
                    $("#editSubmit").prop('disabled', false);
                    if (!data.error2)
                        swal("Successful!", data.success, "success")
                        .then((action) => {
                            window.location.href =
                                '{{ route('special_booking_slots.index') }}';
                        });
                    else
                        swal("Error!", data.error2, "error");
                },
                statusCode: {
                    422: function(responseObject, textStatus, jqXHR) {
                        $("#editSubmit").prop('disabled', false);
                        resetErrors();
                        printErrMsg(responseObject.responseJSON.errors);
                    },
                    500: function(responseObject, textStatus, errorThrown) {
                        $("#editSubmit").prop('disabled', false);
                        swal("Error occured!", "Something went wrong please try again",
                            "error");
                    }
                }
            });

            function resetErrors() {
                var form = document.getElementById('editForm');
                var data = new FormData(form);
                for (var [key, value] of data) {
                    var field = key.replace('[]', '');
                    $('.' + field + '_err').text('');
                    $('#' + field).removeClass('is-invalid');
                    $('#' + field).addClass('is-valid');
                }
            }

            function printErrMsg(msg) {
                $.each(msg, function(key, value) {
                    var field = key.replace('[]', '');
                    $('.' + field + '_err').text(value);
                    $('#' + field).addClass('is-invalid');
                });
            }

        });
    });
</script>
