
<?php $__env->startSection('title', 'Analyze Land'); ?>
<?php $__env->startSection('head'); ?>
<?php if(!empty($googleMapsApiKey)): ?>
<style>
    .pac-container { z-index: 10000 !important; background: var(--bg-card, #1e1e2e); border: 1px solid var(--border, #333); border-radius: 8px; margin-top: 4px; box-shadow: 0 8px 24px rgba(0,0,0,.4); font-family: inherit; }
    .pac-item { padding: 8px 12px; border-top: 1px solid var(--border, #333); color: var(--text, #e0e0e0); cursor: pointer; font-size: 13px; }
    .pac-item:first-child { border-top: none; }
    .pac-item:hover, .pac-item-selected { background: rgba(37,99,235,.15); }
    .pac-item-query { color: var(--text-active, #fff); font-weight: 600; }
    .pac-icon { display: none; }
    .pac-matched { color: #60a5fa; font-weight: 600; }
</style>
<?php endif; ?>
<?php $__env->stopSection(); ?>

<?php $__env->startSection('content'); ?>
<div style="max-width:1100px;margin:0 auto;padding:32px 24px;">

    
    <div style="text-align:center;margin-bottom:40px;">
        <div style="display:inline-flex;align-items:center;gap:6px;background:rgba(37,99,235,.12);border:1px solid rgba(37,99,235,.25);padding:4px 12px;border-radius:20px;font-size:11px;color:#93c5fd;margin-bottom:16px;letter-spacing:.08em;text-transform:uppercase;">
            AI-Powered Land Analysis
        </div>
        <h1 style="font-size:32px;font-weight:700;margin-bottom:8px;line-height:1.2;">Land Feasibility Analysis</h1>
        <p style="font-size:15px;color:var(--text-secondary);max-width:520px;margin:0 auto;">Enter a plot address or coordinates to instantly calculate FAR, buildable area, floor count, setbacks, cost estimates, and feasibility score.</p>
    </div>

    <?php if($errors->any()): ?>
    <div class="alert alert-error" style="max-width:860px;margin:0 auto 24px;">
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg>
        <div>
            <div style="font-weight:600;margin-bottom:4px;">Please fix the following errors:</div>
            <ul style="margin:0;padding-left:16px;">
                <?php $__currentLoopData = $errors->all(); $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $error): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?><li><?php echo e($error); ?></li><?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
            </ul>
        </div>
    </div>
    <?php endif; ?>

    <div style="display:grid;grid-template-columns:1fr 400px;gap:24px;align-items:start;max-width:1060px;margin:0 auto;" x-data="analyzeForm()">

        
        <div class="card" style="padding:24px;">
            <form method="POST" action="<?php echo e(route('portal.analyze')); ?>" id="analyze-form">
                <?php echo csrf_field(); ?>

                
                <div style="margin-bottom:20px;">
                    <label class="form-label">Plot Address or Landmark</label>
                    <div style="display:flex;gap:8px;">
                        <input type="text" name="address" id="address" class="form-input <?php $__errorArgs = ['address'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> is-invalid <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>"
                            value="<?php echo e(old('address')); ?>" placeholder="e.g. 12 Marine Drive, Mumbai, Maharashtra"
                            x-model="address" autocomplete="off" style="flex:1;">
                        <button type="button" class="btn btn-secondary" @click="geocodeAddress()" :disabled="geocoding" style="white-space:nowrap;flex-shrink:0;">
                            <span x-show="!geocoding">📍 Locate</span>
                            <span x-show="geocoding">...</span>
                        </button>
                    </div>
                    <?php $__errorArgs = ['address'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?><div class="invalid-feedback"><?php echo e($message); ?></div><?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                    <div x-show="geocodeMsg" x-transition style="font-size:11px;margin-top:4px;" :style="'color:' + (geocodeOk ? 'var(--green)' : 'var(--red)')">
                        <span x-text="geocodeMsg"></span>
                    </div>
                    <div x-show="!geocodeMsg" style="font-size:11px;color:var(--text-muted);margin-top:4px;">
                        <?php if(!empty($googleMapsApiKey)): ?>
                            Start typing to search Google Places, or place pin on map
                        <?php else: ?>
                            Enter address to auto-detect coordinates, or place pin on map
                        <?php endif; ?>
                    </div>
                </div>

                
                <div style="margin-bottom:20px;">
                    <label class="form-label">Google Maps Location URL (optional)</label>
                    <div style="display:flex;gap:8px;">
                        <input type="text" name="google_maps_url" id="google_maps_url" class="form-input"
                            value="<?php echo e(old('google_maps_url')); ?>" placeholder="Paste any Google Maps link, e.g. https://maps.google.com/..."
                            x-model="googleMapsUrl" style="flex:1;">
                        <button type="button" class="btn btn-secondary" @click="parseGoogleMapsUrl()" :disabled="parsingUrl" style="white-space:nowrap;flex-shrink:0;">
                            <span x-show="!parsingUrl">📍 Extract</span>
                            <span x-show="parsingUrl">...</span>
                        </button>
                    </div>
                    <div x-show="urlMsg" x-transition style="font-size:11px;margin-top:4px;" :style="'color:' + (urlOk ? 'var(--green)' : 'var(--red)')">
                        <span x-text="urlMsg"></span>
                    </div>
                    <div x-show="!urlMsg" style="font-size:11px;color:var(--text-muted);margin-top:4px;">Paste a Google Maps URL to extract exact coordinates (supports all formats: share links, place links, short URLs)</div>
                </div>

                
                <div style="display:grid;grid-template-columns:1fr 1fr;gap:12px;margin-bottom:20px;">
                    <div>
                        <label class="form-label">Latitude</label>
                        <input type="number" name="latitude" id="lat" class="form-input <?php $__errorArgs = ['latitude'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> is-invalid <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>"
                            value="<?php echo e(old('latitude')); ?>" step="0.000001" placeholder="20.5937" x-model="lat">
                        <?php $__errorArgs = ['latitude'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?><div class="invalid-feedback"><?php echo e($message); ?></div><?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                    </div>
                    <div>
                        <label class="form-label">Longitude</label>
                        <input type="number" name="longitude" id="lng" class="form-input <?php $__errorArgs = ['longitude'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> is-invalid <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>"
                            value="<?php echo e(old('longitude')); ?>" step="0.000001" placeholder="78.9629" x-model="lng">
                        <?php $__errorArgs = ['longitude'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?><div class="invalid-feedback"><?php echo e($message); ?></div><?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                    </div>
                </div>

                
                <div style="display:grid;grid-template-columns:1fr 1fr;gap:12px;margin-bottom:20px;">
                    <div>
                        <label class="form-label">State <span style="color:var(--red);">*</span></label>
                        <select name="state_id" id="state_id" class="form-input <?php $__errorArgs = ['state_id'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> is-invalid <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>" required
                            @change="loadCities($event.target.value); loadZones($event.target.value)">
                            <option value="">Select State</option>
                            <?php $__currentLoopData = $states; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $state): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                <option value="<?php echo e($state->id); ?>" <?php echo e(old('state_id') == $state->id ? 'selected' : ''); ?>><?php echo e($state->name); ?></option>
                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                        </select>
                        <?php $__errorArgs = ['state_id'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?><div class="invalid-feedback"><?php echo e($message); ?></div><?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                    </div>
                    <div>
                        <label class="form-label">City (optional)</label>
                        <select name="city_id" id="city_id" class="form-input">
                            <option value="">Auto-detect / Any</option>
                            <?php $__currentLoopData = $cities; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $city): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                <option value="<?php echo e($city->id); ?>" <?php echo e(old('city_id') == $city->id ? 'selected' : ''); ?>><?php echo e($city->name); ?></option>
                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                        </select>
                    </div>
                </div>

                
                <div style="margin-bottom:20px;">
                    <label class="form-label">Zone (optional — auto-detected if blank)</label>
                    <select name="zone_id" id="zone_id" class="form-input" @change="loadZonePreview($event.target.value)">
                        <option value="">Auto-detect from location</option>
                        <?php $__currentLoopData = $zones; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $zone): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                            <option value="<?php echo e($zone->id); ?>" <?php echo e(old('zone_id') == $zone->id ? 'selected' : ''); ?>><?php echo e($zone->name); ?> — <?php echo e($zone->state?->code); ?></option>
                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                    </select>
                </div>

                
                <div x-show="zonePreview" x-transition style="margin-bottom:20px;background:rgba(37,99,235,.08);border:1px solid rgba(37,99,235,.2);border-radius:8px;padding:12px 14px;">
                    <div style="font-size:11px;font-weight:700;color:#93c5fd;text-transform:uppercase;letter-spacing:.06em;margin-bottom:8px;">Zone Quick Preview</div>
                    <div style="display:grid;grid-template-columns:repeat(4,1fr);gap:8px;">
                        <div style="text-align:center;">
                            <div style="font-size:18px;font-weight:700;color:#60a5fa;" x-text="zonePreview?.far_fsi ?? '—'"></div>
                            <div style="font-size:10px;color:var(--text-muted);">FAR / FSI</div>
                        </div>
                        <div style="text-align:center;">
                            <div style="font-size:18px;font-weight:700;color:#a78bfa;" x-text="zonePreview?.max_height_m ? zonePreview.max_height_m+'m' : '—'"></div>
                            <div style="font-size:10px;color:var(--text-muted);">Max Height</div>
                        </div>
                        <div style="text-align:center;">
                            <div style="font-size:18px;font-weight:700;color:#2dd4bf;" x-text="zonePreview?.max_ground_coverage ? (zonePreview.max_ground_coverage*100)+'%' : '—'"></div>
                            <div style="font-size:10px;color:var(--text-muted);">Coverage</div>
                        </div>
                        <div style="text-align:center;">
                            <div style="font-size:13px;font-weight:600;color:#f97316;" x-text="zonePreview?.zone_type ?? '—'"></div>
                            <div style="font-size:10px;color:var(--text-muted);">Zone Type</div>
                        </div>
                    </div>
                    <div style="font-size:10px;color:var(--text-muted);margin-top:6px;" x-text="zonePreview?.regulation_ref ? '📋 '+zonePreview.regulation_ref : ''"></div>
                </div>

                
                <div style="border-top:1px solid var(--border);padding-top:20px;margin-bottom:20px;">
                    <div style="font-size:12px;font-weight:600;color:var(--text-secondary);text-transform:uppercase;letter-spacing:.06em;margin-bottom:16px;">Plot Parameters</div>

                    
                    <div style="margin-bottom:14px;">
                        <label class="form-label">Plot Area <span style="color:var(--red);">*</span></label>
                        <div style="display:grid;grid-template-columns:1fr auto;gap:8px;align-items:end;">
                            <div>
                                <input type="number" name="plot_area_sqm" id="plot_area_sqm" class="form-input <?php $__errorArgs = ['plot_area_sqm'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> is-invalid <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>"
                                    value="<?php echo e(old('plot_area_sqm', request('plot_area'))); ?>" min="10" step="0.01" placeholder="e.g. 500" required
                                    x-model="plotAreaSqm">
                                <?php $__errorArgs = ['plot_area_sqm'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?><div class="invalid-feedback"><?php echo e($message); ?></div><?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                            </div>
                            <span style="font-size:12px;color:var(--text-muted);padding-bottom:10px;">sq.m</span>
                        </div>

                        
                        <div style="margin-top:10px;background:rgba(255,255,255,.03);border:1px solid var(--border);border-radius:8px;padding:12px;">
                            <div style="font-size:11px;font-weight:600;color:var(--text-secondary);margin-bottom:8px;text-transform:uppercase;letter-spacing:.05em;">Unit Converter &rarr; sq.m</div>
                            <div style="display:grid;grid-template-columns:1fr 1fr;gap:8px;">
                                <?php $__currentLoopData = [
                                    ['Guntha', 'guntha', 101.17],
                                    ['Acre', 'acre', 4046.86],
                                    ['Sq.ft', 'sqft', 0.0929],
                                    ['Sq.yd', 'sqyd', 0.8361],
                                    ['Hectare', 'hectare', 10000],
                                    ['Bigha (UP)', 'bigha', 2529.3],
                                ]; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as [$label, $id, $multiplier]): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                <div style="display:flex;gap:6px;align-items:center;">
                                    <input type="number" id="conv_<?php echo e($id); ?>" placeholder="<?php echo e($label); ?>"
                                        class="form-input" style="flex:1;font-size:12px;padding:6px 8px;"
                                        @input="convertUnit($event.target.value, <?php echo e($multiplier); ?>)">
                                    <span style="font-size:11px;color:var(--text-muted);white-space:nowrap;"><?php echo e($label); ?></span>
                                </div>
                                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                            </div>
                            <div style="margin-top:6px;font-size:11px;color:var(--text-muted);">Type a value in any unit to auto-fill sq.m above</div>
                        </div>

                        <div style="margin-top:6px;">
                            <a href="<?php echo e(route('portal.survey.upload', ['report_id' => request('report_id')])); ?>"
                               style="font-size:11px;color:#3b82f6;display:inline-flex;align-items:center;gap:4px;">
                                <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="17 8 12 3 7 8"/><line x1="12" y1="3" x2="12" y2="15"/></svg>
                                Upload PT Survey / Map for auto-fill
                            </a>
                        </div>
                    </div>

                    
                    <div style="display:grid;grid-template-columns:1fr 1fr;gap:12px;">
                        <div>
                            <label class="form-label">Abutting Road Width (m)</label>
                            <input type="number" name="road_width_m" class="form-input" step="0.1" min="0"
                                value="<?php echo e(old('road_width_m')); ?>" placeholder="Auto-detected">
                            <div style="font-size:11px;color:var(--text-muted);margin-top:3px;">Leave blank to auto-detect</div>
                        </div>
                        <div>
                            <label class="form-label">Project Type</label>
                            <select name="project_type" class="form-input">
                                <?php $__currentLoopData = ['residential' => 'Residential', 'commercial' => 'Commercial', 'industrial' => 'Industrial', 'mixed' => 'Mixed Use']; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $val => $lbl): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                <option value="<?php echo e($val); ?>" <?php echo e(old('project_type', 'residential') === $val ? 'selected' : ''); ?>><?php echo e($lbl); ?></option>
                                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                            </select>
                            <div style="font-size:11px;color:var(--text-muted);margin-top:3px;">Affects cost estimates</div>
                        </div>
                    </div>
                </div>

                <button type="submit" class="btn btn-primary btn-lg" style="width:100%;justify-content:center;" id="submit-btn">
                    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>
                    Analyze Feasibility
                </button>
            </form>
        </div>

        
        <div style="display:flex;flex-direction:column;gap:16px;">
            
            <div class="card" style="padding:0;overflow:hidden;">
                <div style="padding:12px 16px;border-bottom:1px solid var(--border);font-size:12px;font-weight:600;color:var(--text-secondary);text-transform:uppercase;letter-spacing:.06em;">
                    Plot Location
                </div>
                <div id="map" style="height:280px;border-radius:0;border:none;"></div>
                <div style="padding:10px 14px;font-size:11px;color:var(--text-muted);">Click on map to set plot location</div>
            </div>

            
            <div class="card" style="padding:18px;">
                <div style="font-size:12px;font-weight:700;color:var(--text);margin-bottom:12px;">How it works</div>
                <?php $__currentLoopData = [
                    ['📍', 'Enter address', 'We geocode it to precise lat/lng'],
                    ['🗺️', 'Zone detection', 'Identify the planning zone & DCR rules'],
                    ['📐', 'FAR calculation', 'Compute max buildable area & floors'],
                    ['💰', 'Cost & ROI', 'Estimate construction cost & development value'],
                    ['✅', 'Score', 'Get a 0-100 feasibility score instantly'],
                ]; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as [$icon, $title, $desc]): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                <div style="display:flex;gap:10px;margin-bottom:10px;align-items:flex-start;">
                    <span style="font-size:16px;flex-shrink:0;margin-top:1px;"><?php echo e($icon); ?></span>
                    <div>
                        <div style="font-size:12px;font-weight:600;color:var(--text);"><?php echo e($title); ?></div>
                        <div style="font-size:11px;color:var(--text-secondary);"><?php echo e($desc); ?></div>
                    </div>
                </div>
                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
            </div>

            
            <div class="card" style="padding:16px;border-color:rgba(167,139,250,.25);">
                <div style="font-size:12px;font-weight:700;color:#a78bfa;margin-bottom:6px;">⚖️ Compare Two Plots</div>
                <div style="font-size:12px;color:var(--text-secondary);margin-bottom:10px;">Run side-by-side feasibility analysis for two different locations and compare all metrics.</div>
                <a href="<?php echo e(route('portal.compare')); ?>" class="btn btn-secondary" style="font-size:12px;width:100%;justify-content:center;">Open Comparison Tool &rarr;</a>
            </div>
        </div>
    </div>
</div>
<?php $__env->stopSection(); ?>

<?php $__env->startSection('scripts'); ?>
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js" crossorigin=""></script>
<?php if(!empty($googleMapsApiKey)): ?>
<script>
function initGooglePlaces() {
    const input = document.getElementById('address');
    if (!input || typeof google === 'undefined') return;
    const autocomplete = new google.maps.places.Autocomplete(input, {
        componentRestrictions: { country: 'in' },
        fields: ['geometry', 'formatted_address', 'address_components', 'name'],
    });
    autocomplete.addListener('place_changed', () => {
        const place = autocomplete.getPlace();
        if (!place.geometry) return;
        const lat = place.geometry.location.lat();
        const lng = place.geometry.location.lng();
        // Update Alpine data
        const el = document.querySelector('[x-data]');
        if (el && el.__x) {
            el.__x.$data.lat = lat.toFixed(6);
            el.__x.$data.lng = lng.toFixed(6);
            el.__x.$data.address = place.formatted_address || place.name || '';
        } else {
            document.getElementById('lat').value = lat.toFixed(6);
            document.getElementById('lng').value = lng.toFixed(6);
            // Dispatch input events so Alpine picks up changes
            document.getElementById('lat').dispatchEvent(new Event('input', { bubbles: true }));
            document.getElementById('lng').dispatchEvent(new Event('input', { bubbles: true }));
            input.value = place.formatted_address || place.name || '';
            input.dispatchEvent(new Event('input', { bubbles: true }));
        }
        if (window._setMapMarker) window._setMapMarker(lat, lng);
    });
    // Prevent form submit on Enter when autocomplete is open
    input.addEventListener('keydown', (e) => {
        if (e.key === 'Enter') {
            const pac = document.querySelector('.pac-container');
            if (pac && pac.style.display !== 'none' && pac.querySelector('.pac-item-selected')) {
                e.preventDefault();
            }
        }
    });
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=<?php echo e($googleMapsApiKey); ?>&libraries=places&callback=initGooglePlaces" async defer></script>
<?php endif; ?>
<script src="https://unpkg.com/alpinejs@3/dist/cdn.min.js" defer></script>
<script>
const BASE_URL = '<?php echo e(url('/')); ?>';

document.addEventListener('DOMContentLoaded', () => {
    const map = L.map('map', { zoomControl: true }).setView([20.5937, 78.9629], 5);
    L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        attribution: '© OpenStreetMap contributors',
        maxZoom: 19
    }).addTo(map);

    let marker = null;
    const latInput = document.getElementById('lat');
    const lngInput = document.getElementById('lng');

    function setMarker(lat, lng) {
        if (marker) map.removeLayer(marker);
        marker = L.marker([lat, lng]).addTo(map);
        map.setView([lat, lng], 16);
        latInput.value = lat.toFixed(6);
        lngInput.value = lng.toFixed(6);
        latInput.dispatchEvent(new Event('input', { bubbles: true }));
        lngInput.dispatchEvent(new Event('input', { bubbles: true }));
    }

    map.on('click', e => setMarker(e.latlng.lat, e.latlng.lng));

    if (latInput.value && lngInput.value) {
        setMarker(parseFloat(latInput.value), parseFloat(lngInput.value));
    }

    window._setMapMarker = setMarker;

    // Fix map tiles when container might have been hidden/resized
    setTimeout(() => map.invalidateSize(), 200);
});

function analyzeForm() {
    return {
        address: '<?php echo e(old('address', '')); ?>',
        googleMapsUrl: '<?php echo e(old('google_maps_url', '')); ?>',
        lat: '<?php echo e(old('latitude', '')); ?>',
        lng: '<?php echo e(old('longitude', '')); ?>',
        plotAreaSqm: '<?php echo e(old('plot_area_sqm', request('plot_area', ''))); ?>',
        geocoding: false,
        geocodeMsg: '',
        geocodeOk: false,
        parsingUrl: false,
        urlMsg: '',
        urlOk: false,
        zonePreview: null,

        convertUnit(value, multiplier) {
            if (!value || isNaN(value)) { this.plotAreaSqm = ''; return; }
            const sqm = parseFloat(value) * multiplier;
            this.plotAreaSqm = Math.round(sqm * 100) / 100;
        },

        /**
         * Extract lat/lng from various Google Maps URL formats:
         * - https://www.google.com/maps/@19.076,72.877,15z
         * - https://www.google.com/maps/place/.../@19.076,72.877,15z
         * - https://www.google.com/maps?q=19.076,72.877
         * - https://maps.google.com/?ll=19.076,72.877
         * - https://goo.gl/maps/xxxxx (short URL — resolved via redirect)
         * - https://maps.app.goo.gl/xxxxx
         * - https://www.google.com/maps/place/...!3d19.076!4d72.877...
         * - Plain coordinates: 19.076, 72.877
         */
        extractCoordsFromUrl(url) {
            if (!url) return null;
            url = url.trim();

            // Plain coordinates: "19.076, 72.877" or "19.076,72.877"
            const plainMatch = url.match(/^(-?\d+\.?\d*)\s*,\s*(-?\d+\.?\d*)$/);
            if (plainMatch) {
                return { lat: parseFloat(plainMatch[1]), lng: parseFloat(plainMatch[2]) };
            }

            // @lat,lng pattern (most common desktop URL)
            const atMatch = url.match(/@(-?\d+\.?\d+),(-?\d+\.?\d+)/);
            if (atMatch) {
                return { lat: parseFloat(atMatch[1]), lng: parseFloat(atMatch[2]) };
            }

            // ?q=lat,lng or &q=lat,lng
            const qMatch = url.match(/[?&]q=(-?\d+\.?\d+),(-?\d+\.?\d+)/);
            if (qMatch) {
                return { lat: parseFloat(qMatch[1]), lng: parseFloat(qMatch[2]) };
            }

            // ?ll=lat,lng
            const llMatch = url.match(/[?&]ll=(-?\d+\.?\d+),(-?\d+\.?\d+)/);
            if (llMatch) {
                return { lat: parseFloat(llMatch[1]), lng: parseFloat(llMatch[2]) };
            }

            // !3d(lat)!4d(lng) pattern (embed/place URLs)
            const dMatch = url.match(/!3d(-?\d+\.?\d+)!4d(-?\d+\.?\d+)/);
            if (dMatch) {
                return { lat: parseFloat(dMatch[1]), lng: parseFloat(dMatch[2]) };
            }

            // ftid or data with 2f pattern
            const fMatch = url.match(/\/(-?\d+\.?\d+),(-?\d+\.?\d+)/);
            if (fMatch) {
                const lat = parseFloat(fMatch[1]);
                const lng = parseFloat(fMatch[2]);
                if (lat >= -90 && lat <= 90 && lng >= -180 && lng <= 180) {
                    return { lat, lng };
                }
            }

            return null;
        },

        async parseGoogleMapsUrl() {
            const url = this.googleMapsUrl?.trim();
            if (!url) { this.urlMsg = 'Please paste a Google Maps URL first.'; this.urlOk = false; return; }
            this.parsingUrl = true;
            this.urlMsg = '';

            // Try to extract coordinates directly from the URL
            let coords = this.extractCoordsFromUrl(url);

            // If it's a short URL (goo.gl, maps.app.goo.gl), resolve it via server
            if (!coords && (url.includes('goo.gl') || url.includes('maps.app'))) {
                try {
                    const res = await fetch(BASE_URL + '/ajax/resolve-map-url?url=' + encodeURIComponent(url), {
                        headers: { 'Accept': 'application/json', 'X-Requested-With': 'XMLHttpRequest' }
                    });
                    if (res.ok) {
                        const data = await res.json();
                        if (data.resolved_url) coords = this.extractCoordsFromUrl(data.resolved_url);
                        if (!coords && data.lat && data.lng) coords = { lat: data.lat, lng: data.lng };
                    }
                } catch (e) { console.error('Resolve URL error:', e); }
            }

            if (coords && coords.lat >= -90 && coords.lat <= 90 && coords.lng >= -180 && coords.lng <= 180) {
                this.lat = coords.lat.toFixed(6);
                this.lng = coords.lng.toFixed(6);
                if (window._setMapMarker) window._setMapMarker(coords.lat, coords.lng);
                this.urlMsg = '✓ Coordinates extracted: ' + coords.lat.toFixed(6) + ', ' + coords.lng.toFixed(6);
                this.urlOk = true;

                // Reverse-geocode to get address and auto-fill dropdowns
                try {
                    const res = await fetch(BASE_URL + '/ajax/geocode?address=' + encodeURIComponent(coords.lat + ',' + coords.lng), {
                        headers: { 'Accept': 'application/json', 'X-Requested-With': 'XMLHttpRequest' }
                    });
                    if (res.ok) {
                        const data = await res.json();
                        if (data.display && !this.address) this.address = data.display;
                        this.autoFillDropdowns(data);
                    }
                } catch (e) { /* ok — coords already extracted */ }
            } else {
                this.urlMsg = 'Could not extract coordinates from this URL. Please check the format and try again.';
                this.urlOk = false;
            }
            this.parsingUrl = false;
        },

        autoFillDropdowns(data) {
            // Auto-select State
            if (data.state_id) {
                const stateSel = document.getElementById('state_id');
                stateSel.value = data.state_id;
                stateSel.dispatchEvent(new Event('change', { bubbles: true }));
            }

            // Populate Cities dropdown and auto-select
            if (data.cities && data.cities.length) {
                const citySel = document.getElementById('city_id');
                citySel.innerHTML = '<option value="">Auto-detect / Any</option>';
                data.cities.forEach(c => citySel.innerHTML += `<option value="${c.id}">${c.name}</option>`);
                if (data.city_id) citySel.value = data.city_id;
            }

            // Populate Zones dropdown
            if (data.zones && data.zones.length) {
                const zoneSel = document.getElementById('zone_id');
                zoneSel.innerHTML = '<option value="">Auto-detect from location</option>';
                data.zones.forEach(z => zoneSel.innerHTML += `<option value="${z.id}">${z.name}</option>`);
            }
        },

        async geocodeAddress() {
            if (!this.address.trim()) { this.geocodeMsg = 'Please enter an address first.'; this.geocodeOk = false; return; }
            this.geocoding = true;
            this.geocodeMsg = '';
            try {
                const res = await fetch(BASE_URL + '/ajax/geocode?address=' + encodeURIComponent(this.address), {
                    headers: { 'Accept': 'application/json', 'X-Requested-With': 'XMLHttpRequest' }
                });
                if (!res.ok) throw new Error('Server returned ' + res.status);
                const data = await res.json();
                const lat = data.latitude ?? data.lat;
                const lng = data.longitude ?? data.lng;
                if (lat && lng) {
                    this.lat = parseFloat(lat).toFixed(6);
                    this.lng = parseFloat(lng).toFixed(6);
                    if (window._setMapMarker) window._setMapMarker(parseFloat(lat), parseFloat(lng));
                    this.geocodeMsg = '✓ Located: ' + (data.display || this.address);
                    this.geocodeOk = true;
                    this.autoFillDropdowns(data);
                } else {
                    this.geocodeMsg = 'Could not find coordinates for this address. Try a more specific location.';
                    this.geocodeOk = false;
                }
            } catch(e) {
                console.error('Geocode error:', e);
                this.geocodeMsg = 'Geocoding failed. Please enter coordinates manually or place pin on map.';
                this.geocodeOk = false;
            }
            this.geocoding = false;
        },

        async loadCities(stateId) {
            const sel = document.getElementById('city_id');
            sel.innerHTML = '<option value="">Loading...</option>';
            if (!stateId) { sel.innerHTML = '<option value="">Auto-detect / Any</option>'; return; }
            const res = await fetch(BASE_URL + '/ajax/cities/' + stateId);
            const cities = await res.json();
            sel.innerHTML = '<option value="">Auto-detect / Any</option>';
            cities.forEach(c => sel.innerHTML += `<option value="${c.id}">${c.name}</option>`);
        },

        async loadZones(stateId) {
            const sel = document.getElementById('zone_id');
            if (!stateId) return;
            const res = await fetch(BASE_URL + '/ajax/zones/' + stateId);
            const zones = await res.json();
            sel.innerHTML = '<option value="">Auto-detect from location</option>';
            zones.forEach(z => sel.innerHTML += `<option value="${z.id}">${z.name}</option>`);
            this.zonePreview = null;
        },

        async loadZonePreview(zoneId) {
            if (!zoneId) { this.zonePreview = null; return; }
            try {
                const res = await fetch(BASE_URL + '/ajax/zone-preview/' + zoneId);
                this.zonePreview = await res.json();
            } catch(e) { this.zonePreview = null; }
        }
    }
}
</script>
<?php $__env->stopSection(); ?>

<?php echo $__env->make('portal.layout', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH C:\xampp_lite_8_4\www\landfeasibility\resources\views/portal/analyze.blade.php ENDPATH**/ ?>