@extends('admin-layouts.master')

@section('title', 'Tambah RTRW')

@section('content')
<div class="row">
    <div class="col-12">
        <!-- Header -->
        <div class="d-flex justify-content-between align-items-center mb-4">
            <div>
                <h2 class="h4 mb-1">Tambah RTRW</h2>
                <p class="text-muted mb-0">Tambahkan data RTRW baru</p>
            </div>
            <a href="{{ route('rtrw.index') }}" class="btn btn-secondary">
                <i class="fas fa-arrow-left"></i> Kembali
            </a>
        </div>

        <div class="row">
            <!-- Form Card -->
            <div class="col-lg-7">
                <div class="card shadow mb-4">
                    <div class="card-header py-3">
                        <h6 class="m-0 font-weight-bold text-primary">
                            <i class="fas fa-plus-circle"></i> Formulir RTRW
                        </h6>
                    </div>
                    <div class="card-body">
                        @if ($errors->any())
                            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                                <strong>Terjadi Kesalahan!</strong>
                                <ul class="mb-0 mt-2">
                                    @foreach ($errors->all() as $error)
                                        <li>{{ $error }}</li>
                                    @endforeach
                                </ul>
                                <button type="button" class="close" data-dismiss="alert">
                                    <span>&times;</span>
                                </button>
                            </div>
                        @endif

                        <form action="{{ route('rtrw.store') }}" method="POST" enctype="multipart/form-data" id="rtrwForm">
                            @csrf
                            
                            <!-- Nama RTRW -->
                            <div class="form-group">
                                <label for="nama_rtrw" class="font-weight-bold">
                                    Nama RTRW <span class="text-danger">*</span>
                                </label>
                                <input 
                                    type="text" 
                                    class="form-control form-control-lg" 
                                    id="nama_rtrw" 
                                    name="nama_rtrw" 
                                    value="{{ old('nama_rtrw') }}" 
                                    placeholder=""
                                    required
                                >
                            </div>

                            <!-- Warna -->
                            <div class="form-group">
                                <label for="warna" class="font-weight-bold">
                                    Warna <span class="text-danger">*</span>
                                </label>
                                <div class="input-group">
                                    <div class="input-group-prepend">
                                        <span class="input-group-text p-0" style="width: 50px;">
                                            <input 
                                                type="color" 
                                                class="form-control border-0" 
                                                id="warna" 
                                                name="warna" 
                                                value="{{ old('warna', '#4e73df') }}" 
                                                style="height: 42px; cursor: pointer;"
                                                required
                                            >
                                        </span>
                                    </div>
                                    <input 
                                        type="text" 
                                        class="form-control" 
                                        id="warnaText" 
                                        value="{{ old('warna', '#4e73df') }}" 
                                        readonly
                                    >
                                </div>
                                <small class="text-muted">Pilih warna untuk menandai area di peta</small>
                            </div>

                            <!-- GeoJSON Upload -->
                            <div class="form-group">
                                <label class="font-weight-bold">
                                    File GeoJSON <span class="text-danger">*</span>
                                </label>
                                
                                <!-- Drop Zone -->
                                <div class="border rounded p-4 text-center" id="dropZone" style="border: 2px dashed #d1d3e2; background: #f8f9fc; transition: all 0.3s;">
                                    <input 
                                        type="file" 
                                        class="d-none" 
                                        id="geojson" 
                                        name="geojson" 
                                        accept=".geojson,.json"
                                        required
                                    >
                                    <label for="geojson" class="mb-0 w-100" style="cursor: pointer;">
                                        <div id="uploadPrompt">
                                            <i class="fas fa-cloud-upload-alt fa-3x text-primary mb-3"></i>
                                            <h5 class="text-primary mb-2">Klik atau Drag & Drop</h5>
                                            <p class="text-muted mb-1">Upload file .geojson atau .json</p>
                                            <small class="text-muted">Maksimal ukuran file: 2MB</small>
                                        </div>
                                    </label>
                                </div>

                                <!-- File Info Display -->
                                <div id="fileInfo" class="alert alert-success mt-3 d-none">
                                    <div class="d-flex justify-content-between align-items-center">
                                        <div>
                                            <i class="fas fa-check-circle mr-2"></i>
                                            <strong id="fileName"></strong>
                                            <br>
                                            <small id="fileSize" class="text-muted"></small>
                                        </div>
                                        <button type="button" class="btn btn-sm btn-danger" onclick="clearFile()">
                                            <i class="fas fa-times"></i>
                                        </button>
                                    </div>
                                </div>

                                <!-- Validation Message -->
                                <div id="validationMsg" class="mt-2 d-none"></div>

                                <small class="text-muted">
                                    <i class="fas fa-info-circle"></i> 
                                    Upload file GeoJSON yang valid
                                </small>
                            </div>

                            <!-- Submit Buttons -->
                            <hr>
                            <div class="form-group mb-0">
                                <button type="submit" class="btn btn-primary btn-lg">
                                    <i class="fas fa-save"></i> Simpan
                                </button>
                                <a href="{{ route('rtrw.index') }}" class="btn btn-secondary btn-lg ml-2">
                                    <i class="fas fa-times"></i> Batal
                                </a>
                            </div>
                        </form>
                    </div>
                </div>
            </div>

            <!-- Preview Card -->
            <div class="col-lg-5">
                <div class="card shadow mb-4">
                    <div class="card-header py-3">
                        <h6 class="m-0 font-weight-bold text-success">
                            <i class="fas fa-map-marked-alt"></i> Preview GeoJSON
                        </h6>
                    </div>
                    <div class="card-body">
                        <div id="previewContainer">
                            <div class="text-center text-muted py-5">
                                <i class="fas fa-map fa-3x mb-3"></i>
                                <p>Upload file GeoJSON untuk melihat informasi</p>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Info Card -->
                <div class="card shadow border-left-info">
                    <div class="card-body">
                        <div class="text-info">
                            <i class="fas fa-info-circle fa-2x mb-3"></i>
                            <h6 class="font-weight-bold">Informasi Format</h6>
                            <ul class="small mb-0 pl-3">
                                <li>Format file: .geojson atau .json</li>
                                <li>Maksimal ukuran: 2MB</li>
                                <li>Harus berisi koordinat yang valid</li>
                                <li>Gunakan format GeoJSON standar</li>
                            </ul>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<style>
