<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(102, 126, 234, 0.1);
    outline: none;
}

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

.section-title {
    color: #667eea;
    font-weight: 600;
    margin-bottom: 1.5rem;
    display: flex;
    align-items: center;
    gap: 0.75rem;
}

.section-title i {
    font-size: 1.25rem;
}

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

.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(102, 126, 234, 0.3);
}

.btn-submit-modern:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 12px rgba(102, 126, 234, 0.4);
    color: white;
}
</style>

<!-- Begin Page Content -->
<div class="container-fluid">
    <div class="form-header-modern">
        <h2 class="mb-2">
            <i class="fa-solid fa-user-plus"></i> Add New Vendor
        </h2>
        <p class="mb-0 opacity-75">Create a new vendor account with city assignment and fulfillment type</p>
    </div>
    
    <form id="addVendorForm" enctype="multipart/form-data" method="POST" action="<?php echo base_url('vendors/insertvendor'); ?>">
        <div class="form-card-modern">
            <div class="card-header">
                <h5 class="mb-0">
                    <i class="fa-solid fa-user text-primary"></i> Basic Information
                </h5>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-12 form-group-modern">
                        <label for="imagefile" class="form-label-modern">
                            <i class="fa-solid fa-image"></i> Vendor Image
                        </label>
                        <input type="file" class="form-control form-control-modern" id="imagefile" name="imagefile" accept="image/*">
                        <small class="text-muted">Optional: Upload vendor profile image</small>
                    </div>
                </div>

                <div class="row">
                    <div class="col-md-6 form-group-modern">
                        <label for="firstName" class="form-label-modern">First Name <span class="text-danger">*</span></label>
                        <input type="text" class="form-control form-control-modern" id="firstName" name="firstName" required>
                    </div>
                    <div class="col-md-6 form-group-modern">
                        <label for="lastName" class="form-label-modern">Last Name</label>
                        <input type="text" class="form-control form-control-modern" id="lastName" name="lastName">
                    </div>
                </div>

                <div class="row">
                    <div class="col-md-6 form-group-modern">
                        <label for="email" class="form-label-modern">Email <span class="text-danger">*</span></label>
                        <input type="email" class="form-control form-control-modern" id="email" name="email" required>
                    </div>
                    <div class="col-md-6 form-group-modern">
                        <label for="phoneNumber" class="form-label-modern">Phone Number</label>
                        <input type="text" class="form-control form-control-modern" id="phoneNumber" name="phoneNumber">
                    </div>
                </div>

                <div class="row">
                    <div class="col-md-6 form-group-modern">
                        <label for="shopName" class="form-label-modern">Store/Shop Name</label>
                        <input type="text" class="form-control form-control-modern" id="shopName" name="shopName">
                    </div>
                    <div class="col-md-6 form-group-modern">
                        <label for="password" class="form-label-modern">Password <span class="text-danger">*</span></label>
                        <input type="password" class="form-control form-control-modern" id="password" name="password" minlength="6" required>
                        <small class="text-muted">Minimum 6 characters</small>
                    </div>
                </div>

                <div class="row">
                    <div class="col-md-12 form-group-modern">
                        <label for="address" class="form-label-modern">Address</label>
                        <input type="text" class="form-control form-control-modern" id="address" name="address" placeholder="Enter address">
                    </div>
                </div>
            </div>
        </div>

        <div class="form-card-modern">
            <div class="card-header">
                <h5 class="mb-0">
                    <i class="fa-solid fa-map-marker-alt text-primary"></i> Location & City Assignment
                </h5>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-6 form-group-modern">
                        <label for="cityId" class="form-label-modern">Assign City <span class="text-danger">*</span></label>
                        <select class="form-control form-control-modern" id="cityId" name="cityId" required>
                            <option value="">-- Select City --</option>
                            <?php foreach ($cities as $cityId => $city): ?>
                                <option value="<?php echo $cityId; ?>">
                                    <?php echo isset($city['cityName']) ? $city['cityName'] : 'Unknown'; ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-6 form-group-modern">
                        <label for="fulfillment_type" class="form-label-modern">Fulfillment Type <span class="text-danger">*</span></label>
                        <select class="form-control form-control-modern" id="fulfillment_type" name="fulfillment_type" required>
                            <option value="storefront_pickup">Storefront Pickup</option>
                            <option value="cannabus_inventory">Cannabus Inventory</option>
                        </select>
                        <small class="text-muted">Storefront Pickup: Driver picks up from vendor. Cannabus Inventory: Product already with driver.</small>
                    </div>
                </div>

                <div class="row" id="locationFields">
                    <div class="col-md-6 form-group-modern">
                        <label for="vendorAddress" class="form-label-modern">Vendor Location Address</label>
                        <input type="text" class="form-control form-control-modern" id="vendorAddress" name="vendorAddress" placeholder="Search for address">
                        <small class="text-muted">Use Google Places autocomplete</small>
                    </div>
                    <div class="col-md-3 form-group-modern">
                        <label for="latitude" class="form-label-modern">Latitude</label>
                        <input type="number" step="any" min="-90" max="90" class="form-control form-control-modern" id="latitude" name="latitude" placeholder="Auto-filled">
                    </div>
                    <div class="col-md-3 form-group-modern">
                        <label for="longitude" class="form-label-modern">Longitude</label>
                        <input type="number" step="any" min="-180" max="180" class="form-control form-control-modern" id="longitude" name="longitude" placeholder="Auto-filled">
                    </div>
                    <input type="hidden" id="googlePlaceId" name="googlePlaceId">
                </div>
            </div>
        </div>

        <div class="form-card-modern">
            <div class="card-header">
                <h5 class="mb-0">
                    <i class="fa-solid fa-cog text-primary"></i> Status & Driver Assignment
                </h5>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-6 form-group-modern">
                        <div class="form-check form-switch">
                            <input class="form-check-input" type="checkbox" id="isApproved" name="isApproved" value="1" style="width: 3rem; height: 1.5rem;">
                            <label class="form-check-label form-label-modern" for="isApproved">
                                Approve Vendor Immediately
                            </label>
                        </div>
                    </div>
                    <div class="col-md-6 form-group-modern">
                        <div class="form-check form-switch">
                            <input class="form-check-input" type="checkbox" id="isActive" name="isActive" value="1" checked style="width: 3rem; height: 1.5rem;">
                            <label class="form-check-label form-label-modern" for="isActive">
                                Active Status
                            </label>
                        </div>
                    </div>
                </div>

                <div class="row">
                    <div class="col-md-12 form-group-modern">
                        <label for="assignedDriverIds" class="form-label-modern">Assign Drivers (Optional)</label>
                        <select class="form-control form-control-modern" id="assignedDriverIds" name="assignedDriverIds[]" multiple size="5">
                            <?php if (isset($drivers) && !empty($drivers)): ?>
                                <?php foreach ($drivers as $driverId => $driver): ?>
                                    <option value="<?php echo $driverId; ?>">
                                        <?php echo isset($driver['firstName']) ? $driver['firstName'] : ''; ?> 
                                        <?php echo isset($driver['lastName']) ? $driver['lastName'] : ''; ?>
                                        (<?php echo isset($driver['email']) ? $driver['email'] : ''; ?>)
                                    </option>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <option disabled>No drivers available</option>
                            <?php endif; ?>
                        </select>
                        <small class="text-muted">Hold Ctrl/Cmd to select multiple drivers</small>
                    </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> Add Vendor
            </button>
            <a href="<?php echo base_url('vendors'); ?>" class="btn btn-secondary btn-modern">
                <i class="fa-solid fa-times"></i> Cancel
            </a>
        </div>
    </form>
