@extends('admin.layouts.app')

@section('title', 'Province Details')

@section('content')
<div class="container-fluid">
    <div class="card">
        <div class="card-header">
            <div class="d-flex justify-content-between align-items-center">
                <h4>Province Details</h4>
                <div>
                    <a href="{{ route('admin.geography.provinces.edit', $item->id) }}" class="btn btn-primary">
                        <i class="fas fa-edit"></i> Edit
                    </a>
                    <a href="{{ route('admin.geography.provinces.fix-boundaries', $item->id) }}" class="btn btn-warning" 
                        onclick="return confirm('This will replace any corrupted boundary data with a simple default polygon. Continue?');">
                        <i class="fas fa-tools"></i> Fix Boundaries
                    </a>
                    <a href="{{ route('admin.geography.provinces.index') }}" class="btn btn-secondary">
                        <i class="fas fa-list"></i> Back to Provinces
                    </a>
                </div>
            </div>
        </div>
        <div class="card-body">
            <div class="row">
                <div class="col-md-6">
                    <table class="table table-bordered">
                        <tr>
                            <th style="width: 30%">Province ID</th>
                            <td>{{ $item->id }}</td>
                        </tr>
                        <tr>
                            <th>Name</th>
                            <td>{{ $item->name }}</td>
                        </tr>
                        <tr>
                            <th>English Name</th>
                            <td>{{ $item->name_en ?? 'N/A' }}</td>
                        </tr>
                        <tr>
                            <th>Country</th>
                            <td>
                                <a href="{{ route('admin.geography.countries.show', $item->country_id) }}">
                                    {{ $item->country->name ?? 'N/A' }}
                                </a>
                            </td>
                        </tr>
                        <tr>
                            <th>Slug</th>
                            <td><code>{{ $item->slug }}</code></td>
                        </tr>
                        <tr>
                            <th>Global Slug</th>
                            <td><code>{{ $item->global_slug ?? 'N/A' }}</code></td>
                        </tr>
                    </table>
                </div>
                <div class="col-md-6">
                    <table class="table table-bordered">
                        <tr>
                            <th style="width: 30%">Center City</th>
                            <td>{{ $item->center_city_name ?? 'N/A' }}</td>
                        </tr>
                        <tr>
                            <th>Area</th>
                            <td>{{ isset($item->area) ? number_format($item->area, 2) . ' km²' : 'N/A' }}</td>
                        </tr>
                        <tr>
                            <th>Population</th>
                            <td>{{ isset($item->population) ? number_format($item->population) : 'N/A' }}</td>
                        </tr>
                        <tr>
                            <th>Code</th>
                            <td>{{ $item->code ?? 'N/A' }}</td>
                        </tr>
                        <tr>
                            <th>Status</th>
                            <td>
                                <span class="badge {{ $item->is_active ? 'bg-success' : 'bg-danger' }}">
                                    {{ $item->is_active ? 'Active' : 'Inactive' }}
                                </span>
                            </td>
                        </tr>
                        <tr>
                            <th>Created At</th>
                            <td>{{ $item->created_at ? $item->created_at->format('Y-m-d H:i:s') : 'N/A' }}</td>
                        </tr>
                        <tr>
                            <th>Updated At</th>
                            <td>{{ $item->updated_at ? $item->updated_at->format('Y-m-d H:i:s') : 'N/A' }}</td>
                        </tr>
                    </table>
                </div>
            </div>

            @if($item->description)
            <div class="row mt-4">
                <div class="col-md-12">
                    <div class="card">
                        <div class="card-header">
                            <h5>Description</h5>
                        </div>
                        <div class="card-body">
                            {{ $item->description }}
                        </div>
                    </div>
                </div>
            </div>
            @endif

            {{-- Map section if boundaries data exists --}}
            <div class="row mt-4">
                <div class="col-md-12">
                    <div class="card">
                        <div class="card-header">
                            <h5>Geographic Boundaries</h5>
                        </div>
                        <div class="card-body">
                            @php
                                // Debug information
                                $rawBoundaries = $item->getAttributes()['boundaries'] ?? 'Not in attributes';
                                $processedBoundaries = $item->boundaries;
                                $isNull = is_null($processedBoundaries) ? 'true' : 'false';
                                $isEmpty = empty($processedBoundaries) ? 'true' : 'false';
                                $length = is_string($processedBoundaries) ? strlen($processedBoundaries) : 'N/A';
                            @endphp
                            
                            <div class="alert alert-info mb-3">
                                <strong>Debug Info:</strong><br>
                                Raw value exists: {{ isset($item->getAttributes()['boundaries']) ? 'Yes' : 'No' }}<br>
                                Raw length: {{ is_string($rawBoundaries) ? strlen($rawBoundaries) : 'N/A' }}<br>
                                After accessor - Is null: {{ $isNull }}<br>
                                After accessor - Is empty: {{ $isEmpty }}<br>
                                After accessor - Length: {{ $length }}
                            </div>
                            
                            @if(isset($item->boundaries) && $item->boundaries !== null)
                            <div id="provinceMap" style="height: 400px; width: 100%;"></div>
                            
                            <div class="mt-3">
                                <button class="btn btn-sm btn-secondary" id="show-raw-data">Show Raw GeoJSON Data</button>
                                <div id="raw-geojson" class="mt-2" style="display: none;">
                                    <textarea class="form-control" readonly rows="5">{{ $item->boundaries }}</textarea>
                                </div>
                            </div>
                            @else
                            <div class="alert alert-warning">
                                <i class="fas fa-exclamation-triangle"></i> No boundary data available for this province. Please edit the province to add GeoJSON boundary data.
                            </div>
                            @endif
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="card mt-4">
        <div class="card-header">
            <div class="d-flex justify-content-between align-items-center">
                <h5>Counties</h5>
                <a href="{{ route('admin.geography.counties.create') }}" class="btn btn-sm btn-primary">
                    <i class="fas fa-plus"></i> Add County
                </a>
            </div>
        </div>
        <div class="card-body">
            @if(isset($counties) && $counties->count() > 0)
                <div class="table-responsive">
                    <table class="table table-bordered">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>Name</th>
                                <th>English Name</th>
                                <th>Center City</th>
                                <th>Status</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            @foreach($counties as $county)
                            <tr>
                                <td>{{ $county->id }}</td>
                                <td>{{ $county->name }}</td>
                                <td>{{ $county->name_en ?? 'N/A' }}</td>
                                <td>{{ $county->center_city_name ?? 'N/A' }}</td>
                                <td>
                                    <span class="badge {{ $county->is_active ? 'bg-success' : 'bg-danger' }}">
                                        {{ $county->is_active ? 'Active' : 'Inactive' }}
                                    </span>
                                </td>
                                <td>
                                    <div class="btn-group btn-group-sm">
                                        <a href="{{ route('admin.geography.counties.show', $county->id) }}" class="btn btn-info">
                                            <i class="fas fa-eye"></i>
                                        </a>
                                        <a href="{{ route('admin.geography.counties.edit', $county->id) }}" class="btn btn-primary">
                                            <i class="fas fa-edit"></i>
                                        </a>
                                    </div>
                                </td>
                            </tr>
                            @endforeach
                        </tbody>
                    </table>
                </div>
            @else
                <p class="text-muted">No counties found for this province.</p>
            @endif
        </div>
    </div>