#dropZone:hover {
    border-color: #4e73df !important;
    background: #eaecf4 !important;
}

#dropZone.drag-over {
    border-color: #4e73df !important;
    background: #e3e6f7 !important;
}

.form-control-lg {
    font-size: 1rem;
}
</style>
@endsection

@push('scripts')
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
let currentFile = null;

// Color picker sync
document.getElementById('warna').addEventListener('input', function(e) {
    document.getElementById('warnaText').value = e.target.value;
});

// Drag and drop functionality
const dropZone = document.getElementById('dropZone');
const fileInput = document.getElementById('geojson');

['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
    dropZone.addEventListener(eventName, preventDefaults, false);
});

function preventDefaults(e) {
    e.preventDefault();
    e.stopPropagation();
}

['dragenter', 'dragover'].forEach(eventName => {
    dropZone.addEventListener(eventName, () => {
        dropZone.classList.add('drag-over');
    });
});

['dragleave', 'drop'].forEach(eventName => {
    dropZone.addEventListener(eventName, () => {
        dropZone.classList.remove('drag-over');
    });
});

dropZone.addEventListener('drop', handleDrop);

function handleDrop(e) {
    const dt = e.dataTransfer;
    const files = dt.files;
    if (files.length > 0) {
        handleFiles(files[0]);
    }
}

// File input change
fileInput.addEventListener('change', function(e) {
    if (this.files.length > 0) {
        handleFiles(this.files[0]);
    }
});

