@extends('layouts.app')

@section('title', 'Offline Data Import - NGBVD')

@push('styles')
<style>
    .ngbvd-upload-zone{border:2px dashed rgba(135,92,0,.28);border-radius:22px;background:linear-gradient(135deg,#fffaf0,#ffffff);padding:34px;text-align:center;position:relative;transition:.2s ease;cursor:pointer;min-height:210px;display:flex;align-items:center;justify-content:center;flex-direction:column;}
    .ngbvd-upload-zone:hover,.ngbvd-upload-zone.dragover{border-color:var(--ngbvd-yellow,#d9a514);box-shadow:0 18px 40px rgba(85,65,0,.12);transform:translateY(-1px);}
    .ngbvd-upload-icon{width:72px;height:72px;border-radius:22px;display:flex;align-items:center;justify-content:center;background:rgba(217,165,20,.14);color:var(--ngbvd-yellow,#d9a514);font-size:2.2rem;margin-bottom:14px;}
    .ngbvd-upload-zone input[type=file]{position:absolute;inset:0;opacity:0;cursor:pointer;}
    .ngbvd-upload-file{margin-top:14px;padding:10px 14px;border-radius:999px;background:#f6f7fb;color:#344054;display:none;align-items:center;gap:8px;font-weight:600;}
    .ngbvd-upload-file.show{display:inline-flex;}
    .ngbvd-import-step{display:flex;gap:12px;margin-bottom:14px;align-items:flex-start;}
    .ngbvd-import-step span{width:30px;height:30px;border-radius:50%;background:var(--ngbvd-primary,#5b3b00);color:white;display:flex;align-items:center;justify-content:center;font-weight:700;flex:0 0 30px;}
</style>
@endpush

@section('content')
<div class="ngbvd-import-page">
    <div class="ngbvd-page-hero">
        <div class="ngbvd-page-hero-icon"><i class="ti-cloud-up"></i></div>
        <div>
            <h2>Offline Data Import</h2>
            <p>Download the case-intake template, collect data offline in Excel, validate it and upload it into NGBVD.</p>
        </div>
    </div>

    <div class="row">
        <div class="col-lg-8">
            <div class="card ngbvd-settings-card">
                <div class="card-block">
                    @php
                        $displayMessage = $message ?? session('message');
                        $displaySummary = $importSummaryJson ?? session('import_summary');
                    @endphp

                    @if($displayMessage)
                        <div class="alert alert-success">{{ $displayMessage }}</div>
                    @endif

                    @if($errors->any())
                        <div class="alert alert-danger">
                            <strong>Offline import could not continue.</strong>
                            <ul class="mb-0 mt-2">
                                @foreach($errors->all() as $error)
                                    <li>{{ $error }}</li>
                                @endforeach
                            </ul>
                        </div>
                    @endif

                    <div class="d-flex justify-content-between align-items-start flex-wrap mb-3" style="gap:10px;">
                        <div>
                            <h4 class="mb-1">Upload Completed Template</h4>
                            <p class="text-muted mb-0">Use validate-only first to detect duplicates, missing fields and invalid dates before saving records.</p>
                        </div>
                        <a href="{{ route('/dataentry/import/template') }}" class="btn ngbvd-btn-soft"><i class="ti-download"></i> Download Template</a>
                    </div>

                    <!-- offline-import-post-fix-v7 -->
                    <form method="post" action="{{ url('/dataentry/import') }}" enctype="multipart/form-data" id="ngbvdOfflineImportForm" data-no-ajax="true">
                        @csrf
                        <label class="ngbvd-upload-zone" id="ngbvdUploadZone">
                            <span class="ngbvd-upload-icon"><i class="ti-cloud-up"></i></span>
                            <h4>Drop Excel/CSV file here or click to browse</h4>
                            <p class="text-muted mb-0">Accepted formats: .xlsx, .xls, .csv and .txt. Maximum size: 10MB.</p>
                            <span class="ngbvd-upload-file" id="ngbvdUploadFile"><i class="ti-file"></i><span>No file selected</span></span>
                            <input type="file" name="offline_file" id="offline_file" accept=".xlsx,.xls,.csv,.txt" required>
                        </label>

                        <div class="row mt-4">
                            <div class="col-md-6 form-group">
                                <label>Import Mode</label>
                                <select name="mode" class="form-control" data-no-selectize="true">
                                    <option value="validate_only" {{ (($selectedMode ?? old('mode')) === 'validate_only') ? 'selected' : '' }}>Validate only first</option>
                                    <option value="import" {{ (($selectedMode ?? old('mode')) === 'import') ? 'selected' : '' }}>Validate and import</option>
                                </select>
                            </div>
                            <div class="col-md-6 d-flex align-items-end flex-wrap" style="gap:10px;">
                                <button type="submit" class="btn ngbvd-btn-primary"><i class="ti-check"></i> Process File</button>
                                <button type="reset" class="btn ngbvd-btn-soft"><i class="ti-reload"></i> Clear</button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
        <div class="col-lg-4">
            <div class="card ngbvd-settings-card">
                <div class="card-block">
                    <h4>Recommended workflow</h4>
                    <div class="ngbvd-import-step"><span>1</span><div><strong>Download template</strong><br><small class="text-muted">Use the Variables sheet for accepted dropdown values.</small></div></div>
                    <div class="ngbvd-import-step"><span>2</span><div><strong>Collect data offline</strong><br><small class="text-muted">Keep column headers unchanged and dates as YYYY-MM-DD.</small></div></div>
                    <div class="ngbvd-import-step"><span>3</span><div><strong>Validate first</strong><br><small class="text-muted">Run validate-only before import to catch duplicates and missing data.</small></div></div>
                    <div class="ngbvd-import-step"><span>4</span><div><strong>Import safely</strong><br><small class="text-muted">Each row is processed in a transaction and failed rows roll back.</small></div></div>
                </div>
            </div>
        </div>
    </div>

    @if($displaySummary)
        <div class="card ngbvd-settings-card mt-4">
            <div class="card-block">
                <h4>Import Summary</h4>
                <pre class="bg-light p-3 rounded" style="white-space:pre-wrap;max-height:520px;overflow:auto;">{{ $displaySummary }}</pre>
            </div>
        </div>
    @endif
</div>
@endsection

@push('scripts')
<script>
(function(){
    var input = document.getElementById('offline_file');
    var zone = document.getElementById('ngbvdUploadZone');
    var label = document.getElementById('ngbvdUploadFile');
    if(!input || !zone || !label){ return; }
    var nameTarget = label.querySelector('span');
    function showFile(){
        if(input.files && input.files.length){
            nameTarget.textContent = input.files[0].name;
            label.classList.add('show');
        } else {
            nameTarget.textContent = 'No file selected';
            label.classList.remove('show');
        }
    }
    input.addEventListener('change', showFile);
    ['dragenter','dragover'].forEach(function(evt){zone.addEventListener(evt,function(e){e.preventDefault();zone.classList.add('dragover');});});
    ['dragleave','drop'].forEach(function(evt){zone.addEventListener(evt,function(e){e.preventDefault();zone.classList.remove('dragover');});});
    zone.addEventListener('drop', function(e){ if(e.dataTransfer && e.dataTransfer.files.length){ input.files = e.dataTransfer.files; showFile(); } });
    var form = document.getElementById('ngbvdOfflineImportForm');
    if(form){
        form.addEventListener('reset', function(){ setTimeout(showFile, 0); });
        form.addEventListener('submit', function(e){
            if(!input.files || !input.files.length){
                e.preventDefault();
                alert('Please select the completed offline import file before processing.');
                return false;
            }
            var submitBtn = form.querySelector('button[type="submit"]');
            if(submitBtn){
                submitBtn.disabled = true;
                submitBtn.innerHTML = '<i class="ti-reload"></i> Processing...';
            }
        });
    }
})();
</script>
@endpush
