<main class="main-wrapper">
    <div class="main-content">
        <div class="row">
            <div class="col-md-8 my-2">
                <h3 class="fmon">Profile</h3>
            </div>
        </div>

        <form class="row my-2" id="profileForm" enctype="multipart/form-data">
            <!-- Profile Image Section -->
            <div class="col-md-12">
                <div class="d-flex justify-content-between align-items-center">
                    <label for="profileImageUpload">
                        <img class="profmage" id="profileImagePreview"
                            src="<?= $user['u_image'] ?? base_url('assets/images/avatars/01.png') ?>"
                            alt="Profile Image">
                    </label>
                    <input type="file" id="profileImageUpload" name="profile_image" accept="image/*" style="display: none;">
                    <button type="submit" id="update_btn" class="btn setBtn px-5 py-3" disabled>Update Profile</button>
                </div>
            </div>

            <!-- Basic Information -->
            <div class="col-md-6 my-2">
                <label class="clabel">Name</label>
                <input class="form-control formInput" type="text" name="name"
                    value="<?= $user['name'] ?? '' ?>">
            </div>

            <!-- <div class="col-md-6 my-2">
              <label class="clabel">Start Date</label>
              <input class="form-control formInput" type="text" name="start_date" 
                     value="<?= $user['startDate'] ?? '' ?>">
          </div> -->

            <!-- Shop Information -->
            <!-- <div class="col-md-6 my-2">
                <label class="clabel">Shop Timing</label>
                <input class="form-control formInput" type="text" name="shop_timing"
                    value="<?= $user['shopTiming'] ?? '' ?>">
            </div> -->
            <div class="col-md-6 my-2">
                <label class="clabel">Shop Timing</label>

                <!-- Split Time Inputs -->
                <div class="d-flex gap-2">
                    <input type="time" class="form-control formInput" id="time_from" placeholder="From">
                    <input type="time" class="form-control formInput" id="time_to" placeholder="To">
                </div>

                <!-- Hidden Combined Input -->
                <input type="hidden" id="shop_timing" name="shop_timing"
                    value="<?= $user['shopTiming'] ?? '' ?>">
            </div>

            <script>
                const timeFrom = document.getElementById('time_from');
                const timeTo = document.getElementById('time_to');
                const shopTiming = document.getElementById('shop_timing');

                function updateShopTiming() {
                    const from = timeFrom.value;
                    const to = timeTo.value;
                    if (from && to) {
                        shopTiming.value = `${from} - ${to}`;
                    } else {
                        shopTiming.value = '';
                    }
                }

                timeFrom.addEventListener('change', updateShopTiming);
                timeTo.addEventListener('change', updateShopTiming);

                window.addEventListener('DOMContentLoaded', () => {
                    const currentValue = shopTiming.value;
                    if (currentValue.includes(' - ')) {
                        const [from, to] = currentValue.split(' - ');
                        timeFrom.value = from;
                        timeTo.value = to;
                    }
                });
            </script>


            <!-- Google Maps Places API -->
            <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDfRI5hac8jwDvEQ1k2S5jfNEiNa9vcWhE&libraries=places&callback=initAutocomplete" async defer></script>

            <!-- Shop Location Input with Validation -->
            <div class="col-md-6 my-2">
                <label class="clabel">Shop Location</label>
                <input id="shop_location" class="form-control formInput" type="text" name="shop_location"
                    value="<?= $user['shopLocation'] ?? '' ?>">
                <input type="hidden" name="lat" id="lat" value="<?= $user['lat'] ?? '' ?>">
                <input type="hidden" name="lng" id="lng" value="<?= $user['lng'] ?? '' ?>">
                <small id="locationError" class="text-danger d-none">Please select a valid location from the suggestions.</small>
            </div>

            <!-- Tailor Specific Fields -->
            <div class="col-md-6 my-2">
                <label class="clabel">ETA (Estimated Delivery Time)</label>
                <input class="form-control formInput" type="text" name="eta"
                    value="<?= $user['eta'] ?? '' ?>"
                    placeholder="e.g., 3 days">
            </div>

            <div class="col-md-6 my-2">
                <label class="clabel">State</label>
                <input class="form-control formInput" type="text" name="state"
                    value="<?= $user['state'] ?? '' ?>"
                    placeholder="e.g., Abu Dhabi">
            </div>

            <!-- Categories Selection -->
            <div class="col-md-12 my-2">
                <label class="clabel">Specializations</label>
                <div class="row">
                    <?php foreach ($categories as $category): ?>
                        <div class="col-md-3">
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox"
                                    name="categoryIds[]"
                                    value="<?= $category['id'] ?>"
                                    id="cat_<?= $category['id'] ?>"
                                    <?= in_array($category['id'], $user['categoryId'] ?? []) ? 'checked' : '' ?>>
                                <label class="form-check-label text-capitalize" for="cat_<?= $category['id'] ?>">
                                    <?= $category['data']['name'] ?? 'Unnamed Category' ?>
                                </label>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>

            <!-- Tailor Type Selection -->
            <div class="col-md-6 my-2">
                <label class="clabel">Tailor Type</label>
                <select class="form-control formInput" name="tailor_type">
                    <option value="">Select Service Type</option>
                    <option value="Men's Tailor" <?= ($user['tailorType'] ?? '') === "Men's Tailor" ? 'selected' : '' ?>>Men's Tailor</option>
                    <option value="Women's Tailor" <?= ($user['tailorType'] ?? '') === "Women's Tailor" ? 'selected' : '' ?>>Women's Tailor</option>
                    <option value="Both Men's & Women's Tailor" <?= ($user['tailorType'] ?? '') === "Both Men's & Women's Tailor" ? 'selected' : '' ?>>Both</option>
                </select>
            </div>
        </form>
    </div>
