@extends('layouts.app')

@section('content')

<div id="main-wrapper" class="min-h-screen bg-gradient-to-br from-blue-50 to-white py-12 px-4">
    <div class="container mx-auto">
        <div class="text-center mb-8">
            <h2 class="text-4xl font-extrabold leading-tight text-slate-800">{{trans('lang.sign_up_with_us')}}</h2>
        </div>

        <div id="data-table_processing" class="fixed inset-0 bg-black bg-opacity-80 z-50 flex items-center justify-center" style="display: none;">
            <div class="text-white text-lg flex flex-col items-center gap-2">
                <i class="fa-solid fa-spinner fa-spin text-4xl"></i>
                <span class="text-base">{{ trans('lang.processing') }}</span>
            </div>
        </div>

        <div class="error_top bg-red-100 border-l-4 border-red-500 text-red-700 p-4 rounded-lg mb-6" style="display:none;" role="alert"></div>
        <div class="alert alert-success bg-green-100 border-l-4 border-green-500 text-green-700 p-4 rounded-lg mb-6" style="display:none;" role="alert"></div>

        <div class="grid grid-cols-1 lg:grid-cols-2 gap-8">
            <!-- Owner Information Card -->
            <div class="rounded-lg border !border-slate-300 shadow-[1px_1px_4px_0px_#e2e8f0] overflow-hidden flex flex-col">
                <div class="bg-slate-900 px-6 py-4">
                    <h3 class="text-xl font-bold text-white m-0">{{trans('lang.admin_area')}}</h3>
                </div>
                <div class="p-6 bg-white flex-grow flex flex-col gap-5">
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-5">
                        <div>
                            <label class="text-sm text-slate-700 font-medium">{{trans('lang.first_name')}}</label>
                            <input type="text" class="user_first_name border !border-slate-300 rounded-lg py-2 px-3 w-full transition duration-150 focus:outline-none focus:ring-0 focus:border-slate-300 focus:bg-blue-50" required>
                            <div class="text-xs text-slate-500 mt-1">{{ trans("lang.user_first_name_help") }}</div>
                        </div>
                        <div>
                            <label class="text-sm text-slate-700 font-medium">{{trans('lang.last_name')}}</label>
                            <input type="text" class="user_last_name border !border-slate-300 rounded-lg py-2 px-3 w-full transition duration-150 focus:outline-none focus:ring-0 focus:border-slate-300 focus:bg-blue-50">
                             <div class="text-xs text-slate-500 mt-1">{{ trans("lang.user_last_name_help") }}</div>
                        </div>
                    </div>
                    <div>
                        <label class="text-sm text-slate-700 font-medium">{{trans('lang.email')}}</label>
                        <input type="email" class="user_email border !border-slate-300 rounded-lg py-2 px-3 w-full transition duration-150 focus:outline-none focus:ring-0 focus:border-slate-300 focus:bg-blue-50" required>
                         <div class="text-xs text-slate-500 mt-1">{{ trans("lang.user_email_help") }}</div>
                    </div>
                     <div class="grid grid-cols-1 md:grid-cols-2 gap-5">
                        <div>
                            <label class="text-sm text-slate-700 font-medium">{{trans('lang.password')}}</label>
                            <input type="password" class="user_password border !border-slate-300 rounded-lg py-2 px-3 w-full transition duration-150 focus:outline-none focus:ring-0 focus:border-slate-300 focus:bg-blue-50" required>
                             <div class="text-xs text-slate-500 mt-1">{{ trans("lang.user_password_help") }}</div>
                        </div>
                        <div>
                            <label class="text-sm text-slate-700 font-medium">{{trans('lang.user_phone')}}</label>
                            <input type="text" class="user_phone border !border-slate-300 rounded-lg py-2 px-3 w-full transition duration-150 focus:outline-none focus:ring-0 focus:border-slate-300 focus:bg-blue-50">
                            <div class="text-xs text-slate-500 mt-1">{{ trans("lang.user_phone_help") }}</div>
                        </div>
                        <div>
                            <label class="text-sm text-slate-700 font-medium">Country</label>
                            <select id="country_id" class="border !border-slate-300 rounded-lg py-2 px-3 
                                w-full transition duration-150 focus:outline-none focus:ring-0 
                                focus:border-slate-300 focus:bg-blue-50" required>
                                <option value="">Select Country</option>
                            </select>
                            <div class="text-xs text-slate-500 mt-1">Select the country of your restaurant</div>
                        </div>
                    </div>
                    <div>
                        <label class="text-sm text-slate-700 font-medium">{{trans('lang.restaurant_image')}}</label>
                        <input type="file" onChange="handleFileSelectowner(event)" class="mt-2">
                        <div id="uploding_image_owner"></div>
                        <div class="uploaded_image_owner mt-2" style="display:none;"><img id="uploaded_image_owner" src="" width="150px" height="150px;" class="rounded-lg"></div>
                    </div>
                </div>
            </div>

            <!-- Restaurant Details Card -->
            <div class="rounded-lg border !border-slate-300 shadow-[1px_1px_4px_0px_#e2e8f0] overflow-hidden flex flex-col">
                <div class="bg-slate-900 px-6 py-4">
                    <h3 class="text-xl font-bold text-white m-0">{{trans('lang.restaurant_details')}}</h3>
                </div>
                <div class="p-6 bg-white flex-grow flex flex-col gap-5">
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-5">
                        <div>
                            <label class="text-sm text-slate-700 font-medium">{{trans('lang.restaurant_name')}}</label>
                            <input type="text" class="restaurant_name border !border-slate-300 rounded-lg py-2 px-3 w-full transition duration-150 focus:outline-none focus:ring-0 focus:border-slate-300 focus:bg-blue-50" required>
                            <div class="text-xs text-slate-500 mt-1">{{ trans("lang.restaurant_name_help") }}</div>
                        </div>
                        <div>
                            <label class="text-sm text-slate-700 font-medium">{{trans('lang.category')}}</label>
                            <select id='restaurant_cuisines' class="border !border-slate-300 rounded-lg py-2 px-3 w-full transition duration-150 focus:outline-none focus:ring-0 focus:border-slate-300 focus:bg-blue-50" required>
                                <option value="">{{ trans("lang.select_cuisines") }}</option>
                            </select>
                            <div class="text-xs text-slate-500 mt-1">{{ trans("lang.restaurant_cuisines_help") }}</div>
                        </div>
                    </div>
                     <div>
                        <label class="text-sm text-slate-700 font-medium">{{trans('lang.restaurant_phone')}}</label>
                        <input type="text" class="restaurant_phone border !border-slate-300 rounded-lg py-2 px-3 w-full transition duration-150 focus:outline-none focus:ring-0 focus:border-slate-300 focus:bg-blue-50" required>
                        <div class="text-xs text-slate-500 mt-1">{{ trans("lang.restaurant_phone_help") }}</div>
                    </div>
                     <div>
                        <label class="text-sm text-slate-700 font-medium">{{trans('lang.restaurant_email')}}</label>
                        <input type="email" class="restaurant_email border !border-slate-300 rounded-lg py-2 px-3 w-full transition duration-150 focus:outline-none focus:ring-0 focus:border-slate-300 focus:bg-blue-50" required>
                        <div class="text-xs text-slate-500 mt-1">Wprowadź adres email restauracji</div>
                    </div>
                     <div>
                        <label class="text-sm text-slate-700 font-medium">{{trans('lang.restaurant_address')}}</label>
                        <input type="text" class="restaurant_address border !border-slate-300 rounded-lg py-2 px-3 w-full transition duration-150 focus:outline-none focus:ring-0 focus:border-slate-300 focus:bg-blue-50" required>
                        <div class="text-xs text-slate-500 mt-1">{{ trans("lang.restaurant_address_help") }}</div>
                    </div>
                    <div class="text-sm p-3 bg-blue-50 rounded-lg">
                        * Don't Know your cordinates ? use <a target="_blank" href="https://www.latlong.net/" class="text-blue-500 hover:underline">Latitude and Longitude Finder</a>
                    </div>
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-5">
                         <div>
                            <label class="text-sm text-slate-700 font-medium">{{trans('lang.restaurant_latitude')}}</label>
                            <input class="restaurant_latitude border !border-slate-300 rounded-lg py-2 px-3 w-full transition duration-150 focus:outline-none focus:ring-0 focus:border-slate-300 focus:bg-blue-50" type="number" min="-90" max="90">
                             <div class="text-xs text-slate-500 mt-1">{{ trans("lang.restaurant_latitude_help") }}</div>
                        </div>
                        <div>
                            <label class="text-sm text-slate-700 font-medium">{{trans('lang.restaurant_longitude')}}</label>
                            <input class="restaurant_longitude border !border-slate-300 rounded-lg py-2 px-3 w-full transition duration-150 focus:outline-none focus:ring-0 focus:border-slate-300 focus:bg-blue-50" type="number" min="-180" max="180">
                            <div class="text-xs text-slate-500 mt-1">{{ trans("lang.restaurant_longitude_help") }}</div>
                        </div>
                    </div>
                    <div>
                        <label class="text-sm text-slate-700 font-medium">{{trans('lang.restaurant_description')}}</label>
                        <textarea rows="5" class="restaurant_description border !border-slate-300 rounded-lg py-2 px-3 w-full transition duration-150 focus:outline-none focus:ring-0 focus:border-slate-300 focus:bg-blue-50" id="restaurant_description"></textarea>
                    </div>
                    <div>
                        <label class="text-sm text-slate-700 font-medium">{{trans('lang.restaurant_image')}}</label>
                        <input type="file" onChange="handleFileSelect(event,'photo')" class="mt-2">
                        <div id="uploding_image_restaurant"></div>
                        <div class="uploaded_image mt-2" style="display:none;"><img id="uploaded_image" src="" width="150px" height="150px;" class="rounded-lg"></div>
                        <div class="text-xs text-slate-500 mt-1">{{ trans("lang.restaurant_image_help") }}</div>
                    </div>
                </div>
            </div>

            <!-- Gallery Card -->
            <div class="rounded-lg border !border-slate-300 shadow-[1px_1px_4px_0px_#e2e8f0] overflow-hidden flex flex-col">
                 <div class="bg-slate-900 px-6 py-4">
                    <h3 class="text-xl font-bold text-white m-0">{{trans('lang.gallery')}}</h3>
                </div>
                <div class="p-6 bg-white flex-grow flex flex-col gap-5">
                    <div class="restaurant_image">
                        <div id="photos" class="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4"></div>
                    </div>
                    <div>
                        <input type="file" onChange="handleFileSelect(event,'photos')">
                        <div id="uploding_image_photos"></div>
                    </div>
                </div>
            </div>

            <!-- Restaurant Tags Card -->
            <div class="rounded-lg border !border-slate-300 shadow-[1px_1px_4px_0px_#e2e8f0] overflow-hidden flex flex-col">
                <div class="bg-slate-900 px-6 py-4">
                    <h3 class="text-xl font-bold text-white m-0">{{trans('lang.tags_heading')}}</h3>
                    <p class="text-sm text-slate-300 m-0">{{trans('lang.select_restaurant_tags')}}</p>
                </div>
                <div class="p-6 bg-white flex-grow">
                    <!-- Price Range -->
                    <div class="mb-6">
                        <h4 class="font-semibold text-slate-700 mb-3">{{trans('lang.tags_group_price')}}</h4>
                        <div class="grid grid-cols-1 sm:grid-cols-3 gap-3">
                            <div class="flex items-center"><input type="radio" name="price_range" id="price_budget" class="h-4 w-4"><label class="ml-2" for="price_budget">{{trans('lang.price_budget')}}</label></div>
                            <div class="flex items-center"><input type="radio" name="price_range" id="price_moderate" class="h-4 w-4"><label class="ml-2" for="price_moderate">{{trans('lang.price_moderate')}}</label></div>
                            <div class="flex items-center"><input type="radio" name="price_range" id="price_expensive" class="h-4 w-4"><label class="ml-2" for="price_expensive">{{trans('lang.price_expensive')}}</label></div>
                        </div>
                    </div>
                    
                    <!-- Cuisine Type -->
                    <div class="mb-6">
                        <h4 class="font-semibold text-slate-700 mb-3">{{trans('lang.tags_group_cuisine')}}</h4>
                        <div class="grid grid-cols-1 sm:grid-cols-2 gap-3">
                            <div class="flex items-center"><input type="radio" name="cuisine_type" id="cuisine_german" class="h-4 w-4"><label class="ml-2" for="cuisine_german">{{trans('lang.cuisine_german')}}</label></div>
                            <div class="flex items-center"><input type="radio" name="cuisine_type" id="cuisine_gutbuergerlich" class="h-4 w-4"><label class="ml-2" for="cuisine_gutbuergerlich">{{trans('lang.cuisine_gutbuergerlich')}}</label></div>
                            <div class="flex items-center"><input type="radio" name="cuisine_type" id="cuisine_bavarian" class="h-4 w-4"><label class="ml-2" for="cuisine_bavarian">{{trans('lang.cuisine_bavarian')}}</label></div>
                            <div class="flex items-center"><input type="radio" name="cuisine_type" id="cuisine_italian" class="h-4 w-4"><label class="ml-2" for="cuisine_italian">{{trans('lang.cuisine_italian')}}</label></div>
                            <div class="flex items-center"><input type="radio" name="cuisine_type" id="cuisine_greek" class="h-4 w-4"><label class="ml-2" for="cuisine_greek">{{trans('lang.cuisine_greek')}}</label></div>
                            <div class="flex items-center"><input type="radio" name="cuisine_type" id="cuisine_turkish" class="h-4 w-4"><label class="ml-2" for="cuisine_turkish">{{trans('lang.cuisine_turkish')}}</label></div>
                            <div class="flex items-center"><input type="radio" name="cuisine_type" id="cuisine_asian" class="h-4 w-4"><label class="ml-2" for="cuisine_asian">{{trans('lang.cuisine_asian')}}</label></div>
                            <div class="flex items-center"><input type="radio" name="cuisine_type" id="cuisine_french" class="h-4 w-4"><label class="ml-2" for="cuisine_french">{{trans('lang.cuisine_french')}}</label></div>
                            <div class="flex items-center"><input type="radio" name="cuisine_type" id="cuisine_imbiss" class="h-4 w-4"><label class="ml-2" for="cuisine_imbiss">{{trans('lang.cuisine_imbiss')}}</label></div>
                            <div class="flex items-center"><input type="radio" name="cuisine_type" id="cuisine_brauhaus" class="h-4 w-4"><label class="ml-2" for="cuisine_brauhaus">{{trans('lang.cuisine_brauhaus')}}</label></div>
                            <div class="flex items-center"><input type="radio" name="cuisine_type" id="cuisine_cafe_konditorei" class="h-4 w-4"><label class="ml-2" for="cuisine_cafe_konditorei">{{trans('lang.cuisine_cafe_konditorei')}}</label></div>
                        </div>
                    </div>
                    
                    <!-- Venue Type -->
                    <div class="mb-4">
                        <h4 class="font-semibold text-slate-700 mb-3">{{trans('lang.tags_group_venue_type')}}</h4>
                        <div class="grid grid-cols-1 sm:grid-cols-2 gap-3">
                            <div class="flex items-center"><input type="radio" name="venue_type" id="venue_restaurant" class="h-4 w-4"><label class="ml-2" for="venue_restaurant">{{trans('lang.venue_restaurant')}}</label></div>
                            <div class="flex items-center"><input type="radio" name="venue_type" id="venue_bar" class="h-4 w-4"><label class="ml-2" for="venue_bar">{{trans('lang.venue_bar')}}</label></div>
                            <div class="flex items-center"><input type="radio" name="venue_type" id="venue_pub" class="h-4 w-4"><label class="ml-2" for="venue_pub">{{trans('lang.venue_pub')}}</label></div>
                            <div class="flex items-center"><input type="radio" name="venue_type" id="venue_cafe" class="h-4 w-4"><label class="ml-2" for="venue_cafe">{{trans('lang.venue_cafe')}}</label></div>
                            <div class="flex items-center"><input type="radio" name="venue_type" id="venue_beer_garden" class="h-4 w-4"><label class="ml-2" for="venue_beer_garden">{{trans('lang.venue_beer_garden')}}</label></div>
                            <div class="flex items-center"><input type="radio" name="venue_type" id="venue_fast_food" class="h-4 w-4"><label class="ml-2" for="venue_fast_food">{{trans('lang.venue_fast_food')}}</label></div>
                            <div class="flex items-center"><input type="radio" name="venue_type" id="venue_club" class="h-4 w-4"><label class="ml-2" for="venue_club">{{trans('lang.venue_club')}}</label></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Dine-in, Working Hours, etc. can be added as more cards here -->

        <div class="form-group col-12 text-center mt-8">
            <button type="button" class="w-full md:w-1/2 lg:w-1/3 create_restaurant_btn h-12 flex items-center justify-center bg-blue-500 hover:bg-blue-600 text-white text-base font-semibold rounded-md shadow-md uppercase focus:outline-none focus:ring-0 active:outline-none active:ring-0 transition-opacity mx-auto">
                <i class="fa fa-save mr-2"></i> {{trans('lang.save')}}
            </button>
            <div class="my-4 relative flex justify-center items-center">
                <span class="absolute w-full h-px bg-slate-300"></span>
                <span class="relative bg-white px-3 text-sm text-slate-500">{{trans('lang.or')}}</span>
            </div>
            <a href="{{route('login')}}" class="text-slate-600 hover:text-blue-500 transition-colors">
                <p class="text-center m-0">{{trans('lang.already_an_account')}} {{trans('lang.sign_in')}}</p>
            </a>
        </div>
    </div>
