@extends('layouts.app')

@section('title', 'My Profile - ' . \App\Models\Setting::get('site_name', 'KiyoKart'))

@section('content')
<div class="container profile-container">
    <!-- Profile Header -->
    <div class="profile-page-header">
        <div class="d-flex align-items-center">
            <div class="profile-avatar">
                {{ strtoupper(substr($user->name, 0, 1)) }}
            </div>
            <div class="profile-header-info">
                <h1>
                    My Profile
                </h1>
                <div class="profile-header-email">
                    <i class="bi bi-envelope"></i>
                    @if($user->email)
                        {{ $user->email }}
                    @else
                        No email address set
                    @endif
                </div>
            </div>
        </div>
    </div>

    <div class="row">
        <!-- Main Content -->
        <div class="col-lg-8">
            <!-- Profile Information -->
            <div class="profile-card-modern">
                <div class="profile-card-header">
                    <h5>
                        <i class="bi bi-person-gear"></i> Profile Information
                    </h5>
                </div>
                <div class="profile-card-body">
                    <form action="{{ route('customer.profile.update') }}" method="POST">
                        @csrf
                        @method('PUT')

                        <div class="profile-form-group">
                            <label class="profile-form-label">
                                <i class="bi bi-person"></i> Full Name
                            </label>
                            <input type="text" 
                                   name="name" 
                                   class="profile-form-control form-control" 
                                   value="{{ old('name', $user->name) }}" 
                                   required
                                   placeholder="Enter your full name">
                        </div>

                        <div class="profile-form-group">
                            <label class="profile-form-label">
                                <i class="bi bi-phone"></i> Mobile Number
                            </label>
                            <div class="input-group">
                                <span class="input-group-text">+91</span>
                                <input type="text" 
                                       class="profile-form-control form-control" 
                                       value="{{ preg_replace('/^\+91/', '', $user->mobile) }}" 
                                       readonly 
                                       disabled>
                            </div>
                            <div class="profile-form-help">
                                <i class="bi bi-info-circle"></i>
                                Mobile number cannot be changed for security reasons
                            </div>
                        </div>

                        <div class="profile-form-group">
                            <label class="profile-form-label">
                                <i class="bi bi-envelope"></i> Email Address <span class="text-muted">(Optional)</span>
                            </label>
                            <input type="email" 
                                   name="email" 
                                   class="profile-form-control form-control" 
                                   value="{{ old('email', $user->email) }}"
                                   placeholder="Enter your email address">
                            <div class="profile-form-help">
                                <i class="bi bi-info-circle"></i>
                                Email address is optional but recommended for order updates
                            </div>
                        </div>

                        <div class="profile-form-group">
                            <label class="profile-form-label">
                                <i class="bi bi-receipt"></i> GST Number <span class="text-muted">(Optional)</span>
                            </label>
                            <input type="text"
                                   name="gst_number"
                                   class="profile-form-control form-control"
                                   value="{{ old('gst_number', $user->gst_number) }}"
                                   maxlength="15"
                                   pattern="[0-9A-Z]{15}"
                                   placeholder="15-digit GSTIN (e.g., 29ABCDE1234F2Z5)">
                            <div class="profile-form-help">
                                <i class="bi bi-info-circle"></i>
                                Enter a 15-character GSTIN if you need invoices with GST details.
                            </div>
                        </div>

                        <div class="mt-4 d-flex gap-3 flex-wrap">
                            <button type="submit" class="btn-profile-primary">
                                <i class="bi bi-check-circle"></i> Update Profile
                            </button>
                        </div>
                    </form>
                </div>
            </div>

            <!-- Change Password -->
            <div class="change-password-card">
                <div class="profile-card-header">
                    <h5>
                        <i class="bi bi-shield-lock"></i> Change Password
                    </h5>
                </div>
                <div class="profile-card-body">
                    <form action="{{ route('customer.profile.change-password') }}" method="POST">
                        @csrf
                        @method('PUT')

                        <div class="profile-form-group">
                            <label class="profile-form-label">
                                <i class="bi bi-shield-lock"></i> New Password
                            </label>
                            <input type="password"
                                   name="password"
                                   class="profile-form-control form-control @error('password') is-invalid @enderror"
                                   placeholder="Enter a new password"
                                   required>
                            @error('password')
                                <div class="invalid-feedback">{{ $message }}</div>
                            @enderror
                            <div class="profile-form-help">
                                <i class="bi bi-info-circle"></i>
                                Use at least 8 characters with a mix of letters and numbers.
                            </div>
                        </div>

                        <div class="profile-form-group">
                            <label class="profile-form-label">
                                <i class="bi bi-lock-fill"></i> Confirm New Password
                            </label>
                            <input type="password"
                                   name="password_confirmation"
                                   class="profile-form-control form-control"
                                   placeholder="Re-enter your new password"
                                   required>
                        </div>

                        <div class="mt-3">
                            <button type="submit" class="btn-profile-primary">
                                <i class="bi bi-arrow-repeat"></i> Update Password
                            </button>
                        </div>
                    </form>
                </div>
            </div>

            <!-- Saved Addresses -->
            <div class="profile-card-modern">
                <div class="profile-card-header d-flex justify-content-between align-items-center flex-wrap gap-2">
                    <h5 class="mb-0">
                        <i class="bi bi-geo-alt"></i> Saved Addresses
                    </h5>
                    <button type="button" class="btn btn-secondary" data-bs-toggle="modal" data-bs-target="#addAddressModal">
                        <i class="bi bi-plus-circle"></i> Add New Address
                    </button>
                </div>
                <div class="profile-card-body">
                    @forelse($user->addresses as $address)
                        <div class="address-card">
                            <div class="address-card-header">
                                <div class="address-name">
                                    <i class="bi bi-person"></i>
                                    {{ $address->name }}
                                </div>
                                <div class="d-flex align-items-center gap-2">
                                    @if($address->is_default)
                                        <span class="address-default-badge">
                                            <i class="bi bi-check-circle"></i> Default
                                        </span>
                                    @endif
                    <button type="button"
                            class="btn btn-primary"
                                            data-bs-toggle="modal"
                                            data-bs-target="#editAddressModal"
                                            data-update-action="{{ route('customer.addresses.update', $address) }}"
                                            data-name="{{ $address->name }}"
                                            data-mobile="{{ preg_replace('/^\+91/', '', $address->mobile) }}"
                                            data-line1="{{ $address->line1 }}"
                                            data-line2="{{ $address->line2 }}"
                                            data-country="{{ $address->country_id }}"
                                            data-state="{{ $address->state_id }}"
                                            data-city="{{ $address->city_id }}"
                                            data-state-name="{{ $address->stateRelation?->name ?? $address->state }}"
                                            data-city-name="{{ $address->cityRelation?->name ?? $address->city }}"
                                            data-pin="{{ $address->pin }}"
                                            data-default="{{ $address->is_default ? '1' : '0' }}">
                                        <i class="bi bi-pencil-square"></i>
                                        Edit
                                    </button>
                                </div>
                            </div>
                            <div class="address-details">
                                <div class="address-detail-item">
                                    <i class="bi bi-telephone"></i>
                                    <span>{{ $address->mobile }}</span>
                                </div>
                                <div class="address-detail-item">
                                    <i class="bi bi-geo-alt-fill"></i>
                                    <span>{{ $address->full_address }}</span>
                                </div>
                            </div>
                        </div>
                    @empty
                        <div class="empty-address">
                            <i class="bi bi-inbox"></i>
                            <h6 class="mt-3 mb-2">No Saved Addresses</h6>
                            <p class="text-muted mb-0">You haven't saved any addresses yet. Add one to speed up checkout.</p>
                        </div>
                    @endforelse
                </div>
            </div>
        </div>

        <!-- Sidebar -->
        <div class="col-lg-4">
            <!-- Profile Stats -->
            @php
                $orderCount = \App\Models\Order::where('user_id', $user->id)->count();
                $addressCount = $user->addresses->count();
            @endphp
            <div class="profile-stats-card">
                <div class="profile-stats-grid">
                    <div>
                        <div class="profile-stats-title">Total Orders</div>
                        <div class="profile-stats-value">{{ $orderCount }}</div>
                    </div>
                    <div>
                        <div class="profile-stats-title">Saved Addresses</div>
                        <div class="profile-stats-value">{{ $addressCount }}</div>
                    </div>
                </div>
            </div>

            <!-- Quick Links -->
            <div class="quick-links-card">
                <div class="quick-links-header">
                    <h5>
                        <i class="bi bi-link-45deg"></i> Quick Links
                    </h5>
                </div>
                <ul class="quick-links-list">
                    <li class="quick-links-item">
                        <a href="{{ route('customer.orders.index') }}">
                            <i class="bi bi-box-seam"></i>
                            <span>My Orders</span>
                        </a>
                    </li>
                    <li class="quick-links-item">
                        <a href="{{ route('cart.index') }}">
                            <i class="bi bi-cart3"></i>
                            <span>Shopping Cart</span>
                        </a>
                    </li>
                    <li class="quick-links-item">
                        <a href="{{ route('checkout.index') }}">
                            <i class="bi bi-bag-check"></i>
                            <span>Checkout</span>
                        </a>
                    </li>
                    <li class="quick-links-item">
                        <a href="{{ route('home') }}">
                            <i class="bi bi-house"></i>
                            <span>Continue Shopping</span>
                        </a>
                    </li>
                </ul>
            </div>
        </div>
    </div>
