@extends('layout.app')

@section('content')
    <div class="container">
        <!-- Import Results Section -->
        @if (session('showResults'))
            <div class="card mb-4">
                <div class="card-header {{ count(session('importErrors', [])) > 0 ? 'bg-warning text-dark' : 'bg-success text-white' }}">
                    <h5 class="mb-0">
                        <i class="fas {{ count(session('importErrors', [])) > 0 ? 'fa-exclamation-triangle' : 'fa-check-circle' }}"></i>
                        Import Results
                    </h5>
                </div>
                <div class="card-body">
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <div class="alert alert-success">
                                <strong>Successfully Imported:</strong> {{ session('successCount', 0) }} records
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="alert {{ count(session('importErrors', [])) > 0 ? 'alert-danger' : 'alert-secondary' }}">
                                <strong>Errors Found:</strong> {{ count(session('importErrors', [])) }} issues
                            </div>
                        </div>
                    </div>

                    @if (!empty(session('importErrors')))
                        <div class="alert alert-warning">
                            <h6><i class="fas fa-list"></i> Error Details:</h6>
                            <div style="max-height: 400px; overflow-y: auto; border: 1px solid #ddd; padding: 15px; background-color: #f8f9fa; border-radius: 5px;">
                                <ul class="mb-0" style="padding-left: 20px;">
                                    @foreach (session('importErrors', []) as $error)
                                        <li style="margin-bottom: 8px; font-size: 14px;">{{ $error }}</li>
                                    @endforeach
                                </ul>
                            </div>
                        </div>

                        <div class="mt-3">
                            <p class="text-muted">
                                <i class="fas fa-info-circle"></i>
                                Please fix the errors in your Excel file and try importing again. Only the rows with errors were skipped.
                            </p>
                        </div>
                    @endif
                </div>
            </div>
        @endif

        <!-- Import Form Section -->
        <div class="card">
            <div class="card-header bg-primary text-white">
                <h4 class="mb-0">
                    <i class="fas fa-file-excel"></i> Client Information Import
                </h4>
            </div>
            <div class="card-body">
                <div class="alert alert-info">
                    <h6><i class="fas fa-info-circle"></i> Instructions:</h6>
                    <ol class="mb-0">
                        <li>Download the sample Excel file below</li>
                        <li>Fill in the Excel with two columns:
                            <ul>
                                <li><strong>Column 1 (username):</strong> The client's username</li>
                                <li><strong>Column 2 (information):</strong> The value you want to update</li>
                            </ul>
                        </li>
                        <li>Select which field you want to update from the dropdown</li>
                        <li>Upload your filled Excel file</li>
                        <li>Click Submit to process the import</li>
                    </ol>
                </div>

                <!-- Download Sample Button -->
                <div class="mb-4">
                    <a href="{{ route('client-info-import.download-sample') }}" class="btn btn-success">
                        <i class="fas fa-download"></i> Download Sample Excel File
                    </a>
                </div>

                <!-- Import Form -->
                <form action="{{ route('client-info-import.import') }}" method="POST" enctype="multipart/form-data">
                    @csrf

                    <div class="row">
                        <!-- Column Selection Dropdown -->
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="column_mapping" class="font-weight-bold">
                                    <i class="fas fa-columns"></i> Select Column to Update <span class="text-danger">*</span>
                                </label>
                                <select name="column_mapping" id="column_mapping" class="form-control select2" required>
                                    <option value="">-- Select Column --</option>
                                    @foreach($columns as $tableName => $tableColumns)
                                        <optgroup label="{{ $tableName }}">
                                            @foreach($tableColumns as $columnKey => $columnLabel)
                                                <option value="{{ $columnKey }}">{{ $columnLabel }}</option>
                                            @endforeach
                                        </optgroup>
                                    @endforeach
                                </select>
                                @error('column_mapping')
                                    <span class="text-danger">{{ $message }}</span>
                                @enderror
                            </div>
                        </div>

                        <!-- File Upload -->
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="excel_file" class="font-weight-bold">
                                    <i class="fas fa-file-upload"></i> Upload Excel File <span class="text-danger">*</span>
                                </label>
                                <input type="file"
                                       name="excel_file"
                                       id="excel_file"
                                       class="form-control"
                                       accept=".xlsx,.xls,.csv"
                                       required>
                                <small class="form-text text-muted">
                                    Accepted formats: .xlsx, .xls, .csv
                                </small>
                                @error('excel_file')
                                    <span class="text-danger">{{ $message }}</span>
                                @enderror
                            </div>
                        </div>
                    </div>

                    <!-- Submit Button -->
                    <div class="row mt-3">
                        <div class="col-md-12">
                            <button type="submit" class="btn btn-primary btn-lg btn-block">
                                <i class="fas fa-upload"></i> Import Data
                            </button>
                        </div>
                    </div>
                </form>
            </div>
        </div>

        <!-- Help Section -->
        <div class="card mt-4">
            <div class="card-header bg-secondary text-white">
                <h5 class="mb-0">
                    <i class="fas fa-question-circle"></i> Help & Examples
                </h5>
            </div>
            <div class="card-body">
                <h6>Excel File Format:</h6>
                <div class="table-responsive">
                    <table class="table table-bordered table-sm">
                        <thead class="thead-light">
                            <tr>
                                <th>username</th>
                                <th>information</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td>user001</td>
                                <td>Sample Data 1</td>
                            </tr>
                            <tr>
                                <td>user002</td>
                                <td>Sample Data 2</td>
                            </tr>
                            <tr>
                                <td>user003</td>
                                <td>Sample Data 3</td>
                            </tr>
                        </tbody>
                    </table>
                </div>

                <div class="alert alert-warning mt-3">
                    <strong><i class="fas fa-exclamation-triangle"></i> Important Notes:</strong>
                    <ul class="mb-0">
                        <li>The username must exactly match the client's username in the system</li>
                        <li>Do not delete or modify the header row (username, information)</li>
                        <li>Make sure the data format matches the selected column type</li>
                        <li>For date fields, use format: YYYY-MM-DD</li>
                        <li>For numeric fields, use numbers only (no special characters)</li>
                    </ul>
                </div>
            </div>
        </div>
    </div>
@endsection

@section('ajax')
<script>
    $(document).ready(function() {
        // Initialize Select2 for better dropdown experience
        if ($.fn.select2) {
            $('#column_mapping').select2({
                placeholder: '-- Select Column --',
                allowClear: true
            });
        }

        // File input validation
        $('#excel_file').on('change', function() {
            var fileName = $(this).val();
            var allowedExtensions = /(\.xlsx|\.xls|\.csv)$/i;

            if (!allowedExtensions.exec(fileName)) {
                alert('Please upload a valid Excel file (.xlsx, .xls, or .csv)');
                $(this).val('');
                return false;
            }
        });

        // Form submission validation
        $('form').on('submit', function(e) {
            var columnMapping = $('#column_mapping').val();
            var excelFile = $('#excel_file').val();

            if (!columnMapping) {
                alert('Please select a column to update');
                e.preventDefault();
                return false;
            }

            if (!excelFile) {
                alert('Please select an Excel file to upload');
                e.preventDefault();
                return false;
            }

            // Show loading indicator
            var submitBtn = $(this).find('button[type="submit"]');
            submitBtn.prop('disabled', true);
            submitBtn.html('<i class="fas fa-spinner fa-spin"></i> Processing...');
        });
    });
</script>
@endsection