</div>

{{-- Keep the old script tag for now, as it contains all the logic --}}
@endsection

@section('scripts')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="{{ asset('js/jquery.cookie.js') }}"></script>
<script src="{{ asset('js/jquery.validate.js') }}"></script>

@section('scripts')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<script>
/**
 * Restaurant Registration — Laravel/PostgreSQL version
 *
 * Changes from original:
 *  - All $.ajax / $.get calls replaced with fetch()
 *  - Firebase Storage removed — images go to /register/upload-image (Laravel)
 *  - Routes are injected by Blade: window.routes = { … }
 *  - countriesData cache kept exactly as before
 *  - Working-hours & special-discount collectors unchanged
 */
 
// ── State (mirrors original globals) ─────────────────────────────────────────
let restaurantPhoto         = '';
let ownerphoto              = '';
let restaurnt_photos        = [];
let restaurant_menu_photos  = [];
let photocount              = 0;
let menuPhotoCount          = 0;
let countriesData           = {};
 
const timeslotwork = { Sunday:[], Monday:[], Tuesday:[], Wednesday:[], Thursday:[], Friday:[], Satuarday:[] };
const timeslot     = { Sunday:[], Monday:[], Tuesday:[], Wednesday:[], Thursday:[], Friday:[], Satuarday:[] };
 
