@extends('Admin.layouts.master')

@section('content')
    @php
        $currentPage = 'restraunt';
    @endphp
    <style>
        .error-message {
            color: #FF0000;
        }

        form .error-message {
            color: red;
            /* Set your desired color here */
        }

        form .input_class.error-message {
            color: #0e1726;
        }
    </style>
    <div class="layout-px-spacing">
        <div class="middle-content container-xxl p-0">
            <div class="row layout-top-spacing ">
                <div class="top-tabel">
                    <div class="row">
                        <div class="col-md-4">
                            <a class="d-flex align-items-center justify-content-center pl-2"
                                href="{{ route('manage.restaurants') }}">
                                <img class="back-btn" src="{{ asset('public/assets/img/left-arrow.svg') }}">
                                <h6 class="card-title p-0">Edit Details</h6>
                            </a>
                        </div>
                        <div class="col-md-8">

                        </div>
                    </div>
                </div>
                <form method="POST" id="update_voucher" class="form py-5 pb-0" action="javascript:void(0)"
                    enctype="multipart/form-data">
                    {{ csrf_field() }}
                    <input type="hidden" name="id" id="id" value="{{ $restaurantItem->id }}" />
                    <div class="col-xl-12 col-lg-12 col-sm-12  layout-spacing">
                        <div class="widget-content widget-content-area br-8 position-btn h-10">
                            <div class="view-details Article">
                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="form-group ">
                                            <label for="company-name" class="label">Restaurant Name</label>
                                            <input type="text" class="form-control" id="name" name="name"
                                                maxlength="40" value="{{ $restaurantItem->name }}">
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="form-group ">
                                            <label for="company-name" class="label">Restaurant ID</label>
                                            <input type="text" class="form-control" id="restaurant_id"
                                                name="restaurant_id" maxlength="30"
                                                value="{{ $restaurantItem->restaurant_id }}">
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="form-group ">
                                            <label for="company-name" class="label">Image</label>
                                            <input type="file" accept="image/*" class="form-control" name="image"
                                                id="imageInputNormal">
                                            <div id="imageInputPreviewNormal" style="width: 30%;">
                                                <img src="{{ $restaurantItem->image }}" alt="Image Preview"
                                                    style="width: 40%;">
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="form-group ">
                                            <label for="company-name" class="label">Restaurant Address</label>
                                            <input type="text" class="form-control" id="location_name"
                                                name="location_name" value="{{ $restaurantItem->address }}">
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="form-group ">
                                            <label for="company-name" class="label">Phone Number</label>
                                            <input type="text" class="form-control" id="phone_number" name="phone_number"
                                                value="{{ $restaurantItem->phone_number }}" maxlength="15">
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="form-group ">
                                            <label for="company-name" class="label">Exclusion</label>
                                            <textarea type="text" class="form-control" id="exclusion" name="exclusion">{!! $restaurantItem->exclusion !!}</textarea>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <label for="location" class="label">Select state</label>
                                        <select class="form-select" aria-label="Default select example" id="single"
                                            name="state_xid">
                                            <option value="">Select State</option>
                                            @foreach ($state as $states)
                                                <option value="{{ $states['id'] }}"
                                                    @if ($states['id'] == $restaurantItem->state_xid) selected @endif>
                                                    {{ $states['name'] }}
                                                </option>
                                            @endforeach
                                        </select>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="form-group ">
                                            <label for="company-name" class="label">Latitude</label>
                                            <input type="text" class="form-control" id="latitude" name="latitude"
                                                maxlength="30" value="{{ $restaurantItem->latitude }}">
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="form-group ">
                                            <label for="company-name" class="label">Longitude</label>
                                            <input type="text" class="form-control" id="longitude" name="longitude"
                                                maxlength="30" value="{{ $restaurantItem->longtitude }}">
                                        </div>
                                    </div>
                                    @php
                                        $timeInterval = $restaurantItem->timeInterval->first();
                                        $timeHours = $timeInterval->time_hours ?? '';
                                        $timeIntervalValue = $timeInterval->time_interval ?? '';
                                        $timeQuantity = $timeInterval->quantity ?? '';
                                    @endphp


                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="timeHours" class="label">Time in hours between redeeming two
                                                drinks</label>
                                            <input type="number" class="form-control" id="timeHours" name="timeHours"
                                                value="{{ $timeHours }}">
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="timeQuantity" class="label">Maximum number of drinks</label>
                                            <div class="input-group">
                                                <select class="form-control" id="timeInterval" name="timeInterval"
                                                    required>
                                                    {{-- <option value="day"
                                                        {{ $timeIntervalValue == 'day' ? 'selected' : '' }}>Day</option>
                                                    <option value="week"
                                                        {{ $timeIntervalValue == 'week' ? 'selected' : '' }}>Week</option> --}}
                                                    <option value="month"
                                                        {{ $timeIntervalValue == 'month' ? 'selected' : '' }}>Month
                                                    </option>
                                                </select>
                                                <input type="number" class="form-control" id="timeQuantity"
                                                    name="timeQuantity" value="{{ $timeQuantity }}">
                                            </div>
                                        </div>
                                    </div>


                                    <div class="col-md-6">
                                        <div class="form-group ">
                                            <label for="company-name" class="label">Bio</label>
                                            <input type="text" class="form-control" name="bio"
                                                value="{{ $restaurantItem->bio }}">
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="form-group ">
                                            <label for="company-name" class="label">While at Restaurant be sure to
                                                try
                                                :</label>
                                            <input type="text" class="form-control mb-3" name="try_on_1"
                                                value="{{ $restaurantItem->try_on_1 }}">
                                            <input type="text" class="form-control mb-3" name="try_on_2"
                                                value="{{ $restaurantItem->try_on_2 }}">
                                            <input type="text" class="form-control mb-3" name="try_on_3"
                                                value="{{ $restaurantItem->try_on_3 }}">
                                            <input type="text" class="form-control mb-3" name="try_on_4"
                                                value="{{ $restaurantItem->try_on_4 }}">
                                        </div>
                                    </div>
                                    {{-- <div class="col-md-12">
                                        <div class="form-group">
                                            <label class="label">Operating Hours</label>
                                            @foreach (['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] as $day)
                                                <div class="row">
                                                    <div class="col-md-3">
                                                        <label>{{ $day }} Start Time:</label>
                                                        <input type="time" class="form-control"
                                                            name="operating_hours[{{ $day }}][start_time]"
                                                            value="{{ isset($operating_hours[$day]) ? $operating_hours[$day]->start_time : '' }}">
                                                    </div>
                                                    <div class="col-md-3">
                                                        <label>{{ $day }} End Time:</label>
                                                        <input type="time" class="form-control"
                                                            name="operating_hours[{{ $day }}][end_time]"
                                                            value="{{ isset($operating_hours[$day]) ? $operating_hours[$day]->end_time : '' }}">
                                                    </div>
                                                </div>
                                            @endforeach

                                        </div>
                                    </div> --}}

                                    <div class="col-md-12">
                                        <label for="timeHours" class="label">Closed Hours : </label><br>

                                        <div id="closed-hours-container">
                                            @foreach ($restaurantClosedTime as $closedHour)
                                                <div class="closed-hour-entry">
                                                    <label for="day_of_week[]">Closed Day:</label>
                                                    <select name="day_of_week[]">
                                                        <option value="0"
                                                            {{ $closedHour->day_of_week == 0 ? 'selected' : '' }}>Sunday
                                                        </option>
                                                        <option value="1"
                                                            {{ $closedHour->day_of_week == 1 ? 'selected' : '' }}>Monday
                                                        </option>
                                                        <option value="2"
                                                            {{ $closedHour->day_of_week == 2 ? 'selected' : '' }}>Tuesday
                                                        </option>
                                                        <option value="3"
                                                            {{ $closedHour->day_of_week == 3 ? 'selected' : '' }}>Wednesday
                                                        </option>
                                                        <option value="4"
                                                            {{ $closedHour->day_of_week == 4 ? 'selected' : '' }}>Thursday
                                                        </option>
                                                        <option value="5"
                                                            {{ $closedHour->day_of_week == 5 ? 'selected' : '' }}>Friday
                                                        </option>
                                                        <option value="6"
                                                            {{ $closedHour->day_of_week == 6 ? 'selected' : '' }}>Saturday
                                                        </option>
                                                    </select>

                                                    <label for="start_time[]">Start Time:</label>
                                                    <input type="time" name="start_time[]"
                                                        value="{{ $closedHour->start_time }}">

                                                    <label for="end_time[]">End Time:</label>
                                                    <input type="time" name="end_time[]"
                                                        value="{{ $closedHour->end_time }}">

                                                    <button type="button" class="remove-btn"
                                                        onclick="removeClosedHourEntry(this)">Remove</button>
                                                </div>
                                            @endforeach
                                        </div>
                                        <button type="button" class="extra-btn" style="float:left;" onclick="addClosedHourEntry()">Add Time
                                            Slot</button>
                                    </div>

                                    <div class="col-md-12">
                                        <button class="download-btn "style="width: 30%;" id="update_restaurant">
                                            <span>Submit</span>
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </form>

            </div>
        </div>
    </div>

    <script>
        const imageInput = document.getElementById('imageInputThumb');
        const imagePreview = document.getElementById('imagePreviewThumb');

        imageInput.addEventListener('change', function() {
            console.log("in change kjbck");
            const file = this.files[0];
            if (file) {
                const reader = new FileReader();
                reader.onload = function(event) {
                    const img = document.createElement('img');
                    img.src = event.target.result;
                    img.style.maxWidth = '200px';
                    img.style.maxHeight = '200px';
                    imagePreview.innerHTML = '';
                    imagePreview.appendChild(img);
                };
                reader.readAsDataURL(file);
            } else {
                imagePreview.innerHTML = '';
            }
        });


        const imageInputEdit = document.getElementById('imageInputNormal');
        const imagePreviewEdit = document.getElementById('imageInputPreviewNormal');

        imageInputEdit.addEventListener('change', function() {
            const file = this.files[0];
            if (file) {
                const reader = new FileReader();
                reader.onload = function(event) {
                    const img = document.createElement('img');
                    img.src = event.target.result;
                    img.style.maxWidth = '200px';
                    img.style.maxHeight = '200px';
                    imagePreviewEdit.innerHTML = '';
                    imagePreviewEdit.appendChild(img);
                };
                reader.readAsDataURL(file);
            } else {
                imagePreviewEdit.innerHTML = '';
            }
        });
    </script>
@endsection
@section('section_script')
    <script>
        $(document).ready(function() {
            $('#update_voucher').validate({
                ignore: [],
                debug: false,
                rules: {
                    name: {
                        required: true
                    },
                    state_xid: {
                        required: true,
                    },
                    rest_id: {
                        required: true,
                    },
                    address: {
                        required: true,
                    },
                    phone_number: {
                        required: true,
                    },
                    latitude: {
                        required: true,
                        number: true,
                        normalizer: function(value) {
                            return $.trim(value);
                        }
                    },
                    longitude: {
                        required: true,
                        number: true,
                        normalizer: function(value) {
                            return $.trim(value);
                        }
                    },
                    timeHours: {
                        required: true,
                        number: true,
                        min: 1
                    },
                    timeQuantity: {
                        required: true,
                        number: true,
                        min: 1
                    },
                    maxCocktails: {
                        required: true,
                        number: true,
                        min: 1
                    },
                    bio: {
                        required: true,
                    },
                    try_on_1: {
                        required: true,
                        maxlength: 18,

                    },
                    try_on_2: {
                        required: true,
                        maxlength: 18,

                    },
                    try_on_3: {
                        required: true,
                        maxlength: 18,

                    },
                    try_on_4: {
                        required: true,
                        maxlength: 18,

                    },
                    'start_time[]': {
                        required: function(element) {
                            return $(element).closest('.closed-hour-entry').find(
                                'select[name="day_of_week[]"]').val() !== '';
                        }
                    },
                    'end_time[]': {
                        required: function(element) {
                            return $(element).closest('.closed-hour-entry').find(
                                'select[name="day_of_week[]"]').val() !== '';
                        }
                    }
                },
                messages: {
                    name: {
                        required: "Enter restaurant Name",
                    },
                    state_xid: {
                        required: "Please select state",
                    },
                    rest_id: {
                        required: "Enter restaurant Id",
                    },
                    address: {
                        required: "Please enter location",
                    },
                    phone_number: {
                        required: "Please enter phone number",
                    },
                    latitude: {
                        required: "Please enter latitude",
                        number: "Latitude must be a number without spaces",
                    },
                    longitude: {
                        required: "Please enter longitude",
                        number: "Longitude must be a number without spaces",
                    },
                    timeHours: {
                        required: "Please enter the time in hours between redeeming two cocktails",
                        number: "Time must be a number",
                        min: "Time must be greater than 0"
                    },
                    timeQuantity: {
                        required: "Please enter the time quantity",
                        number: "Time quantity must be a number",
                        min: "Time quantity must be greater than 0"
                    },
                    maxCocktails: {
                        required: "Please enter the maximum number of cocktails",
                        number: "Maximum number of cocktails must be a number",
                        min: "Maximum number of cocktails must be greater than 0"
                    },
                    bio: {
                        required: "Enter Bio",
                    },
                    try_on_1: {
                        required: "Please enter this field",
                        maxlength: "Maximum length is 18 characters"

                    },
                    try_on_2: {
                        required: "Please enter this field",
                        maxlength: "Maximum length is 18 characters"

                    },
                    try_on_3: {
                        required: "Please enter this field",
                        maxlength: "Maximum length is 18 characters"

                    },
                    try_on_4: {
                        required: "Please enter this field",
                        maxlength: "Maximum length is 18 characters"

                    },
                    'start_time[]': {
                        required: "Please select a start time",
                    },
                    'end_time[]': {
                        required: "Please select an end time",
                    }
                },
                errorClass: 'error-message',
                submitHandler: function(form) {
                    var formData = new FormData(form);

                    $('#update_restaurant').text('Please wait...');
                    $('#update_restaurant').attr('disabled', true);

                    $.ajaxSetup({
                        headers: {
                            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                        }
                    });
                    $.ajax({
                        url: "{{ route('update_restaurant') }}",
                        type: 'POST',
                        data: formData,
                        processData: false,
                        contentType: false,
                        success: function(result) {
                            if (result.status_code == 200) {
                                toastr.success('Restaurant Updated Successfully');
                                setTimeout(function() {
                                    window.location.href =
                                        "{{ route('manage.restaurants') }}";
                                }, 2000);
                            } else {
                                toastr.error('Something Went Wrong');
                                setTimeout(function() {
                                    window.location.href =
                                        "{{ route('manage.restaurants') }}";
                                }, 2000);
                            }
                            $('#update_restaurant').attr('disabled', false);
                            $('#update_restaurant').text('Submit');
                        },
                    });

                    $('#store_coupon').attr('disabled', false);
                    $('#store_coupon').text('Submit');
                }
            });
        });
    </script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const closedDateInput = document.getElementById('closed_date');

            closedDateInput.addEventListener('input', function() {
                const today = new Date().toISOString().split('T')[0];
                if (this.value < today) {
                    alert('Please select a future date.');
                    this.value = '';
                }
            });
        });
    </script>
    <script>
        function addClosedHourEntry() {
            const container = document.getElementById('closed-hours-container');
            const entryTemplate = `
            <div class="closed-hour-entry">
                <label for="day_of_week[]">Closed Day:</label>
                <select name="day_of_week[]">
                    <option value="0">Sunday</option>
                    <option value="1">Monday</option>
                    <option value="2">Tuesday</option>
                    <option value="3">Wednesday</option>
                    <option value="4">Thursday</option>
                    <option value="5">Friday</option>
                    <option value="6">Saturday</option>
                </select>

                <label for="start_time[]">Start Time:</label>
                <input type="time" name="start_time[]">

                <label for="end_time[]">End Time:</label>
                <input type="time" name="end_time[]">

                <button type="button" class="remove-btn" onclick="removeClosedHourEntry(this)">Remove</button>
            </div>
        `;
            container.insertAdjacentHTML('beforeend', entryTemplate);
        }

        function removeClosedHourEntry(button) {
            const entry = button.parentNode;
            entry.parentNode.removeChild(entry);
        }
    </script>
@endsection