</div>

<!-- Add Address Modal -->
<div class="modal fade mt-5" id="addAddressModal" tabindex="-1" aria-labelledby="addAddressModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-centered">
        <div class="modal-content brand-modal">
            <div class="modal-header">
                <h5 class="modal-title" id="addAddressModalLabel">Add New Address</h5>
                <button type="button" class="btn p-0 text-white" data-bs-dismiss="modal" aria-label="Close"><i class="bi-x-lg"></i></button>
            </div>
            <form action="{{ route('customer.addresses.store') }}" method="POST" class="address-form" data-address-form>
                @csrf
                <div class="modal-body">
                    <div class="row g-3">
                        <div class="col-md-6">
                            <label class="form-label">Name *</label>
                            <input type="text" name="name" class="form-control" value="{{ old('name', $user->name) }}" required>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Mobile *</label>
                            <div class="input-group">
                                <span class="input-group-text">+91</span>
                                <input type="text" name="mobile" class="form-control" placeholder="9876543210" maxlength="10" pattern="[6-9]\d{9}" value="{{ old('mobile', preg_replace('/^\+91/', '', $user->mobile)) }}" required>
                            </div>
                        </div>
                        <div class="col-md-12">
                            <label class="form-label">Address Line 1 *</label>
                            <input type="text" name="line1" class="form-control" value="{{ old('line1') }}" required>
                        </div>
                        <div class="col-md-12">
                            <label class="form-label">Address Line 2</label>
                            <input type="text" name="line2" class="form-control" value="{{ old('line2') }}">
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">Country *</label>
                            <select name="country_id" class="form-select" required data-country-select data-selected-country="{{ old('country_id') }}">
                                <option value="">Select country</option>
                            </select>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">State *</label>
                            <select name="state_id" class="form-select" required data-state-select data-selected-state="{{ old('state_id') }}" disabled>
                                <option value="">Select state</option>
                            </select>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">City *</label>
                            <select name="city_id" class="form-select" required data-city-select data-selected-city="{{ old('city_id') }}" disabled>
                                <option value="">Select city</option>
                            </select>
                        </div>
                        <input type="hidden" name="state" data-state-name value="{{ old('state') }}">
                        <input type="hidden" name="city" data-city-name value="{{ old('city') }}">
                        <div class="col-md-4">
                            <label class="form-label">PIN Code *</label>
                            <input type="text" name="pin" class="form-control" maxlength="6" value="{{ old('pin') }}" required>
                        </div>
                        <div class="col-md-8 d-flex align-items-center mt-4">
                            <div class="form-check">
                                <input type="checkbox" name="is_default" value="1" class="form-check-input" id="addIsDefault">
                                <label class="form-check-label" for="addIsDefault">Set as default address</label>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Save Address</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Edit Address Modal -->