// ── CSRF token helper (reads Laravel's XSRF-TOKEN cookie) ────────────────────
function csrfToken() {
    return document.cookie
        .split('; ')
        .find(r => r.startsWith('XSRF-TOKEN='))
        ?.split('=')[1]
        ?.replace(/%3D/g, '=') ?? '';
}
 
// The Blade template must inject these URLs, e.g.:
// <script>
  window.routes = {
    countries:   "{{ route('register.countries') }}",
    cuisines:    "{{ route('register.cuisines') }}",
    uploadImage: "{{ route('register.upload-image') }}",
    deleteImage: "{{ route('register.delete-image') }}",
    store:       "{{ route('register.restaurant') }}",
  };

const routes = window.routes;
 
// ── On page load: fetch countries ─────────────────────────────────────────────
document.addEventListener('DOMContentLoaded', async () => {
    showProcessing(true);
    try {
        const res  = await fetch(routes.countries, { credentials: 'same-origin' });
        const data = await res.json();
 
        const select = document.getElementById('country_id');
        data.forEach(c => {
            countriesData[c.id] = c;
            const opt = document.createElement('option');
            opt.value = c.id;
            opt.textContent = c.name;
            select.appendChild(opt);
        });
    } catch {
        showError('Failed to load countries. Please refresh.');
    } finally {
        showProcessing(false);
    }
});
 