</main>

<script>
    let autocomplete;
    let placeSelected = false;

    function initAutocomplete() {
        const input = document.getElementById('shop_location');
        const latInput = document.getElementById('lat');
        const lngInput = document.getElementById('lng');
        const updateBtn = document.getElementById('update_btn');
        const errorMsg = document.getElementById('locationError');

        autocomplete = new google.maps.places.Autocomplete(input, {
            types: ['geocode'],
            componentRestrictions: {
                country: 'ae'
            }
        });

        autocomplete.addListener('place_changed', () => {
            const place = autocomplete.getPlace();
            if (place.geometry) {
                latInput.value = place.geometry.location.lat();
                lngInput.value = place.geometry.location.lng();
                placeSelected = true;

                updateBtn.disabled = false;
                errorMsg.classList.add('d-none');
            }
        });

        input.addEventListener('blur', () => {
            if (!placeSelected || !latInput.value || !lngInput.value) {
                updateBtn.disabled = true;
                errorMsg.classList.remove('d-none');
            } else {
                errorMsg.classList.add('d-none');
            }
        });

        input.addEventListener('input', () => {
            placeSelected = false;
            latInput.value = '';
            lngInput.value = '';
            updateBtn.disabled = true;
            errorMsg.classList.add('d-none');
        });

        // If the existing values are already valid on load, enable button
        if (input.value.trim() !== '' && latInput.value && lngInput.value) {
            updateBtn.disabled = false;
        }
    }
</script>

<script>
    document.getElementById("profileImageUpload").addEventListener("change", function(e) {
        const reader = new FileReader();
        reader.onload = () => document.getElementById("profileImagePreview").src = reader.result;
        reader.readAsDataURL(e.target.files[0]);
    });

    document.getElementById("profileForm").addEventListener("submit", function(e) {
        e.preventDefault();
        const formData = new FormData(this);

        document.querySelector(".loader-overlay").style.display = "block";

        fetch("<?= base_url('dashboard/updateProfile') ?>", {
                method: "POST",
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                document.querySelector(".loader-overlay").style.display = "none";
                if (data.success) {
                    Swal.fire({
                        icon: 'success',
                        title: 'Success!',
                        text: data.message,
                        confirmButtonColor: '#FFD700'
                    }).then(() => location.reload());
                } else {
                    Swal.fire({
                        icon: 'error',
                        title: 'Error!',
                        text: data.message,
                        confirmButtonColor: '#FFD700'
                    });
                }
            })
            .catch(error => {
                console.error("Error:", error);
                document.querySelector(".loader-overlay").style.display = "none";
                Swal.fire({
                    icon: 'error',
                    title: 'Error!',
                    text: 'Update failed. Please try again.',
                    confirmButtonColor: '#FFD700'
                });
            });
    });
</script>