<div class="modal fade mt-5" id="editAddressModal" tabindex="-1" aria-labelledby="editAddressModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-centered">
        <div class="modal-content brand-modal">
            <div class="modal-header">
                <h5 class="modal-title" id="editAddressModalLabel">Edit Address</h5>
                <button type="button" class="btn p-0 text-white" data-bs-dismiss="modal" aria-label="Close"><i class="bi-x-lg"></i></button>
            </div>
            <form id="editAddressForm" method="POST" class="address-form" data-address-form>
                @csrf
                @method('PUT')
                <div class="modal-body">
                    <div class="row g-3">
                        <div class="col-md-6">
                            <label class="form-label">Name *</label>
                            <input type="text" name="name" class="form-control" required>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Mobile *</label>
                            <div class="input-group">
                                <span class="input-group-text">+91</span>
                                <input type="text" name="mobile" class="form-control" placeholder="9876543210" maxlength="10" pattern="[6-9]\d{9}" required>
                            </div>
                        </div>
                        <div class="col-md-12">
                            <label class="form-label">Address Line 1 *</label>
                            <input type="text" name="line1" class="form-control" required>
                        </div>
                        <div class="col-md-12">
                            <label class="form-label">Address Line 2</label>
                            <input type="text" name="line2" class="form-control">
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">Country *</label>
                            <select name="country_id" class="form-select" required data-country-select>
                                <option value="">Select country</option>
                            </select>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">State *</label>
                            <select name="state_id" class="form-select" required data-state-select disabled>
                                <option value="">Select state</option>
                            </select>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">City *</label>
                            <select name="city_id" class="form-select" required data-city-select disabled>
                                <option value="">Select city</option>
                            </select>
                        </div>
                        <input type="hidden" name="state" data-state-name>
                        <input type="hidden" name="city" data-city-name>
                        <div class="col-md-4">
                            <label class="form-label">PIN Code *</label>
                            <input type="text" name="pin" class="form-control" maxlength="6" required>
                        </div>
                        <div class="col-md-8 d-flex align-items-center mt-4">
                            <div class="form-check">
                                <input type="checkbox" name="is_default" value="1" class="form-check-input" id="editIsDefault">
                                <label class="form-check-label" for="editIsDefault">Set as default address</label>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Update Address</button>
                </div>
            </form>
        </div>
    </div>