// ── Country change → load cuisines + apply settings ──────────────────────────
document.getElementById('country_id').addEventListener('change', async function () {
    const countryId = this.value;
    const cuisineEl = document.getElementById('restaurant_cuisines');
 
    cuisineEl.innerHTML = '<option value="">Select Cuisines</option>';
    if (!countryId) return;
 
    // Apply country settings immediately (no extra request)
    const s = countriesData[countryId];
 
    // Load cuisines
    try {
        const res  = await fetch(`${routes.cuisines}?country_id=${countryId}`, { credentials: 'same-origin' });
        const data = await res.json();
 
        if (!data.length) {
            cuisineEl.innerHTML += '<option disabled>No cuisines available</option>';
            return;
        }
        data.forEach(c => {
            const opt = document.createElement('option');
            opt.value = c.id;
            opt.textContent = c.title;
            cuisineEl.appendChild(opt);
        });
    } catch {
        cuisineEl.innerHTML += '<option disabled>Failed to load cuisines</option>';
    }
});
 
// ── Core image upload → Laravel ───────────────────────────────────────────────
async function uploadImage(file, onSuccess, statusEl) {
    if (!file) return;
    statusEl.textContent = 'Uploading…';
 
    const form = new FormData();
    form.append('image', file);
 
    try {
        const res  = await fetch(routes.uploadImage, {
            method: 'POST',
            credentials: 'same-origin',
            headers: { 'X-XSRF-TOKEN': csrfToken() },
            body: form,
        });
        const data = await res.json();
        if (data.url) {
            onSuccess(data.url);
            statusEl.textContent = 'Upload complete';
        } else {
            statusEl.textContent = 'Upload failed.';
        }
    } catch {
        statusEl.textContent = 'Upload failed.';
    }
}
 
