<?php $__env->startSection('content'); ?>
<div class="card">
    <div class="card-header">
        <div class="row align-items-center">
            <div class="col">
                <h5 class="mb-0">Import Attendance from CSV</h5>
            </div>
            <div class="col-auto">
                <a href="<?php echo e(route('attendance.import.logs')); ?>" class="btn btn-secondary btn-sm">
                <i class="bi bi-clock-history"></i> Import History
            </a>
            </div>
        </div>       
    </div>

    <div class="card-body">
        <?php if($settings->isEmpty()): ?>
            <div class="alert alert-warning">
                <i class="bi bi-exclamation-triangle"></i>
                No attendance settings configured for CSV import.
                <a href="<?php echo e(route('attendance.settings.create')); ?>">Create settings profile</a> first.
            </div>
        <?php else: ?>
            <form id="uploadForm" enctype="multipart/form-data">
                <?php echo csrf_field(); ?>
                <div class="row">
                    <div class="col-md-4">
                        <div class="mb-3">
                            <label class="form-label">Settings Profile <span class="text-danger">*</span></label>
                            <select name="setting_id" id="setting_id" class="form-control" required>
                                <?php $__currentLoopData = $settings; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $setting): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                    <option value="<?php echo e($setting->id); ?>"
                                        <?php echo e(($defaultSetting && $defaultSetting->id == $setting->id) ? 'selected' : ''); ?>

                                        data-punch-mode="<?php echo e($setting->punch_mode); ?>"
                                        data-source-type="<?php echo e($setting->source_type); ?>">
                                        <?php echo e($setting->name); ?>

                                        <?php if($setting->is_default): ?> (Default) <?php endif; ?>
                                    </option>
                                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                            </select>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="mb-3">
                            <label class="form-label">Branch <span class="text-danger">*</span></label>
                            <select name="branch_id" id="branch_id" class="form-control" required>
                                <option value="">Select Branch</option>
                                <?php $__currentLoopData = $branches; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $branch): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                    <option value="<?php echo e($branch->id); ?>"><?php echo e($branch->name); ?></option>
                                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                            </select>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="mb-3">
                            <label class="form-label">CSV File <span class="text-danger">*</span></label>
                            <input type="file" name="csv_file" id="csv_file" class="form-control"
                                    accept=".csv,.txt" required>
                            <small class="text-muted">Max 10MB. CSV or TXT format.</small>
                        </div>
                    </div>
                </div>

                <button type="submit" class="btn btn-primary" id="previewBtn">
                    <i class="bi bi-eye"></i> Preview Data
                </button>
            </form>

            <!-- Preview Section -->
            <div id="previewSection" class="mt-4" style="display: none;">
                <hr>
                <h6>Data Preview</h6>

                <div class="alert alert-info">
                    <strong>Total Records:</strong> <span id="totalRecords">0</span> |
                    <strong>Columns:</strong> <span id="columnCount">0</span>
                </div>

                <div class="table-responsive">
                    <table class="table table-sm table-bordered" id="previewTable">
                        <thead class="table-light">
                            <tr id="previewHeaders"></tr>
                        </thead>
                        <tbody id="previewBody"></tbody>
                    </table>
                </div>

                <div class="mt-3">
                    <button type="button" class="btn btn-success" id="importBtn">
                        <i class="bi bi-upload"></i> Import Data
                    </button>
                    <button type="button" class="btn btn-secondary" id="cancelBtn">
                        Cancel
                    </button>
                </div>
            </div>

            <!-- Result Section -->
            <div id="resultSection" class="mt-4" style="display: none;">
                <hr>
                <div class="alert" id="resultAlert">
                    <h5 id="resultTitle"></h5>
                    <div id="resultStats"></div>
                    <div id="resultErrors" class="mt-2" style="display: none;">
                        <strong>Errors:</strong>
                        <ul id="errorList" class="mb-0"></ul>
                    </div>
                </div>
            </div>
        <?php endif; ?>
    </div>
</div>
<?php $__env->stopSection(); ?>