</div>

@push('scripts')
<script>
const shippingApiBase = '/api/shipping';

function resetSelect(selectEl, placeholder) {
    if (!selectEl) return;
    selectEl.innerHTML = `<option value="">${placeholder}</option>`;
    selectEl.disabled = true;
}

function populateSelect(selectEl, items, placeholder, selectedId = null) {
    if (!selectEl) return;
    const options = [`<option value=\"\">${placeholder}</option>`];
    items.forEach(item => {
        const selected = selectedId && Number(selectedId) === Number(item.id) ? 'selected' : '';
        options.push(`<option value=\"${item.id}\" ${selected}>${item.name}</option>`);
    });
    selectEl.innerHTML = options.join('');
    selectEl.disabled = items.length === 0;
}

async function fetchJson(url) {
    const response = await fetch(url, { headers: { Accept: 'application/json' } });
    if (!response.ok) throw new Error('Failed to load data');
    return response.json();
}

async function loadCountries(form) {
    const countrySelect = form.querySelector('[data-country-select]');
    const stateSelect = form.querySelector('[data-state-select]');
    const citySelect = form.querySelector('[data-city-select]');
    if (!countrySelect) return;

    const data = await fetchJson(`${shippingApiBase}/countries`);
    const countries = data.data || [];
    let selectedCountry = countrySelect.dataset.selectedCountry || '';
    if (!selectedCountry) {
        const india = countries.find(c => c.code === 'IN');
        selectedCountry = india ? india.id : '';
    }

    populateSelect(countrySelect, countries, 'Select country', selectedCountry);

    if (selectedCountry) {
        await loadStates(form, selectedCountry, stateSelect?.dataset.selectedState || '');
    } else {
        resetSelect(stateSelect, 'Select state');
        resetSelect(citySelect, 'Select city');
    }
}