// ── Owner photo ───────────────────────────────────────────────────────────────
function handleFileSelectowner(evt) {
    uploadImage(
        evt.target.files[0],
        url => {
            ownerphoto = url;
            document.getElementById('uploaded_image_owner').src = url;
            document.querySelector('.uploaded_image_owner').style.display = '';
        },
        document.getElementById('uploding_image_owner')
    );
}
 
// ── Restaurant photo + gallery ────────────────────────────────────────────────
function handleFileSelect(evt, type) {
    uploadImage(
        evt.target.files[0],
        url => {
            if (type === 'photo') {
                restaurantPhoto = url;
                document.getElementById('uploaded_image').src = url;
                document.querySelector('.uploaded_image').style.display = '';
                document.getElementById('uploding_image_restaurant').textContent = 'Upload complete';
            } else {
                photocount++;
                document.getElementById('photos').insertAdjacentHTML('beforeend',
                    `<span class="image-item" id="photo_${photocount}">
                        <span class="remove-btn cursor-pointer" data-id="${photocount}" data-img="${url}">
                            <i class="fa fa-remove"></i>
                        </span>
                        <img width="100px" height="auto" src="${url}">
                    </span>`
                );
                restaurnt_photos.push(url);
                document.getElementById('uploding_image_photos').textContent = 'Upload complete';
            }
        },
        document.getElementById(type === 'photo' ? 'uploding_image_restaurant' : 'uploding_image_photos')
    );
}
 