</div>

<!-- Google Maps API for address autocomplete -->
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB0jx5yCf4vk4I5ridEorfPMqohEhpH1H4&libraries=places"></script>

<script>
$(document).ready(function() {
    // Initialize Google Places Autocomplete
    var autocomplete = new google.maps.places.Autocomplete(document.getElementById('vendorAddress'));
    
    autocomplete.addListener('place_changed', function() {
        var place = autocomplete.getPlace();
        
        if (place.geometry) {
            // Ensure proper decimal formatting
            var lat = parseFloat(place.geometry.location.lat()).toFixed(6);
            var lng = parseFloat(place.geometry.location.lng()).toFixed(6);
            
            $('#latitude').val(lat);
            $('#longitude').val(lng);
            $('#googlePlaceId').val(place.place_id);
            $('#address').val(place.formatted_address);
        }
    });
    
    // Show/hide location fields based on fulfillment type
    $('#fulfillment_type').on('change', function() {
        if ($(this).val() === 'storefront_pickup') {
            $('#locationFields').show();
            $('#latitude, #longitude').prop('required', true);
        } else {
            $('#locationFields').hide();
            $('#latitude, #longitude').prop('required', false);
            // Clear location fields for Cannabus inventory
            $('#vendorAddress, #latitude, #longitude, #googlePlaceId').val('');
        }
    });
    
    // Trigger on page load
    $('#fulfillment_type').trigger('change');
    
    // Form submission with SweetAlert
    $('#addVendorForm').on('submit', function(e) {
        e.preventDefault();
        
        var formData = new FormData(this);
        
        $.ajax({
            url: $(this).attr('action'),
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    Swal.fire({
                        icon: 'success',
                        title: 'Success!',
                        text: response.message,
                        confirmButtonText: 'OK'
                    }).then((result) => {
                        if (result.isConfirmed) {
                            window.location.href = '<?php echo base_url("vendors"); ?>';
                        }
                    });
                } else {
                    Swal.fire({
                        icon: 'error',
                        title: 'Error!',
                        text: response.message
                    });
                }
            },
            error: function() {
                // Fallback to regular form submission if AJAX fails
                document.getElementById('addVendorForm').submit();
            }
        });
    });
});
</script>

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