// Handle file upload
function handleFiles(file) {
    const fileName = file.name.toLowerCase();
    
    if (!fileName.endsWith('.json') && !fileName.endsWith('.geojson')) {
        showValidation('File harus berformat .geojson atau .json', 'danger');
        return;
    }

    if (file.size > 2 * 1024 * 1024) {
        showValidation('Ukuran file maksimal 2MB', 'danger');
        return;
    }

    currentFile = file;

    const dataTransfer = new DataTransfer();
    dataTransfer.items.add(file);
    fileInput.files = dataTransfer.files;

    const reader = new FileReader();
    reader.onload = function(e) {
        try {
            const geojson = JSON.parse(e.target.result);
            
            if (!geojson.type) {
                showValidation('Format GeoJSON tidak valid: property "type" tidak ditemukan', 'warning');
                return;
            }

            document.getElementById('fileName').textContent = file.name;
            document.getElementById('fileSize').textContent = formatFileSize(file.size);
            document.getElementById('fileInfo').classList.remove('d-none');
            document.getElementById('uploadPrompt').style.display = 'none';

            updatePreview(geojson, file.name);
            
            showValidation('✓ File GeoJSON valid dan siap diupload', 'success');
        } catch (error) {
            showValidation('File JSON tidak valid: ' + error.message, 'danger');
        }
    };
    reader.readAsText(file);
}

function clearFile() {
    currentFile = null;
    fileInput.value = '';
    document.getElementById('fileInfo').classList.add('d-none');
    document.getElementById('uploadPrompt').style.display = 'block';
    document.getElementById('validationMsg').classList.add('d-none');
    
    document.getElementById('previewContainer').innerHTML = `
        <div class="text-center text-muted py-5">
            <i class="fas fa-map fa-3x mb-3"></i>
            <p>Upload file GeoJSON untuk melihat informasi</p>
        </div>
    `;
}

function updatePreview(geojson, filename) {
    let html = '<div class="small">';
    
    html += `<div class="mb-3">
        <strong><i class="fas fa-file"></i> Nama File:</strong><br>
        <code class="text-primary">${filename}</code>
    </div>`;
    
    html += `<div class="mb-3">
        <strong><i class="fas fa-layer-group"></i> Type:</strong><br>
        <span class="badge badge-primary">${geojson.type}</span>
    </div>`;

    if (geojson.features) {
        html += `<div class="mb-3">
            <strong><i class="fas fa-shapes"></i> Jumlah Features:</strong><br>
            <span class="badge badge-success">${geojson.features.length}</span>
        </div>`;

        const types = [...new Set(geojson.features.map(f => f.geometry?.type).filter(Boolean))];
        if (types.length > 0) {
            html += `<div class="mb-3">
                <strong><i class="fas fa-draw-polygon"></i> Tipe Geometri:</strong><br>
                ${types.map(t => `<span class="badge badge-info mr-1">${t}</span>`).join('')}
            </div>`;
        }
    }

    if (geojson.geometry) {
        html += `<div class="mb-3">
            <strong><i class="fas fa-map-pin"></i> Geometri:</strong><br>
            <span class="badge badge-info">${geojson.geometry.type}</span>
        </div>`;
    }

    html += '</div>';
    
    document.getElementById('previewContainer').innerHTML = html;
}

function showValidation(message, type) {
    const validationMsg = document.getElementById('validationMsg');
    validationMsg.className = `alert alert-${type} mt-2`;
    validationMsg.innerHTML = `<i class="fas fa-${type === 'success' ? 'check-circle' : type === 'danger' ? 'exclamation-circle' : 'info-circle'}"></i> ${message}`;
    validationMsg.classList.remove('d-none');
}

function formatFileSize(bytes) {
    if (bytes === 0) return '0 Bytes';
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return Math.round(bytes / Math.pow(k, i) * 100) / 100 + ' ' + sizes[i];
}

@if(session('success'))
    Swal.fire({
        icon: 'success',
        title: 'Berhasil!',
        text: '{{ session('success') }}',
        confirmButtonColor: '#1cc88a',
    });
@endif

@if(session('error'))
    Swal.fire({
        icon: 'error',
        title: 'Gagal!',
        text: '{{ session('error') }}',
        confirmButtonColor: '#e74a3b',
    });
@endif
</script>
@endpush