<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>

                                        <!-- Days -->
                                        <div class="col-md-12 mb-3">
                                            <label class="col-form-label fw-bold mb-2" for="days">
                                                Select Day <span class="text-danger">*</span>
                                            </label>
                                            <div class="d-flex gap-3">
                                                @foreach (['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] as $day)
                                                    <input type="checkbox" class="btn-check day-checkbox" name="day" id="day_{{ $day }}" value="{{ $day }}">
                                                    <label class="btn btn-outline-success day-slot" for="day_{{ $day }}">{{ $day }}</label>
                                                @endforeach
                                            </div>
                                            <span class="text-danger error-text day_err"></span>
                                        </div>

                                        <div class="col-md-12">
                                            <label class="col-form-label fw-bold" for="time">Select Time Slots <span class="text-danger">*</span></label>
                                            <div class="time-slot-grid">
                                                @for ($i = 0; $i < 24; $i++)
                                                    @php
                                                        $value = sprintf('%02d:00', $i);
                                                        $display = \Carbon\Carbon::createFromTime($i, 0)->format('h:i A');
                                                    @endphp
                                                    <input class="btn-check" type="checkbox" name="time[]" id="time_{{ $i }}" value="{{ $value }}">
                                                    <label class=" btn btn-outline-primary time-slot" for="time_{{ $i }}">
                                                        {{ $display }}
                                                    </label>
                                                @endfor
                                            </div>
                                            <span class="text-danger error-text time_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-sm-12">
                        <div class="card">
                            <form class="theme-form" name="editForm" id="editForm" enctype="multipart/form-data">
                                @csrf
                                <input type="hidden" name="edit_model_id" id="edit_model_id" value="">

                                <div class="card-body">
                                    <div class="mb-3 row">

                                        <!-- Service -->
                                        <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>

                                        <!-- Price -->
                                        <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>

                                        <!-- Days -->
                                        <div class="col-md-12 mb-3">
                                            <label class="col-form-label fw-bold mb-2" for="days">
                                                Select Day <span class="text-danger">*</span>
                                            </label>
                                            <div id="editDaysContainer" class="d-flex gap-3 flex-wrap"></div>
                                            <span class="text-danger error-text day_err"></span>
                                            {{-- <div class="d-flex gap-3 flex-wrap">
                                                @foreach (['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] as $day)
                                                    <input type="checkbox" class="btn-check day-checkbox"
                                                        name="day" id="edit_day_{{ $day }}"
                                                        value="{{ $day }}">
                                                    <label class="btn btn-outline-success day-slot"
                                                        for="edit_day_{{ $day }}">{{ $day }}</label>
                                                @endforeach
                                            </div>
                                            <span class="text-danger error-text day_err"></span> --}}
                                        </div>

                                        <!-- Time Slots -->
                                        <div class="col-md-12">
                                            <label class="col-form-label fw-bold" for="time">
                                                Select Time Slots <span class="text-danger">*</span>
                                            </label>
                                            <div class="time-slot-grid">
                                                @for ($i = 0; $i < 24; $i++)
                                                    @php
                                                        $value = sprintf('%02d:00', $i);
                                                        $display = \Carbon\Carbon::createFromTime($i, 0)->format('h:i A');
                                                    @endphp
                                                    <input class="btn-check time-checkbox" type="checkbox"
                                                        name="time[]" id="edit_time_{{ $i }}"
                                                        value="{{ $value }}">
                                                    <label class="btn btn-outline-primary time-slot"
                                                        for="edit_time_{{ $i }}">{{ $display }}</label>
                                                @endfor
                                            </div>
                                            <span class="text-danger error-text time_err"></span>
                                        </div>

                                    </div>
                                </div>

                                <div class="card-footer">
                                    <button type="submit" class="btn btn-primary" id="editSubmit">Update</button>
                                    <button type="button" class="btn btn-warning" id="btnCancel">Cancel</button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>


                <div class="row">
                    <div class="col-sm-12">
                        <h3>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>Service Name</th>
                                            <th>Price</th>
                                            <th>Day</th>
                                            <th>Time</th>
                                            <th>Action</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        @php $sr = 1; @endphp
                                        @foreach ($datas as $service => $days)
                                            @foreach ($days as $day => $slots)
                                                <tr>
                                                    <td>{{ $sr++ }}</td>
                                                    <td> <strong> {{ $slots->first()->bookingFor->service }} </strong>
                                                    </td>
                                                    <td> {{ $slots->first()->price }} </td>
                                                    <td> {{ $slots->first()->day }} </td>
                                                    <td>
                                                        @foreach ($slots as $slot)
                                                            <span class="badge bg-primary">
                                                                {{ \Carbon\Carbon::parse($slot->time)->format('h:i A') }}
                                                            </span>
                                                        @endforeach
                                                    </td>
                                                    <td>
                                                        <button class="edit-element btn btn-primary px-2 py-1" title="Edit slot" data-id="{{ $slot->id }}"><i data-feather="edit"></i></button>
                                                        <button class="btn btn-dark rem-element px-2 py-1" title="Delete slot" data-id="{{ $slot->id }}"><i data-feather="trash-2"></i> </button>
                                                    </td>
                                                </tr>
                                            @endforeach
                                        @endforeach
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>

                </div>

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


    @push('scripts')
    @endpush


</x-admin.admin-layout>

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

        var formdata = new FormData(this);
        $.ajax({
            url: '{{ route('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('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('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>
    $(document).on("click", ".edit-element", function(e) {
        e.preventDefault();

        const model_id = $(this).data("id");
        const url = "{{ route('booking_slots.edit', ':id') }}".replace(':id', model_id);

        $.ajax({
            url: url,
            type: "GET",
            dataType: "json",
            success: function(response) {
                if (response && response.slots && response.slots.length > 0) {
                    $("#addContainer").slideUp();
                    $("#editContainer").slideDown();
                    $("#btnCancel").show();

                    const slots = response.slots;

                    // Prefill Service, Price
                    $("#editForm input[name='edit_model_id']").val(slots[0].id);
                    $("#editForm select[name='booking_for_id']").val(response.service_id).trigger(
                        "change");
                    $("#editForm input[name='price']").val(response.price);

                    // Reset and check the correct day
                    $("#editDaysContainer").empty();

                    // Get single day from response
                    const dayValue = response.day?.trim();

                    if (dayValue) {
                        const inputId = `edit_day_${dayValue}`;
                        const dayCheckboxHtml = `
                                <input type="checkbox" class="btn-check day-checkbox" id="${inputId}" name="day" value="${dayValue}" checked>
                                <label class="btn btn-outline-success day-slot active" for="${inputId}">${dayValue}</label>
                            `;
                        $("#editDaysContainer").append(dayCheckboxHtml);
                    }

                    // Reset all times first
                    $(".time-checkbox").prop("checked", false).siblings("label").removeClass(
                        "active");

                    // Check only fetched times
                    slots.forEach(slot => {
                        const time = slot.time?.trim();
                        if (time) {
                            $(`.time-checkbox[value='${time}']`).prop("checked", true);
                            $(`label[for='edit_time_${parseInt(time)}']`).addClass(
                                "active");
                        }
                    });
                } else {
                    Swal.fire("No Data", "No booking slots found for this service/day.", "info");
                }
            },
            error: function() {
                Swal.fire("Error", "Something went wrong while fetching data.", "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('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("Booking", data.bookingSlot);
                    const slot = data.bookingSlot[0];
                    // $("#editForm input[name='edit_model_id']").val(data.slot.id);
                    $("#editForm select[name='booking_for_id']").val(data.slot.booking_for_id).trigger('change');
                    $(".day-checkbox").prop("checked", false);
                    if (slot.day) {
                        slot.day.split(',').forEach(day => {
                            $("#day_" + day.trim()).prop("checked", true);
                        });
                    }
                    // $("#editForm input[name='day']").val(data.bookingSlot[0].day);
                    $("#editForm select[name='time']").val(data.bookingSlot.time).trigger('change');
                    $("#editForm input[name='price']").val(data.bookingSlot[0].price);
                } 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();
            console.log(model_id);
            var url = "{{ route('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('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>


<script>
    document.querySelectorAll('.day-checkbox').forEach((checkbox) => {
        checkbox.addEventListener('change', function() {
            if (this.checked) {
                document.querySelectorAll('.day-checkbox').forEach(cb => {
                    if (cb !== this) cb.checked = false;
                });
            }
        });
    });
</script>

<script>
    $(document).on("change", ".day-checkbox, .time-checkbox", function() {
        const id = $(this).attr("id");
        const $label = $(`label[for='${id}']`);
        if ($(this).is(":checked")) {
            $label.addClass("active");
        } else {
            $label.removeClass("active");
        }
    });
</script>