<?php $__env->startSection('scripts'); ?>
<script>
$(function() {
    // Preview form submit
    $('#uploadForm').on('submit', function(e) {
        e.preventDefault();

        let formData = new FormData(this);

        $('#previewBtn').prop('disabled', true).html('<span class="spinner-border spinner-border-sm"></span> Loading...');
        $('#previewSection').hide();
        $('#resultSection').hide();

        $.ajax({
            url: "<?php echo e(route('attendance.import.csv.preview')); ?>",
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function(res) {
                if (res.status) {
                    showPreview(res.data, res.setting);
                } else {
                    Swal.fire('Error', res.message, 'error');
                }
            },
            error: function(xhr) {
                let msg = xhr.responseJSON?.message || 'Error uploading file';
                Swal.fire('Error', msg, 'error');
            },
            complete: function() {
                $('#previewBtn').prop('disabled', false).html('<i class="bi bi-eye"></i> Preview Data');
            }
        });
    });

    // Show preview data
    function showPreview(data, setting) {
        $('#totalRecords').text(data.total_records);
        $('#columnCount').text(data.column_count);

        // Build headers
        let headers = '<th>#</th>';
        data.headers.forEach(function(h, i) {
            let mapped = getMappedField(i, setting.field_mapping);
            headers += '<th>' + h + (mapped ? '<br><small class="text-success">→ ' + mapped + '</small>' : '') + '</th>';
        });
        $('#previewHeaders').html(headers);

        // Build body
        let body = '';
        data.preview.forEach(function(row) {
            body += '<tr><td>' + row.line_number + '</td>';
            row.data.forEach(function(cell) {
                body += '<td>' + (cell || '-') + '</td>';
            });
            body += '</tr>';
        });
        $('#previewBody').html(body);

        $('#previewSection').show();
    }

    // Get mapped field name for column index
    function getMappedField(index, mapping) {
        let fields = {
            'emp_id': 'Employee ID',
            'date': 'Date',
            'time': 'Time',
            'datetime': 'DateTime',
            'punch_type': 'Punch Type',
            'in_time': 'In Time',
            'out_time': 'Out Time'
        };

        for (let key in mapping) {
            if (mapping[key].csv_column === index) {
                return fields[key] || key;
            }
        }
        return null;
    }

    // Import button
    $('#importBtn').on('click', function() {
        let branchId = $('#branch_id').val();
        let settingId = $('#setting_id').val();

        if (!branchId) {
            Swal.fire('Error', 'Please select a branch', 'error');
            return;
        }

        Swal.fire({
            title: 'Confirm Import',
            text: 'Are you sure you want to import this attendance data?',
            icon: 'question',
            showCancelButton: true,
            confirmButtonText: 'Yes, Import'
        }).then((result) => {
            if (result.isConfirmed) {
                doImport(settingId, branchId);
            }
        });
    });

    // Do import
    function doImport(settingId, branchId) {
        $('#importBtn').prop('disabled', true).html('<span class="spinner-border spinner-border-sm"></span> Importing...');

        $.ajax({
            url: "<?php echo e(route('attendance.import.csv.process')); ?>",
            type: 'POST',
            data: {
                _token: "<?php echo e(csrf_token()); ?>",
                setting_id: settingId,
                branch_id: branchId
            },
            success: function(res) {
                showResult(res);
            },
            error: function(xhr) {
                let msg = xhr.responseJSON?.message || 'Import failed';
                showResult({
                    status: false,
                    message: msg,
                    data: xhr.responseJSON?.data || null
                });
            },
            complete: function() {
                $('#importBtn').prop('disabled', false).html('<i class="bi bi-upload"></i> Import Data');
                $('#previewSection').hide();
            }
        });
    }

    // Show import result
    function showResult(res) {
        let alertClass = res.status ? 'alert-success' : 'alert-danger';
        let title = res.status ? 'Import Completed!' : 'Import Failed';

        $('#resultAlert').removeClass('alert-success alert-danger alert-warning').addClass(alertClass);
        $('#resultTitle').text(title);

        if (res.data) {
            let stats = `
                <p class="mb-1"><strong>Total Records:</strong> ${res.data.total || 0}</p>
                <p class="mb-1"><strong>Processed:</strong> ${res.data.processed || 0}</p>
                <p class="mb-1"><strong>Success:</strong> ${res.data.success || 0}</p>
                <p class="mb-1"><strong>Failed:</strong> ${res.data.failed || 0}</p>
                <p class="mb-0"><strong>Skipped:</strong> ${res.data.skipped || 0}</p>
            `;
            $('#resultStats').html(stats);

            // Show errors if any
            if (res.data.errors && res.data.errors.length > 0) {
                let errorHtml = '';
                res.data.errors.slice(0, 10).forEach(function(err) {
                    errorHtml += '<li>' + err.message + ' (Key: ' + err.key + ')</li>';
                });
                if (res.data.errors.length > 10) {
                    errorHtml += '<li>... and ' + (res.data.errors.length - 10) + ' more errors</li>';
                }
                $('#errorList').html(errorHtml);
                $('#resultErrors').show();
            } else {
                $('#resultErrors').hide();
            }
        } else {
            $('#resultStats').html('<p>' + (res.message || '') + '</p>');
            $('#resultErrors').hide();
        }

        $('#resultSection').show();

        // Reset form for new upload
        $('#uploadForm')[0].reset();
    }

    // Cancel button
    $('#cancelBtn').on('click', function() {
        $('#previewSection').hide();
        $('#resultSection').hide();
        $('#uploadForm')[0].reset();
    });
});
</script>
<?php $__env->stopSection(); ?>

<?php echo $__env->make('layouts.app', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH /home/codeproh/demo.laraoffice.com/app/Modules/HR/Attendance/Providers/../Views/import/csv.blade.php ENDPATH**/ ?>