async function loadStates(form, countryId, selectedStateId = '') {
    const stateSelect = form.querySelector('[data-state-select]');
    const citySelect = form.querySelector('[data-city-select]');
    if (!stateSelect || !countryId) return;
    resetSelect(stateSelect, 'Loading states...');
    resetSelect(citySelect, 'Select city');
    const data = await fetchJson(`${shippingApiBase}/states?country_id=${countryId}`);
    const states = data.data || [];
    populateSelect(stateSelect, states, 'Select state', selectedStateId);
    stateSelect.disabled = false;

    if (selectedStateId) {
        await loadCities(form, selectedStateId, citySelect?.dataset.selectedCity || '');
    }
}

async function loadCities(form, stateId, selectedCityId = '') {
    const citySelect = form.querySelector('[data-city-select]');
    if (!citySelect || !stateId) return;
    resetSelect(citySelect, 'Loading cities...');
    const data = await fetchJson(`${shippingApiBase}/cities?state_id=${stateId}`);
    const cities = data.data || [];
    populateSelect(citySelect, cities, 'Select city', selectedCityId);
    citySelect.disabled = false;
}

function syncHiddenLocationNames(form) {
    const stateSelect = form.querySelector('[data-state-select]');
    const citySelect = form.querySelector('[data-city-select]');
    const stateName = form.querySelector('[data-state-name]');
    const cityName = form.querySelector('[data-city-name]');

    if (stateSelect && stateName) {
        const selected = stateSelect.options[stateSelect.selectedIndex];
        stateName.value = selected ? selected.textContent.trim() : '';
    }
    if (citySelect && cityName) {
        const selected = citySelect.options[citySelect.selectedIndex];
        cityName.value = selected ? selected.textContent.trim() : '';
    }
}

function attachAddressFormHandlers(form) {
    // Prevent duplicate handlers
    if (form.hasAttribute('data-handlers-attached')) {
        return;
    }
    form.setAttribute('data-handlers-attached', 'true');

    // Use event delegation on the form to handle all changes
    // This ensures handlers work even if elements are replaced
    form.addEventListener('change', async (e) => {
        const target = e.target;
        
        // Handle country change
        if (target.matches('[data-country-select]')) {
            const stateSelect = form.querySelector('[data-state-select]');
            const citySelect = form.querySelector('[data-city-select]');
            resetSelect(stateSelect, 'Loading states...');
            resetSelect(citySelect, 'Select city');
            const countryId = target.value;
            target.dataset.selectedCountry = countryId;
            if (countryId) {
                await loadStates(form, countryId);
            }
        }
        
        // Handle state change
        if (target.matches('[data-state-select]')) {
            const citySelect = form.querySelector('[data-city-select]');
            resetSelect(citySelect, 'Loading cities...');
            const stateId = target.value;
            target.dataset.selectedState = stateId;
            if (stateId) {
                await loadCities(form, stateId);
            } else {
                resetSelect(citySelect, 'Select city');
            }
            syncHiddenLocationNames(form);
        }
        
        // Handle city change
        if (target.matches('[data-city-select]')) {
            syncHiddenLocationNames(form);
        }
    });

    // Handle form submit
    form.addEventListener('submit', () => syncHiddenLocationNames(form));
}

async function initAddressForm(form) {
    attachAddressFormHandlers(form);
    try {
        await loadCountries(form);
    } catch (error) {
        console.error('Failed to load address dropdowns', error);
    }
}