// ── Menu card photos ──────────────────────────────────────────────────────────
function handleFileSelectMenuCard(evt) {
    uploadImage(
        evt.target.files[0],
        url => {
            menuPhotoCount++;
            document.getElementById('photos_menu_card').insertAdjacentHTML('beforeend',
                `<span class="image-item" id="photo_menu${menuPhotoCount}">
                    <span class="remove-btn remove-menu-btn" data-id="${menuPhotoCount}" data-img="${url}">
                        <i class="fa fa-remove"></i>
                    </span>
                    <img width="100px" height="auto" src="${url}">
                </span>`
            );
            restaurant_menu_photos.push(url);
            document.getElementById('uploaded_image_menu').textContent = 'Upload complete';
        },
        document.getElementById('uploaded_image_menu')
    );
}
 
// ── Remove gallery photo ──────────────────────────────────────────────────────
document.addEventListener('click', async e => {
    const btn = e.target.closest('.remove-btn');
    if (!btn) return;
 
    const id  = btn.dataset.id;
    const url = btn.dataset.img;
 
    await fetch(routes.deleteImage, {
        method: 'POST',
        credentials: 'same-origin',
        headers: { 'Content-Type': 'application/json', 'X-XSRF-TOKEN': csrfToken() },
        body: JSON.stringify({ url }),
    });
 
    document.getElementById('photo_' + id)?.remove();
    const idx = restaurnt_photos.indexOf(url);
    if (idx > -1) restaurnt_photos.splice(idx, 1);
});
 
