@extends('backEnd.layouts.master')
@section('title', 'Local Delivery Management')

@section('css')
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" />
<style>
    .local-delivery-map {
        height: 450px;
        border-radius: 12px;
        border: 2px solid #e2e8f0;
        box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.05);
    }
    .premium-card {
        border: none;
        border-radius: 14px;
        box-shadow: 0 10px 30px rgba(0,0,0,0.03);
        background: #ffffff;
        margin-bottom: 24px;
    }
    .card-header-premium {
        background: #f8fafc;
        border-bottom: 1px solid #f1f5f9;
        padding: 20px 24px;
        border-top-left-radius: 14px !important;
        border-top-right-radius: 14px !important;
    }
    .card-title-premium {
        font-size: 18px;
        font-weight: 700;
        color: #1e293b;
        margin: 0;
        display: flex;
        align-items: center;
        gap: 10px;
    }
    .btn-premium {
        background: linear-gradient(135deg, #FF9900 0%, #FF5E00 100%);
        border: none;
        color: #fff;
        font-weight: 600;
        padding: 10px 22px;
        border-radius: 8px;
        transition: 0.2s;
    }
    .btn-premium:hover {
        transform: translateY(-2px);
        box-shadow: 0 8px 20px rgba(255, 94, 0, 0.2);
        color: #fff;
    }
    .toggle-switch {
        position: relative;
        display: inline-block;
        width: 50px;
        height: 26px;
    }
    .toggle-switch input {
        opacity: 0;
        width: 0;
        height: 0;
    }
    .slider-toggle {
        position: absolute;
        cursor: pointer;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background-color: #cbd5e1;
        transition: .4s;
        border-radius: 34px;
    }
    .slider-toggle:before {
        position: absolute;
        content: "";
        height: 18px;
        width: 18px;
        left: 4px;
        bottom: 4px;
        background-color: white;
        transition: .4s;
        border-radius: 50%;
    }
    input:checked + .slider-toggle {
        background-color: #10b981;
    }
    input:checked + .slider-toggle:before {
        transform: translateX(24px);
    }
    .zone-circle-badge {
        width: 16px;
        height: 16px;
        border-radius: 50%;
        display: inline-block;
        background: rgba(255, 94, 0, 0.6);
        border: 2px solid #FF5E00;
    }
</style>
@endsection

@section('content')
<div class="container-fluid">
    <!-- Page Title -->
    <div class="row mb-4">
        <div class="col-12 d-flex justify-content-between align-items-center">
            <div>
                <h4 class="page-title fw-bold text-dark mb-0">Local Delivery Management</h4>
                <p class="text-muted mb-0">Define delivery areas, sub-locations, boundaries, and automate charges.</p>
            </div>
            
            <!-- Global Enable/Disable Toggle -->
            <div class="d-flex align-items-center gap-3 bg-white p-3 rounded-3 shadow-sm border border-light">
                <span class="fw-bold text-dark" id="toggle-label">
                    {{ ($setting->local_delivery_enabled ?? 0) == 1 ? 'Local Delivery Active' : 'Local Delivery Inactive' }}
                </span>
                <label class="toggle-switch">
                    <input type="checkbox" id="global-toggle" {{ ($setting->local_delivery_enabled ?? 0) == 1 ? 'checked' : '' }} onchange="toggleLocalDelivery(this)">
                    <span class="slider-toggle"></span>
                </label>
            </div>
        </div>
    </div>

    <div class="row">
        <!-- Interactive Boundary Map Selector -->
        <div class="col-lg-8">
            <div class="card premium-card">
                <div class="card-header-premium">
                    <h5 class="card-title-premium">
                        <i class="fe-map-pin text-danger"></i> Interactive Delivery Zone Picker
                    </h5>
                </div>
                <div class="card-body">
                    <p class="text-muted small">Click anywhere on the map to define the center coordinate of your delivery zone. Fill in the parameters on the right to complete setup.</p>
                    <div id="zone-picker-map" class="local-delivery-map"></div>
                </div>
            </div>
        </div>

        <!-- Add Zone Parameters Form -->
        <div class="col-lg-4">
            <div class="card premium-card">
                <div class="card-header-premium">
                    <h5 class="card-title-premium">
                        <i class="fe-plus-circle text-primary"></i> Create Delivery Zone
                    </h5>
                </div>
                <div class="card-body">
                    <form action="{{ route('admin.local-delivery.zone.store') }}" method="POST" id="zone-form">
                        @csrf
                        <div class="mb-3">
                            <label class="form-label fw-semibold text-dark">Zone Name</label>
                            <input type="text" name="name" class="form-control" placeholder="e.g. Dhaka Central, Banani Area" required>
                        </div>
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label fw-semibold text-dark">Latitude</label>
                                <input type="number" step="any" name="lat" id="zone-lat" class="form-control" placeholder="e.g. 23.8103" required oninput="updateCirclePreview()">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label fw-semibold text-dark">Longitude</label>
                                <input type="number" step="any" name="lng" id="zone-lng" class="form-control" placeholder="e.g. 90.4125" required oninput="updateCirclePreview()">
                            </div>
                        </div>
                        <div class="mb-3">
                            <label class="form-label fw-semibold text-dark">Boundary Radius (km)</label>
                            <div class="input-group">
                                <input type="number" step="0.01" name="radius" id="zone-radius" class="form-control" placeholder="e.g. 3.0" min="0.1" required oninput="updateCirclePreview()">
                                <span class="input-group-text bg-light">km</span>
                            </div>
                        </div>
                        <div class="mb-4">
                            <label class="form-label fw-semibold text-dark">Base Delivery Charge (Tk)</label>
                            <div class="input-group">
                                <span class="input-group-text bg-light">à§³</span>
                                <input type="number" name="delivery_charge" class="form-control" placeholder="e.g. 60" min="0" required>
                            </div>
                        </div>

                        <button type="submit" class="btn btn-premium w-100 shadow-sm" id="btn-save-zone" disabled>
                            <i class="fe-check me-1"></i> Save Delivery Zone
                        </button>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <div class="row">
        <!-- Active Zones List -->
        <div class="col-lg-6">
            <div class="card premium-card">
                <div class="card-header-premium">
                    <h5 class="card-title-premium">
                        <i class="fe-grid text-warning"></i> Active Zones List
                    </h5>
                </div>
                <div class="card-body p-0">
                    <div class="table-responsive">
                        <table class="table table-hover align-middle mb-0">
                            <thead class="bg-light">
                                <tr>
                                    <th class="ps-4">Zone Details</th>
                                    <th>Boundary (Radius)</th>
                                    <th>Base Charge</th>
                                    <th class="text-end pe-4">Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                @forelse($zones as $zone)
                                <tr>
                                    <td class="ps-4">
                                        <div class="d-flex align-items-center gap-2">
                                            <div class="zone-circle-badge"></div>
                                            <div>
                                                <span class="fw-bold text-dark">{{ $zone->name }}</span>
                                                <code class="d-block small text-muted">{{ round($zone->lat, 4) }}, {{ round($zone->lng, 4) }}</code>
                                            </div>
                                        </div>
                                    </td>
                                    <td>
                                        <span class="badge bg-soft-primary text-primary px-2 py-1 rounded-pill">{{ $zone->radius }} km</span>
                                    </td>
                                    <td class="fw-bold text-dark">à§³{{ number_format($zone->delivery_charge) }}</td>
                                    <td class="text-end pe-4">
                                        <div class="d-inline-flex gap-2">
                                            <button class="btn btn-sm btn-outline-info rounded-pill" onclick="locateZone({{ $zone->lat }}, {{ $zone->lng }}, {{ $zone->radius }})">
                                                <i class="fe-map-pin"></i> Locate
                                            </button>
                                            <form action="{{ route('admin.local-delivery.zone.destroy', $zone->id) }}" method="POST" onsubmit="return confirm('Are you sure you want to delete this zone and all its sub-locations?');">
                                                @csrf
                                                @method('DELETE')
                                                <button type="submit" class="btn btn-sm btn-outline-danger rounded-pill">
                                                    <i class="fe-trash"></i>
                                                </button>
                                            </form>
                                        </div>
                                    </td>
                                </tr>
                                @empty
                                <tr>
                                    <td colspan="4" class="text-center py-4 text-muted">No delivery zones configured yet. Pinpoint one on the map above!</td>
                                </tr>
                                @endforelse
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>

        <!-- Add Sub-location Points Form & Active Sub-locations List -->
        <div class="col-lg-6">
            <!-- Add Sub-location -->
            <div class="card premium-card">
                <div class="card-header-premium">
                    <h5 class="card-title-premium">
                        <i class="fe-map text-success"></i> Add Manual Sub-location (Point)
                    </h5>
                </div>
                <div class="card-body">
                    <form action="{{ route('admin.local-delivery.point.store') }}" method="POST" class="row g-3">
                        @csrf
                        <div class="col-md-6">
                            <label class="form-label fw-semibold text-dark">Select Parent Zone</label>
                            <select name="zone_id" class="form-select select2" required>
                                <option value="">-- Choose Zone --</option>
                                @foreach($zones as $z)
                                <option value="{{ $z->id }}">{{ $z->name }} (Base: à§³{{ $z->delivery_charge }})</option>
                                @endforeach
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label fw-semibold text-dark">Sub-location/Point Name</label>
                            <input type="text" name="name" class="form-control" placeholder="e.g. Sector 4, Banani Road 11" required>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label fw-semibold text-dark">Extra Delivery Charge (Tk)</label>
                            <div class="input-group">
                                <span class="input-group-text bg-light">à§³</span>
                                <input type="number" name="extra_charge" class="form-control" placeholder="e.g. 15" min="0" required>
                            </div>
                        </div>
                        <div class="col-md-6 d-flex align-items-end">
                            <button type="submit" class="btn btn-premium w-100 shadow-sm">
                                <i class="fe-plus me-1"></i> Add Sub-location Point
                            </button>
                        </div>
                    </form>
                </div>
            </div>

            <!-- Active Sub-locations Table -->
            <div class="card premium-card">
                <div class="card-header-premium">
                    <h5 class="card-title-premium">
                        <i class="fe-align-left text-info"></i> Configured Sub-locations
                    </h5>
                </div>
                <div class="card-body p-0">
                    <div class="table-responsive" style="max-height: 250px;">
                        <table class="table table-hover align-middle mb-0">
                            <thead class="bg-light">
                                <tr>
                                    <th class="ps-4">Sub-location Point</th>
                                    <th>Parent Zone</th>
                                    <th>Extra Fee</th>
                                    <th class="text-end pe-4">Action</th>
                                </tr>
                            </thead>
                            <tbody>
                                @forelse($points as $pt)
                                <tr>
                                    <td class="ps-4">
                                        <span class="fw-bold text-dark">{{ $pt->name }}</span>
                                    </td>
                                    <td>
                                        <span class="badge bg-soft-warning text-warning">{{ $pt->zone->name ?? 'None' }}</span>
                                    </td>
                                    <td class="fw-bold text-dark">+ à§³{{ number_format($pt->extra_charge) }}</td>
                                    <td class="text-end pe-4">
                                        <form action="{{ route('admin.local-delivery.point.destroy', $pt->id) }}" method="POST" onsubmit="return confirm('Remove this point?');">
                                            @csrf
                                            @method('DELETE')
                                            <button type="submit" class="btn btn-sm btn-outline-danger rounded-pill">
                                                <i class="fe-trash-2"></i>
                                            </button>
                                        </form>
                                    </td>
                                </tr>
                                @empty
                                <tr>
                                    <td colspan="4" class="text-center py-4 text-muted">No manual sub-locations configured. Add one above!</td>
                                </tr>
                                @endforelse
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="row mt-4">
        <div class="col-lg-6">
            <div class="card premium-card">
                <div class="card-body">
                    <label class="form-label fw-bold">Default platform commission (%)</label>
                    <div class="input-group">
                        <input type="number" step="0.01" id="default-commission" class="form-control" value="{{ $setting->default_rider_commission_percent ?? 10 }}">
                        <button type="button" class="btn btn-dark" onclick="saveDefaultCommission()">Save</button>
                    </div>
                    <p class="text-muted small mt-2 mb-0">Collect rider payments in <a href="{{ route('admin.rider-revenue.index') }}">Rider Revenue Collection</a>.</p>
                </div>
            </div>
        </div>
        <div class="col-lg-6">
            <div class="card premium-card">
                <div class="card-body">
                    <label class="form-label fw-bold">Auto-cancel if no rider accepts (minutes)</label>
                    <div class="input-group">
                        <input type="number" min="5" max="1440" id="cancel-minutes" class="form-control" value="{{ $setting->local_delivery_unassigned_cancel_minutes ?? 45 }}">
                        <button type="button" class="btn btn-dark" onclick="saveCancelMinutes()">Save</button>
                    </div>
                    <p class="text-muted small mt-2 mb-0">Order is cancelled automatically when no rider takes it within this time.</p>
                </div>
            </div>
        </div>
    </div>

</div>
@endsection

@section('script')
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
<script>
    let map, clickMarker, circlePreview, radiusMarker;
    const defaultLat = 23.8103;
    const defaultLng = 90.4125;

    document.addEventListener("DOMContentLoaded", function() {
        map = L.map('zone-picker-map').setView([defaultLat, defaultLng], 12);
        L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
            attribution: '&copy; OpenStreetMap'
        }).addTo(map);

        const existingZones = @json($zones);
        existingZones.forEach(zone => {
            L.circle([zone.lat, zone.lng], {
                color: '#FF5E00',
                fillColor: '#FF9900',
                fillOpacity: 0.2,
                radius: zone.radius * 1000
            }).addTo(map)
            .bindPopup(`<strong>${zone.name}</strong><br>Radius: ${zone.radius} km`);
        });

        map.on('click', function(e) {
            document.getElementById('zone-lat').value = e.latlng.lat.toFixed(6);
            document.getElementById('zone-lng').value = e.latlng.lng.toFixed(6);
            let radiusInput = document.getElementById('zone-radius');
            if (!radiusInput.value || parseFloat(radiusInput.value) <= 0) {
                radiusInput.value = "3.00";
            }
            document.getElementById('btn-save-zone').removeAttribute('disabled');
            updateCirclePreview();
        });
    });

    // Helper to calculate latlng at a specific distance (eastward) for the radius drag handle
    function getRadiusMarkerLatLng(centerLat, centerLng, radiusKm) {
        const deltaLng = radiusKm / (111.320 * Math.cos(centerLat * Math.PI / 180));
        return L.latLng(centerLat, centerLng + deltaLng);
    }

    // Creates or updates the interactive zone preview (center marker + circle + resizer handle)
    function createOrUpdateZonePreview(lat, lng, radiusKm) {
        const centerLatLng = L.latLng(lat, lng);
        const radiusLatLng = getRadiusMarkerLatLng(lat, lng, radiusKm);

        // 1. Center Marker (Draggable Red Pin)
        if (clickMarker) {
            clickMarker.setLatLng(centerLatLng);
        } else {
            const redIcon = L.icon({
                iconUrl: 'https://raw.githubusercontent.com/pointhi/leaflet-color-markers/master/img/marker-icon-2x-red.png',
                shadowUrl: 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.7/images/marker-shadow.png',
                iconSize: [25, 41],
                iconAnchor: [12, 41],
                popupAnchor: [1, -34],
                shadowSize: [41, 41]
            });

            clickMarker = L.marker(centerLatLng, { 
                draggable: true, 
                icon: redIcon 
            }).addTo(map);

            clickMarker.on('drag', function(event) {
                const newCenter = event.target.getLatLng();
                document.getElementById('zone-lat').value = newCenter.lat.toFixed(6);
                document.getElementById('zone-lng').value = newCenter.lng.toFixed(6);
                
                const rKm = parseFloat(document.getElementById('zone-radius').value) || 3.00;
                
                if (circlePreview) {
                    circlePreview.setLatLng(newCenter);
                }
                if (radiusMarker) {
                    radiusMarker.setLatLng(getRadiusMarkerLatLng(newCenter.lat, newCenter.lng, rKm));
                }
            });
        }

        // 2. Boundary Circle
        if (circlePreview) {
            circlePreview.setLatLng(centerLatLng);
            circlePreview.setRadius(radiusKm * 1000);
        } else {
            circlePreview = L.circle(centerLatLng, {
                color: '#0d6efd',
                fillColor: '#3b82f6',
                fillOpacity: 0.15,
                radius: radiusKm * 1000
            }).addTo(map);
        }

        // 3. Resizer Handle (Draggable Gold Pin on Circle Boundary)
        if (radiusMarker) {
            radiusMarker.setLatLng(radiusLatLng);
        } else {
            const goldIcon = L.icon({
                iconUrl: 'https://raw.githubusercontent.com/pointhi/leaflet-color-markers/master/img/marker-icon-2x-gold.png',
                shadowUrl: 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.7/images/marker-shadow.png',
                iconSize: [20, 32],
                iconAnchor: [10, 32],
                shadowSize: [30, 30]
            });

            radiusMarker = L.marker(radiusLatLng, { 
                draggable: true, 
                icon: goldIcon 
            }).addTo(map);

            radiusMarker.on('drag', function(event) {
                const center = clickMarker.getLatLng();
                const currentLatLng = event.target.getLatLng();
                
                const distanceMeters = center.distanceTo(currentLatLng);
                const newRadiusKm = distanceMeters / 1000;
                const clampedRadiusKm = Math.max(0.1, newRadiusKm); // minimum 100m
                
                document.getElementById('zone-radius').value = clampedRadiusKm.toFixed(2);
                
                if (circlePreview) {
                    circlePreview.setRadius(clampedRadiusKm * 1000);
                }
            });
        }
    }

    // Triggered when form input elements (lat, lng, radius) are modified
    function updateCirclePreview() {
        const lat = parseFloat(document.getElementById('zone-lat').value);
        const lng = parseFloat(document.getElementById('zone-lng').value);
        const radius = parseFloat(document.getElementById('zone-radius').value);

        if (isNaN(lat) || isNaN(lng)) return;

        document.getElementById('btn-save-zone').removeAttribute('disabled');

        const radiusKm = isNaN(radius) || radius <= 0 ? 3.00 : radius;
        createOrUpdateZonePreview(lat, lng, radiusKm);
    }

    // Locate active zone on map
    function locateZone(lat, lng, radius) {
        map.flyTo([lat, lng], 14, { duration: 1.5 });
        L.circle([lat, lng], {
            color: '#10b981',
            fillColor: '#10b981',
            fillOpacity: 0.35,
            radius: radius * 1000
        }).addTo(map)
        .bindPopup('Target Zone Focused!')
        .openPopup();
    }

    // Toggle global delivery setting via AJAX
    function toggleLocalDelivery(checkbox) {
        const enabled = checkbox.checked ? 1 : 0;
        const label = document.getElementById('toggle-label');

        label.innerHTML = '<i class="fe-loader spinner"></i> Updating...';

        fetch("{{ route('admin.local-delivery.toggle-setting') }}", {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': '{{ csrf_token() }}'
            },
            body: JSON.stringify({ enabled: enabled })
        })
        .then(res => res.json())
        .then(data => {
            if (data.success) {
                label.innerText = enabled ? 'Local Delivery Active' : 'Local Delivery Inactive';
                toastr.success(data.message, 'Setting Saved!');
            } else {
                checkbox.checked = !checkbox.checked;
                label.innerText = !enabled ? 'Local Delivery Active' : 'Local Delivery Inactive';
                toastr.error('Failed to update setting.', 'Error');
            }
        })
        .catch(() => {
            checkbox.checked = !checkbox.checked;
            label.innerText = !enabled ? 'Local Delivery Active' : 'Local Delivery Inactive';
            toastr.error('Connection error.', 'Error');
        });
    }

    function saveDefaultCommission() {
        const val = document.getElementById('default-commission').value;
        fetch("{{ route('admin.local-delivery.commission-default') }}", {
            method: 'POST',
            headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': '{{ csrf_token() }}' },
            body: JSON.stringify({ default_rider_commission_percent: val })
        }).then(r => r.json()).then(d => {
            if (d.success) toastr.success(d.message); else toastr.error('Failed');
        });
    }

    function saveCancelMinutes() {
        const val = document.getElementById('cancel-minutes').value;
        fetch("{{ route('admin.local-delivery.cancel-minutes') }}", {
            method: 'POST',
            headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': '{{ csrf_token() }}' },
            body: JSON.stringify({ local_delivery_unassigned_cancel_minutes: val })
        }).then(r => r.json()).then(d => {
            if (d.success) toastr.success(d.message); else toastr.error('Failed');
        });
    }
</script>
@endsection