document.addEventListener('DOMContentLoaded', () => {
    document.querySelectorAll('[data-address-form]').forEach((form) => {
        initAddressForm(form);
    });

    const editModal = document.getElementById('editAddressModal');
    const editForm = document.getElementById('editAddressForm');

    if (editModal && editForm) {
        editModal.addEventListener('show.bs.modal', async (event) => {
            const button = event.relatedTarget;
            if (!button) return;

            editForm.action = button.dataset.updateAction || '#';
            editForm.querySelector('input[name="name"]').value = button.dataset.name || '';
            editForm.querySelector('input[name="mobile"]').value = button.dataset.mobile || '';
            editForm.querySelector('input[name="line1"]').value = button.dataset.line1 || '';
            editForm.querySelector('input[name="line2"]').value = button.dataset.line2 || '';
            editForm.querySelector('input[name="pin"]').value = button.dataset.pin || '';

            const defaultCheckbox = editForm.querySelector('input[name="is_default"]');
            if (defaultCheckbox) {
                defaultCheckbox.checked = button.dataset.default === '1';
            }

            const countrySelect = editForm.querySelector('[data-country-select]');
            const stateSelect = editForm.querySelector('[data-state-select]');
            const citySelect = editForm.querySelector('[data-city-select]');

            // Reset dropdowns first
            resetSelect(stateSelect, 'Select state');
            resetSelect(citySelect, 'Select city');

            // Set selected values from button data
            const selectedCountry = button.dataset.country || '';
            const selectedState = button.dataset.state || '';
            const selectedCity = button.dataset.city || '';

            if (countrySelect) countrySelect.dataset.selectedCountry = selectedCountry;
            if (stateSelect) stateSelect.dataset.selectedState = selectedState;
            if (citySelect) citySelect.dataset.selectedCity = selectedCity;

            const stateName = editForm.querySelector('[data-state-name]');
            const cityName = editForm.querySelector('[data-city-name]');
            if (stateName) stateName.value = button.dataset.stateName || '';
            if (cityName) cityName.value = button.dataset.cityName || '';

            try {
                // Load countries and cascade to states and cities
                await loadCountries(editForm);
                // Ensure state and city are loaded if country is selected
                if (selectedCountry && selectedState) {
                    await loadStates(editForm, selectedCountry, selectedState);
                }
                if (selectedState && selectedCity) {
                    await loadCities(editForm, selectedState, selectedCity);
                }
                syncHiddenLocationNames(editForm);
            } catch (error) {
                console.error('Failed to load address data', error);
            }
        });
    }
});
</script>
@endpush
@push('styles')
<style>
.brand-modal .modal-header {
    background: linear-gradient(135deg, var(--color-primary), var(--color-secondary));
    color: #ffffff;
    border-bottom: none;
}
.brand-modal .modal-title {
    font-weight: 700;
}
.brand-modal .btn-close {
    filter: invert(1);
}
.brand-modal .modal-content {
    border: none;
    box-shadow: 0 12px 30px rgba(0,0,0,0.12);
    border-radius: 14px;
}
.brand-modal .form-control,
.brand-modal .form-select {
    border: 1px solid var(--border-color);
    border-radius: 10px;
    padding: 0.65rem 0.85rem;
    box-shadow: none;
    transition: var(--transition);
}
.brand-modal .form-control:focus,
.brand-modal .form-select:focus {
    border-color: var(--color-primary);
    box-shadow: 0 0 0 0.2rem rgba(19,35,60,0.1);
}
.brand-modal .form-label {
    color: var(--text-dark);
    font-weight: 600;
}
.brand-modal .modal-footer {
    border-top: 1px solid var(--border-color);
}
.brand-modal .modal-body {
    overflow: visible;
}
.brand-link {
    color: var(--color-primary) !important;
    font-weight: 600;
}
.brand-link:hover {
    color: var(--color-secondary) !important;
    text-decoration: none;
}
.brand-modal select,
.brand-modal .form-select {
    position: relative;
    z-index: 1065;
}
.brand-modal .select2-container {
    z-index: 2000 !important;
}
</style>
@endpush
@endsection
