<style>
.form-header-modern {
    background: linear-gradient(135deg, #72A565 0%, #91A134 100%);
    color: white;
    padding: 2rem;
    border-radius: 15px;
    margin-bottom: 2rem;
    box-shadow: 0 10px 30px rgba(0,0,0,0.1);
}

.form-card-modern {
    background: white;
    border-radius: 15px;
    box-shadow: 0 5px 15px rgba(0,0,0,0.08);
    margin-bottom: 1.5rem;
    border: none;
    overflow: hidden;
}

.form-card-modern .card-header {
    background: linear-gradient(135deg, #f7fafc 0%, #edf2f7 100%);
    border-bottom: 2px solid #e2e8f0;
    padding: 1.25rem 1.5rem;
    font-weight: 600;
    color: #2d3748;
}

.form-card-modern .card-body {
    padding: 2rem;
}

.form-label-modern {
    font-weight: 600;
    color: #2d3748;
    margin-bottom: 0.5rem;
    font-size: 0.875rem;
    text-transform: uppercase;
    letter-spacing: 0.5px;
}

.form-control-modern {
    border-radius: 10px;
    border: 2px solid #e2e8f0;
    padding: 0.75rem 1rem;
    transition: all 0.3s ease;
}

.form-control-modern:focus {
    border-color: #72A565;
    box-shadow: 0 0 0 3px rgba(114, 165, 101, 0.1);
    outline: none;
}

.btn-submit-modern {
    background: linear-gradient(135deg, #72A565 0%, #91A134 100%);
    border: none;
    color: white;
    padding: 0.75rem 2rem;
    border-radius: 10px;
    font-weight: 600;
    transition: all 0.3s ease;
    box-shadow: 0 4px 6px rgba(114, 165, 101, 0.3);
}

.btn-submit-modern:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 12px rgba(114, 165, 101, 0.4);
    color: white;
}

.form-group-modern {
    margin-bottom: 1.5rem;
}

.section-divider {
    border: none;
    height: 2px;
    background: linear-gradient(90deg, transparent, #e2e8f0, transparent);
    margin: 2rem 0;
}

.info-box {
    background: #f7fafc;
    border-left: 4px solid #667eea;
    padding: 1rem;
    border-radius: 8px;
    margin-bottom: 1.5rem;
}
</style>

<!-- Begin Page Content -->
<div class="container-fluid">
    <div class="form-header-modern">
        <h2 class="mb-2">
            <i class="fa-solid fa-city"></i> <?php echo (isset($city)) ? 'Edit City' : 'Add City' ?>
        </h2>
        <p class="mb-0 opacity-75">Configure city details, location, and HQ address for delivery zone calculations</p>
    </div>
    
    <?php
    if(isset($city)){
        $endpoint = 'updatecity';
    }else{
        $endpoint = 'insertcity';
    }
    ?>
    
    <form method="post" id="add_city" action="<?php echo base_url() . "dashboard/".$endpoint; ?>">
        <input type="hidden" name="id" id="id" value="<?=isset($id) ? $id : ''?>">
        <input type="hidden" name="googlePlaceId" id="googlePlaceId" value="<?php echo isset($city['googlePlaceId']) ? $city['googlePlaceId'] : '';?>">

        <!-- City Information -->
        <div class="form-card-modern">
            <div class="card-header">
                <h5 class="mb-0">
                    <i class="fa-solid fa-map-marker-alt text-primary"></i> City Information
                </h5>
            </div>
            <div class="card-body">
                <div class="info-box">
                    <i class="fa-solid fa-info-circle text-primary"></i>
                    <strong>Quick Search:</strong> Use Google Places autocomplete below to quickly fill city details, or enter manually.
                </div>

                <div class="form-group-modern">
                    <label class="form-label-modern">Search City (Google Places)</label>
                    <input type="text" id="autocomplete" class="form-control form-control-modern" placeholder="Start typing city name..." autocomplete="off">
                    <small class="text-muted">Select a city from Google Places to auto-fill the form (optional)</small>
                </div>

                <div class="row">
                    <div class="col-md-12 form-group-modern">
                        <label class="form-label-modern">City Name <span class="text-danger">*</span></label>
                        <input type="text" name="cityName" id="cityName" class="form-control form-control-modern" 
                            placeholder="City Name" value="<?php echo isset($city['cityName']) ? $city['cityName'] : '';?>" required>
                    </div>
                </div>

                <div class="row">
                    <div class="col-md-6 form-group-modern">
                        <label class="form-label-modern">State <span class="text-danger">*</span></label>
                        <input type="text" name="state" id="state" class="form-control form-control-modern" 
                            placeholder="State" value="<?php echo isset($city['state']) ? $city['state'] : '';?>" required>
                    </div>
                    <div class="col-md-6 form-group-modern">
                        <label class="form-label-modern">Country <span class="text-danger">*</span></label>
                        <input type="text" name="country" id="country" class="form-control form-control-modern" 
                            placeholder="Country" value="<?php echo isset($city['country']) ? $city['country'] : '';?>" required>
                    </div>
                </div>

                <div class="row">
                    <div class="col-md-6 form-group-modern">
                        <label class="form-label-modern">Latitude <span class="text-danger">*</span></label>
                        <input type="number" step="any" min="-90" max="90" name="latitude" id="latitude" 
                            class="form-control form-control-modern" placeholder="Latitude (can be negative)" 
                            value="<?php echo isset($city['latitude']) ? $city['latitude'] : '';?>" required>
                    </div>
                    <div class="col-md-6 form-group-modern">
                        <label class="form-label-modern">Longitude <span class="text-danger">*</span></label>
                        <input type="number" step="any" min="-180" max="180" name="longitude" id="longitude" 
                            class="form-control form-control-modern" placeholder="Longitude (can be negative)" 
                            value="<?php echo isset($city['longitude']) ? $city['longitude'] : '';?>" required>
                    </div>
                </div>
            </div>
        </div>

        <!-- City HQ Information -->
        <div class="form-card-modern">
            <div class="card-header">
                <h5 class="mb-0">
                    <i class="fa-solid fa-building text-primary"></i> City HQ (Delivery Zone Center)
                </h5>
            </div>
            <div class="card-body">
                <div class="info-box">
                    <i class="fa-solid fa-info-circle text-primary"></i>
                    <strong>HQ Address:</strong> The HQ address is used as the origin point for all distance calculations and zone assignments. 
                    This is where drivers start their routes.
                </div>

                <div class="form-group-modern">
                    <label class="form-label-modern">Search HQ Address (Google Places)</label>
                    <input type="text" id="hqAutocomplete" class="form-control form-control-modern" 
                        placeholder="Start typing HQ address..." autocomplete="off">
                    <small class="text-muted">Select HQ address from Google Places to auto-fill coordinates (optional)</small>
                </div>

                <div class="form-group-modern">
                    <label class="form-label-modern">HQ Address (Full Text)</label>
                    <textarea name="hqAddress" id="hqAddress" class="form-control form-control-modern" rows="3" 
                        placeholder="Enter full HQ address"><?php echo isset($city['hqAddress']) ? $city['hqAddress'] : '';?></textarea>
                </div>

                <div class="row">
                    <div class="col-md-6 form-group-modern">
                        <label class="form-label-modern">HQ Latitude</label>
                        <input type="number" step="any" min="-90" max="90" name="hqLatitude" id="hqLatitude" 
                            class="form-control form-control-modern" placeholder="HQ Latitude" 
                            value="<?php echo isset($city['hqLatitude']) ? $city['hqLatitude'] : '';?>">
                    </div>
                    <div class="col-md-6 form-group-modern">
                        <label class="form-label-modern">HQ Longitude</label>
                        <input type="number" step="any" min="-180" max="180" name="hqLongitude" id="hqLongitude" 
                            class="form-control form-control-modern" placeholder="HQ Longitude" 
                            value="<?php echo isset($city['hqLongitude']) ? $city['hqLongitude'] : '';?>">
                    </div>
                </div>
            </div>
        </div>

        <div class="text-end mb-4">
            <button type="submit" class="btn btn-submit-modern">
                <i class="fa-solid fa-save"></i> <?php echo (isset($city)) ? 'Update City' : 'Add City' ?>
            </button>
            <a href="<?php echo base_url('dashboard/cities'); ?>" class="btn btn-secondary btn-modern">
                <i class="fa-solid fa-times"></i> Cancel
            </a>
        </div>
    </form>
</div>

<!-- Google Places Autocomplete Script -->
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB0jx5yCf4vk4I5ridEorfPMqohEhpH1H4&libraries=places,geometry,directions"></script>

<script>
    function initializeAutocomplete() {
        var autocomplete = new google.maps.places.Autocomplete(
            document.getElementById('autocomplete'),
            {
                types: ['(cities)'],
                componentRestrictions: { country: [] }
            }
        );

        autocomplete.addListener('place_changed', function() {
            var place = autocomplete.getPlace();
            
            if (!place.geometry) {
                console.log("No details available for input: '" + place.name + "'");
                return;
            }

            var cityName = '';
            var state = '';
            var country = '';
            
            for (var i = 0; i < place.address_components.length; i++) {
                var component = place.address_components[i];
                var componentType = component.types[0];

                switch(componentType) {
                    case 'locality':
                        cityName = component.long_name;
                        break;
                    case 'administrative_area_level_1':
                        state = component.long_name;
                        break;
                    case 'country':
                        country = component.long_name;
                        break;
                }
            }

            if (!cityName && place.name) {
                cityName = place.name.split(',')[0].trim();
            }

            document.getElementById('cityName').value = cityName || '';
            document.getElementById('state').value = state || '';
            document.getElementById('country').value = country || '';
            document.getElementById('latitude').value = place.geometry.location.lat();
            document.getElementById('longitude').value = place.geometry.location.lng();
            document.getElementById('googlePlaceId').value = place.place_id || '';
        });
    }

    function initializeHQAutocomplete() {
        var hqAutocomplete = new google.maps.places.Autocomplete(
            document.getElementById('hqAutocomplete'),
            {
                types: ['address']
            }
        );

        hqAutocomplete.addListener('place_changed', function() {
            var place = hqAutocomplete.getPlace();
            
            if (!place.geometry) {
                console.log("No details available for HQ input: '" + place.name + "'");
                return;
            }

            document.getElementById('hqAddress').value = place.formatted_address || '';
            document.getElementById('hqLatitude').value = place.geometry.location.lat();
            document.getElementById('hqLongitude').value = place.geometry.location.lng();
        });
    }

    google.maps.event.addDomListener(window, 'load', function() {
        initializeAutocomplete();
        initializeHQAutocomplete();
    });
</script>

<!-- SweetAlert2 -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<script>
$(document).ready(function() {
    $('#add_city').on('submit', function(e) {
        e.preventDefault();
        
        var form = $(this);
        var formData = form.serialize();
        var url = form.attr('action');
        
        var submitBtn = form.find('button[type="submit"]');
        var originalText = submitBtn.html();
        submitBtn.prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i> Processing...');
        
        $.ajax({
            url: url,
            type: 'POST',
            data: formData,
            dataType: 'json',
            headers: {
                'X-Requested-With': 'XMLHttpRequest'
            },
            success: function(response) {
                submitBtn.prop('disabled', false).html(originalText);
                
                if (response.success) {
                    Swal.fire({
                        icon: 'success',
                        title: 'Success!',
                        text: response.message,
                        confirmButtonText: 'OK',
                        timer: 2000,
                        timerProgressBar: true
                    }).then(function() {
                        window.location.href = '<?php echo base_url("dashboard/cities"); ?>';
                    });
                } else {
                    Swal.fire({
                        icon: 'error',
                        title: 'Error!',
                        text: response.message,
                        confirmButtonText: 'OK'
                    });
                }
            },
            error: function(xhr, status, error) {
                submitBtn.prop('disabled', false).html(originalText);
                
                var errorMessage = 'Something went wrong. Please try again.';
                try {
                    var response = JSON.parse(xhr.responseText);
                    if (response.message) {
                        errorMessage = response.message;
                    }
                } catch (e) {
                    // If not JSON, use default message
                }
                
                Swal.fire({
                    icon: 'error',
                    title: 'Error!',
                    text: errorMessage,
                    confirmButtonText: 'OK'
                });
            }
        });
    });
});
</script>