// ── Register / Save ───────────────────────────────────────────────────────────
document.querySelector('.create_restaurant_btn').addEventListener('click', async () => {
    hideError();
 
    const countryId       = getVal('country_id');
    const userFirstName   = getVal('user_first_name').trim();
    const userLastName    = getVal('user_last_name').trim();
    const email           = getVal('user_email').trim();
    const password        = getVal('user_password');
    const userPhone       = getVal('user_phone').trim();
    const restaurantname  = getVal('restaurant_name').trim();
    const cuisines        = getVal('restaurant_cuisines');
    const phonenumber     = getVal('restaurant_phone').trim();
    const restaurantEmail = getVal('restaurant_email').trim();
    const address         = getVal('restaurant_address').trim();
    const latitude        = parseFloat(getVal('restaurant_latitude'));
    const longitude       = parseFloat(getVal('restaurant_longitude'));
    const description     = getVal('restaurant_description').trim();
    const restaurantCost  = getVal('restaurant_cost');
    const reststatus      = document.getElementById('is_open').checked;
    const enabledDiveIn   = document.getElementById('dine_in_feature').checked;
 
    // ── Client-side validation (same order as original) ──────────────────────
    const validEmail = s => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(s);
    let error = '';
    if (!countryId)                              error = 'Please select your country.';
    else if (!userFirstName)                     error = "{{ trans('lang.enter_owners_name_error') }}";
    else if (!email)                             error = "{{ trans('lang.enter_owners_email') }}";
    else if (!password)                          error = "{{ trans('lang.enter_owners_password_error') }}";
    else if (!userPhone)                         error = "{{ trans('lang.enter_owners_phone') }}";
    else if (!restaurantname)                    error = "{{ trans('lang.restaurant_name_error') }}";
    else if (!cuisines)                          error = "{{ trans('lang.restaurant_cuisine_error') }}";
    else if (!phonenumber)                       error = "{{ trans('lang.restaurant_phone_error') }}";
    else if (!restaurantEmail)                   error = "{{ trans('lang.restaurant_email_error') }}";
    else if (!validEmail(restaurantEmail))       error = "{{ trans('lang.restaurant_email_invalid_error') }}";
    else if (!address)                           error = "{{ trans('lang.restaurant_address_error') }}";
    else if (isNaN(latitude))                    error = "{{ trans('lang.restaurant_lattitude_error') }}";
    else if (latitude < -90 || latitude > 90)    error = "{{ trans('lang.restaurant_lattitude_limit_error') }}";
    else if (isNaN(longitude))                   error = "{{ trans('lang.restaurant_longitude_error') }}";
    else if (longitude < -180 || longitude > 180)error = "{{ trans('lang.restaurant_longitude_limit_error') }}";
    else if (!description)                       error = "{{ trans('lang.restaurant_description_error') }}";
 
    if (error) { showError(error); return; }
 
    // ── Filters ───────────────────────────────────────────────────────────────
    const filterKeys = [
        'price_budget','price_moderate','price_expensive',
        'cuisine_german','cuisine_gutbuergerlich','cuisine_bavarian','cuisine_italian',
        'cuisine_greek','cuisine_turkish','cuisine_asian','cuisine_french',
        'cuisine_imbiss','cuisine_brauhaus','cuisine_cafe_konditorei',
        'venue_restaurant','venue_bar','venue_pub','venue_cafe',
        'venue_beer_garden','venue_fast_food','venue_club',
    ];
    const filters = {};
    filterKeys.forEach(k => { filters[k] = document.getElementById(k)?.checked ?? false; });
 
    // ── Working hours (uses the timeslotwork map) ─────────────────────────────
    const working_hours = [
        { day: 'Monday',    timeslot: timeslotwork.Monday    },
        { day: 'Tuesday',   timeslot: timeslotwork.Tuesday   },
        { day: 'Wednesday', timeslot: timeslotwork.Wednesday },
        { day: 'Thursday',  timeslot: timeslotwork.Thursday  },
        { day: 'Friday',    timeslot: timeslotwork.Friday    },
        { day: 'Saturday',  timeslot: timeslotwork.Satuarday },
        { day: 'Sunday',    timeslot: timeslotwork.Sunday    },
    ];
 
    // ── Special discounts ─────────────────────────────────────────────────────
    const special_discount = [
        { day: 'Monday',    timeslot: timeslot.Monday    },
        { day: 'Tuesday',   timeslot: timeslot.Tuesday   },
        { day: 'Wednesday', timeslot: timeslot.Wednesday },
        { day: 'Thursday',  timeslot: timeslot.Thursday  },
        { day: 'Friday',    timeslot: timeslot.Friday    },
        { day: 'Saturday',  timeslot: timeslot.Satuarday },
        { day: 'Sunday',    timeslot: timeslot.Sunday    },
    ];
 
    // ── Submit ────────────────────────────────────────────────────────────────
    showProcessing(true);
 
    try {
        const res = await fetch(routes.store, {
            method: 'POST',
            credentials: 'same-origin',
            headers: {
                'Content-Type':  'application/json',
                'Accept':        'application/json',
                'X-XSRF-TOKEN':  csrfToken(),
            },
            body: JSON.stringify({
                // Country
                country_id:       countryId,
                // Owner
                first_name:       userFirstName,
                last_name:        userLastName,
                email,
                password,
                phone:            userPhone,
                owner_photo:      ownerphoto,
                // Restaurant
                restaurant_name:  restaurantname,
                category_id:      cuisines,
                category_title:   document.querySelector('#restaurant_cuisines option:checked')?.textContent ?? '',
                restaurant_phone: phonenumber,
                restaurant_email: restaurantEmail,
                address,
                latitude,
                longitude,
                description,
                photo:            restaurantPhoto,
                photos:           restaurnt_photos,
                rest_status:      reststatus,
                restaurant_cost:  restaurantCost,
                enabled_dine_in:  enabledDiveIn,
                open_dine_time:   getVal('openDineTime')  || null,
                close_dine_time:  getVal('closeDineTime') || null,
                filters,
                working_hours,
                menu_photos:      restaurant_menu_photos,
            }),
        });
 
        const data = await res.json();
        showProcessing(false);
 
        if (data.success) {
            document.querySelector('.alert-success').style.display = '';
            document.querySelector('.alert-success').innerHTML = `<p>${data.message}</p>`;
            window.scrollTo(0, 0);
            clearInput();
        } else {
            showError(data.message ?? 'Something went wrong.');
        }
    } catch (err) {
        showProcessing(false);
        showError('Something went wrong. Please try again.');
    }
});
 