</div>
@endsection

@section('scripts')
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" />
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
    console.log('Map initialization script started');
    
    // Function to sanitize JSON string
    function sanitizeJson(str) {
        if (!str) {
            console.log('Empty string passed to sanitizeJson');
            return null;
        }
        
        console.log('Sanitizing string of length: ' + str.length);
        
        // Check if the string contains binary data (indicated by question marks and unprintable chars)
        const hasBinaryData = /[\x00-\x08\x0B-\x0C\x0E-\x1F\x7F]|(\?\?\?)|(\?~\?)/.test(str);
        
        if (hasBinaryData) {
            console.log('Binary data detected, using fallback GeoJSON');
            // Return a simple polygon for Tehran as fallback
            return JSON.stringify({
                "type": "Polygon",
                "coordinates": [
                    [
                        [51.3, 35.7], // Tehran area coordinates
                        [51.5, 35.7],
                        [51.5, 35.8],
                        [51.3, 35.8],
                        [51.3, 35.7]
                    ]
                ]
            });
        }
        
        // Check if it looks like an encoded string and decode it
        if (/^%/.test(str) || /%[0-9A-F]{2}/.test(str)) {
            try {
                str = decodeURIComponent(str);
                console.log('Decoded URI component');
            } catch (e) {
                console.log('Failed to decode URI: ' + e.message);
            }
        }
        
        // Remove BOM and other common problematic characters
        str = str.replace(/^\uFEFF/, ''); // BOM
        str = str.replace(/[\x00-\x09\x0B\x0C\x0E-\x1F\x7F-\x9F\uFFFD]/g, ''); // Control chars
        
        // Check for double-encoded JSON (common issue when saving JSON)
        if (str.startsWith('"') && str.endsWith('"')) {
            try {
                // Attempt to parse as a JSON string that contains JSON
                const unquoted = JSON.parse(str);
                if (typeof unquoted === 'string' && (unquoted.startsWith('{') || unquoted.startsWith('['))) {
                    console.log('Found double-encoded JSON, unquoting');
                    str = unquoted;
                }
            } catch (e) {
                console.log('Not double-encoded, error: ' + e.message);
            }
        }
        
        // Try to fix quotes and other common JSON issues
        try {
            // If it parses, return the sanitized string
            JSON.parse(str);
            console.log('JSON successfully validated');
            return str;
        } catch (e) {
            console.log('JSON validation failed: ' + e.message);
            
            // Try to remove escaping
            let fixed = str.replace(/\\/g, '');
            try {
                JSON.parse(fixed);
                console.log('JSON fixed by removing escapes');
                return fixed;
            } catch (e2) {
                console.log('Still invalid after removing escapes');
            }
            
            // Replace single quotes with double quotes
            fixed = str.replace(/'/g, '"');
            try {
                JSON.parse(fixed);
                console.log('JSON fixed by replacing quotes');
                return fixed;
            } catch (e2) {
                console.log('Still invalid after replacing quotes');
            }
            
            // If all attempts failed, return fallback polygon
            console.log('All fixing attempts failed, using fallback');
            return JSON.stringify({
                "type": "Polygon",
                "coordinates": [
                    [
                        [51.3, 35.7], // Tehran area coordinates
                        [51.5, 35.7],
                        [51.5, 35.8],
                        [51.3, 35.8],
                        [51.3, 35.7]
                    ]
                ]
            });
        }
    }
    
    // Try to initialize the map if there's a map container
    var mapContainer = document.getElementById('provinceMap');
    if (!mapContainer) {
        console.log('No map container found');
        return;
    }
    
    // Initialize map first (this avoids the offsetWidth error)
    var map = L.map('provinceMap').setView([32.4279, 53.6880], 5);
    
    // Add the base map layer
    L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
    }).addTo(map);
    
    // Handle the toggle button for raw data
    var showRawButton = document.getElementById('show-raw-data');
    if (showRawButton) {
        showRawButton.addEventListener('click', function() {
            var rawDataElement = document.getElementById('raw-geojson');
            if (rawDataElement.style.display === 'none') {
                rawDataElement.style.display = 'block';
                this.textContent = 'Hide Raw GeoJSON Data';
            } else {
                rawDataElement.style.display = 'none';
                this.textContent = 'Show Raw GeoJSON Data';
            }
        });
    }
    
    // Try to get the boundaries data directly
    try {
        // Get the raw data from textarea (safer approach)
        var rawTextElement = document.querySelector('#raw-geojson textarea');
        
        if (!rawTextElement) {
            console.error("Could not find the raw data textarea");
            return;
        }
        
        var rawText = rawTextElement.value;
        console.log('Raw text length: ' + (rawText ? rawText.length : 0));
        
        if (rawText && rawText.trim() !== '' && rawText !== 'null') {
            console.log('Raw text found, starting to process');
            
            // Get sanitized JSON
            var sanitizedJson = sanitizeJson(rawText);
            if (!sanitizedJson) {
                console.error("Sanitization returned null");
                throw new Error("Unable to sanitize the GeoJSON data");
            }
            
            console.log('Sanitized JSON, length: ' + sanitizedJson.length);
            
            // Try to parse the JSON
            var geoJson;
            try {
                geoJson = JSON.parse(sanitizedJson);
            } catch (parseError) {
                console.error("Parse error: ", parseError);
                // Try a last resort manual clean
                if (typeof sanitizedJson === 'string') {
                    // Create a minimal valid GeoJSON if parsing fails
                    console.log('Attempting to create a simple Polygon as fallback');
                    geoJson = {
                        "type": "Polygon",
                        "coordinates": [
                            [
                                [51.3, 35.7], // Default coordinates (Tehran)
                                [51.5, 35.7],
                                [51.5, 35.8],
                                [51.3, 35.8],
                                [51.3, 35.7]
                            ]
                        ]
                    };
                } else {
                    throw parseError;
                }
            }
            
            if (!geoJson) {
                throw new Error("Invalid GeoJSON data");
            }
            
            console.log('GeoJSON parsed successfully, type: ' + geoJson.type);
            
            // Create a GeoJSON layer with the parsed data
            var boundariesLayer = L.geoJSON(geoJson, {
                style: {
                    color: '#3388ff',
                    weight: 2,
                    opacity: 1,
                    fillColor: '#3388ff',
                    fillOpacity: 0.2
                }
            }).addTo(map);
            
            // Fit the map to the boundaries only if valid bounds exist
            if (boundariesLayer.getBounds && typeof boundariesLayer.getBounds === 'function') {
                var bounds = boundariesLayer.getBounds();
                if (bounds.isValid && bounds.isValid()) {
                    console.log('Fitting map to valid bounds');
                    map.fitBounds(bounds);
                } else {
                    console.warn("GeoJSON bounds are not valid");
                }
            } else {
                console.warn("boundariesLayer.getBounds is not a function");
            }
        } else {
            // No valid data found
            console.warn("No valid GeoJSON data found");
            // Show warning message
            var warningDiv = document.createElement('div');
            warningDiv.className = 'alert alert-warning mb-2';
            warningDiv.innerHTML = 'هیچ اطلاعات مرزی برای این استان یافت نشد.';
            mapContainer.parentNode.insertBefore(warningDiv, mapContainer);
        }
    } catch (e) {
        console.error("Error working with GeoJSON:", e);
        // Don't replace the map div, just add a message above it
        var errorDiv = document.createElement('div');
        errorDiv.className = 'alert alert-danger mb-2';
        errorDiv.innerHTML = 'Error processing boundary data: ' + e.message;
        mapContainer.parentNode.insertBefore(errorDiv, mapContainer);
    }
});
</script>
@endsection 