// ── Working hours UI (unchanged logic, just tidied) ───────────────────────────
let countAddhours = 1;
 
function addMorehour(day, day2, _count) {
    const count = countAddhours;
    document.querySelector(`#working_hour_table_${day} tr:last-child`).insertAdjacentHTML('afterend',
        `<tr>
            <td><input type="time" class="form-control" id="from${day}${count}"></td>
            <td><input type="time" class="form-control" id="to${day}${count}"></td>
            <td><button type="button" class="bg-blue-500 text-white px-3 py-1 rounded save_option_day_button${day}${count}"
                onclick="addMoreFunctionhour('${day2}','${day}',${count})">Save</button></td>
            <td><button type="button" class="btn btn-danger" onclick="removeMorehour('${day}',${count})">
                <i class="fa fa-trash"></i></button></td>
        </tr>`
    );
    countAddhours++;
}
 
function addMoreFunctionhour(day1, day2, count) {
    const from = document.getElementById(`from${day2}${count}`)?.value;
    const to   = document.getElementById(`to${day2}${count}`)?.value;
 
    if (!from || !to) {
        showError('Please enter valid time.'); return;
    }
 
    // Map HTML day keys (lowercase) to our object keys
    const keyMap = {
        sunday: 'Sunday', monday: 'Monday', tuesday: 'Tuesday',
        wednesday: 'Wednesday', thursday: 'Thursday', friday: 'Friday', satuarday: 'Satuarday'
    };
    const key = keyMap[day1.toLowerCase()];
    if (key) timeslotwork[key].push({ from, to });
 
    document.querySelector(`.save_option_day_button${day2}${count}`)?.style.setProperty('display','none');
    document.getElementById(`from${day2}${count}`).disabled = true;
    document.getElementById(`to${day2}${count}`).disabled   = true;
}
 
// ── Special discounts UI (unchanged logic) ────────────────────────────────────
let countAddButton = 1;
 
// ── Dine-in toggle ────────────────────────────────────────────────────────────
document.getElementById('dine_in_feature').addEventListener('change', function () {
    document.querySelector('.divein_div').style.display = this.checked ? '' : 'none';
});

 
document.querySelector('.add_working_hours_restaurant_btn').addEventListener('click', () => {
    document.querySelector('.working_hours_div').style.display = '';
});
 
// ── Utilities ─────────────────────────────────────────────────────────────────
function getVal(id) { return document.getElementById(id)?.value ?? ''; }
function setVal(id, v) { const el = document.getElementById(id); if (el) el.value = v; }
 
function showError(msg) {
    const el = document.querySelector('.error_top');
    if (el) { el.innerHTML = `<p>${msg}</p>`; el.style.display = ''; }
    window.scrollTo(0, 0);
}
function hideError() {
    const el = document.querySelector('.error_top');
    if (el) el.style.display = 'none';
}
function showProcessing(show) {
    const el = document.getElementById('data-table_processing');
    if (el) el.style.display = show ? '' : 'none';
}
 
function clearInput() {
    ['user_first_name','user_last_name','user_email','user_password','user_phone',
     'restaurant_name','restaurant_phone','restaurant_email','restaurant_address',
     'restaurant_latitude','restaurant_longitude','restaurant_description','country_id']
        .forEach(id => setVal(id, ''));
}
</script>

@endsection
