<?php
if (!defined('ABSPATH')) exit;

$lists = get_terms(['taxonomy' => 'plover_crm_list', 'hide_empty' => false]);
$tags = get_terms(['taxonomy' => 'plover_crm_tag', 'hide_empty' => false]);
if (is_wp_error($lists)) $lists = [];
if (is_wp_error($tags)) $tags = [];
$nonce = wp_create_nonce('plover_crm_csv');
?>
<style>
    .plvcrm-csv-wrap {
        max-width: 900px;
    }

    .plvcrm-csv-tabs {
        display: flex;
        border-bottom: 1px solid #c3c4c7;
        margin-bottom: 20px;
    }

    .plvcrm-csv-tab {
        padding: 10px 20px;
        cursor: pointer;
        background: #f0f0f1;
        border: 1px solid transparent;
        border-bottom: none;
        margin-bottom: -1px;
    }

    .plvcrm-csv-tab.active {
        background: #fff;
        border-color: #c3c4c7;
        border-bottom-color: #fff;
    }

    .plvcrm-csv-panel {
        display: none;
        padding: 20px;
        background: #fff;
        border: 1px solid #c3c4c7;
        border-top: none;
    }

    .plvcrm-csv-panel.active {
        display: block;
    }

    .plvcrm-csv-section {
        margin-bottom: 25px;
    }

    .plvcrm-csv-section h3 {
        margin: 0 0 15px;
        padding-bottom: 10px;
        border-bottom: 1px solid #eee;
    }

    .plvcrm-csv-row {
        margin-bottom: 15px;
    }

    .plvcrm-csv-row>label {
        display: block;
        margin-bottom: 5px;
        font-weight: 600;
    }

    .plvcrm-csv-row select,
    .plvcrm-csv-row input[type="date"] {
        width: 250px;
    }

    .plvcrm-csv-dropzone {
        border: 2px dashed #c3c4c7;
        padding: 40px;
        text-align: center;
        cursor: pointer;
    }

    .plvcrm-csv-dropzone:hover,
    .plvcrm-csv-dropzone.dragover {
        border-color: #2271b1;
        background: #f0f7fc;
    }

    .plvcrm-csv-dropzone input {
        display: none;
    }

    .plvcrm-csv-table {
        width: 100%;
        border-collapse: collapse;
        margin: 15px 0;
    }

    .plvcrm-csv-table th,
    .plvcrm-csv-table td {
        padding: 10px;
        border: 1px solid #ddd;
        text-align: left;
    }

    .plvcrm-csv-table th {
        background: #f5f5f5;
    }

    .plvcrm-csv-table select {
        width: 100%;
    }

    .plvcrm-csv-progress {
        margin: 20px 0;
    }

    .plvcrm-csv-bar {
        height: 20px;
        background: #e0e0e0;
        border-radius: 3px;
        overflow: hidden;
    }

    .plvcrm-csv-fill {
        height: 100%;
        background: #2271b1;
        transition: width 0.3s;
    }

    .plvcrm-csv-stats {
        display: flex;
        gap: 15px;
        margin: 15px 0;
    }

    .plvcrm-csv-stat {
        padding: 12px 20px;
        background: #f5f5f5;
        border-radius: 4px;
        text-align: center;
    }

    .plvcrm-csv-stat-val {
        font-size: 20px;
        font-weight: 600;
    }

    .plvcrm-csv-stat-val.green {
        color: #00a32a;
    }

    .plvcrm-csv-stat-val.blue {
        color: #2271b1;
    }

    .plvcrm-csv-stat-val.orange {
        color: #dba617;
    }

    .plvcrm-csv-stat-val.red {
        color: #d63638;
    }

    .plvcrm-csv-stat-lbl {
        font-size: 11px;
        color: #666;
    }

    .plvcrm-csv-list {
        max-height: 150px;
        overflow-y: auto;
        border: 1px solid #ddd;
        padding: 10px;
    }

    .plvcrm-csv-list label {
        display: block;
        margin-bottom: 5px;
        font-weight: normal;
    }

    .plvcrm-csv-msg {
        padding: 12px 15px;
        margin: 15px 0;
        border-left: 4px solid;
    }

    .plvcrm-csv-msg.success {
        background: #edfaef;
        border-color: #00a32a;
    }

    .plvcrm-csv-msg.warning {
        background: #fcf9e8;
        border-color: #dba617;
    }
</style>

<div class="wrap plvcrm-csv-wrap">
    <h1>Import/Export Contacts</h1>

    <div class="plvcrm-csv-tabs">
        <div class="plvcrm-csv-tab active" data-tab="import">Import CSV</div>
        <div class="plvcrm-csv-tab" data-tab="export">Export CSV</div>
    </div>

    <!-- Import Panel -->
    <div class="plvcrm-csv-panel active" id="panel-import">
        <div id="import-upload" class="plvcrm-csv-section">
            <h3>Upload CSV File</h3>
            <div class="plvcrm-csv-dropzone" id="dropzone">
                <input type="file" id="csv-file" accept=".csv">
                <p><strong>Drop CSV file here or click to browse</strong></p>
                <p class="description">CSV with headers in first row</p>
            </div>
        </div>

        <div id="import-mapping" class="plvcrm-csv-section" style="display:none;">
            <h3>Map Fields</h3>
            <p>Auto-detected mappings are pre-selected. Adjust as needed.</p>
            <table class="plvcrm-csv-table" id="mapping-table">
                <thead>
                    <tr>
                        <th>CSV Column</th>
                        <th>Sample</th>
                        <th>Map To</th>
                    </tr>
                </thead>
                <tbody></tbody>
            </table>
            <div id="unmapped-msg" class="plvcrm-csv-msg warning" style="display:none;">
                <strong>Unmapped:</strong> <span id="unmapped-list"></span>
            </div>

            <h3>Options</h3>
            <div class="plvcrm-csv-row">
                <label>Duplicates</label>
                <select id="opt-duplicate">
                    <option value="skip">Skip</option>
                    <option value="update">Update existing</option>
                    <option value="create">Create new</option>
                </select>
            </div>
            <div class="plvcrm-csv-row">
                <label>Assign Lists</label>
                <div class="plvcrm-csv-list">
                    <?php if (!empty($lists)): foreach ($lists as $l): ?>
                            <label><input type="checkbox" name="opt_lists[]" value="<?php echo $l->term_id; ?>"> <?php echo esc_html($l->name); ?></label>
                        <?php endforeach;
                    else: ?><em>No lists</em><?php endif; ?>
                </div>
            </div>
            <div class="plvcrm-csv-row">
                <label>Assign Tags</label>
                <div class="plvcrm-csv-list">
                    <?php if (!empty($tags)): foreach ($tags as $t): ?>
                            <label><input type="checkbox" name="opt_tags[]" value="<?php echo $t->term_id; ?>"> <?php echo esc_html($t->name); ?></label>
                        <?php endforeach;
                    else: ?><em>No tags</em><?php endif; ?>
                </div>
            </div>
            <p>
                <button class="button button-primary" id="btn-import">Start Import</button>
                <button class="button" id="btn-cancel-map">Cancel</button>
            </p>
        </div>

        <div id="import-progress" class="plvcrm-csv-section" style="display:none;">
            <h3>Importing...</h3>
            <div class="plvcrm-csv-progress">
                <div class="plvcrm-csv-bar">
                    <div class="plvcrm-csv-fill" id="progress-fill"></div>
                </div>
                <p id="progress-text">Preparing...</p>
            </div>
            <div class="plvcrm-csv-stats">
                <div class="plvcrm-csv-stat">
                    <div class="plvcrm-csv-stat-val green" id="stat-created">0</div>
                    <div class="plvcrm-csv-stat-lbl">Created</div>
                </div>
                <div class="plvcrm-csv-stat">
                    <div class="plvcrm-csv-stat-val blue" id="stat-updated">0</div>
                    <div class="plvcrm-csv-stat-lbl">Updated</div>
                </div>
                <div class="plvcrm-csv-stat">
                    <div class="plvcrm-csv-stat-val orange" id="stat-skipped">0</div>
                    <div class="plvcrm-csv-stat-lbl">Skipped</div>
                </div>
                <div class="plvcrm-csv-stat">
                    <div class="plvcrm-csv-stat-val red" id="stat-errors">0</div>
                    <div class="plvcrm-csv-stat-lbl">Errors</div>
                </div>
            </div>
            <p><button class="button" id="btn-cancel-import">Cancel</button></p>
        </div>

        <div id="import-done" class="plvcrm-csv-section" style="display:none;">
            <div class="plvcrm-csv-msg success">
                <strong>Import Complete!</strong>
                <div class="plvcrm-csv-stats" id="final-stats"></div>
            </div>
            <p>
                <button class="button button-primary" id="btn-new-import">Import Another</button>
                <a href="<?php echo admin_url('edit.php?post_type=plover_crm_contact'); ?>" class="button">View Contacts</a>
            </p>
        </div>
    </div>

    <!-- Export Panel -->
    <div class="plvcrm-csv-panel" id="panel-export">
        <div class="plvcrm-csv-section">
            <h3>Export Contacts</h3>
            <div class="plvcrm-csv-row">
                <label><input type="checkbox" id="export-all" checked> Export all contacts</label>
            </div>
            <div id="export-filters" style="display:none;">
                <div class="plvcrm-csv-row">
                    <label>Lists</label>
                    <div class="plvcrm-csv-list">
                        <?php if (!empty($lists)): foreach ($lists as $l): ?>
                                <label><input type="checkbox" name="exp_lists[]" value="<?php echo $l->term_id; ?>"> <?php echo esc_html($l->name); ?></label>
                            <?php endforeach;
                        else: ?><em>No lists</em><?php endif; ?>
                    </div>
                </div>
                <div class="plvcrm-csv-row">
                    <label>Tags</label>
                    <div class="plvcrm-csv-list">
                        <?php if (!empty($tags)): foreach ($tags as $t): ?>
                                <label><input type="checkbox" name="exp_tags[]" value="<?php echo $t->term_id; ?>"> <?php echo esc_html($t->name); ?></label>
                            <?php endforeach;
                        else: ?><em>No tags</em><?php endif; ?>
                    </div>
                </div>
                <div class="plvcrm-csv-row">
                    <label>Date Range</label>
                    <input type="date" id="exp-from"> to <input type="date" id="exp-to">
                </div>
            </div>
            <div class="plvcrm-csv-row">
                <label><input type="checkbox" id="export-custom" checked> Include custom fields</label>
            </div>
            <p><button class="button button-primary" id="btn-export">Export CSV</button></p>
            <div id="export-result"></div>
        </div>
    </div>
</div>

<script>
    jQuery(function($) {
        var nonce = '<?php echo $nonce; ?>';
        var importId = null,
            cancelled = false;

        // Tabs
        $('.plvcrm-csv-tab').click(function() {
            var tab = $(this).data('tab');
            $('.plvcrm-csv-tab').removeClass('active');
            $(this).addClass('active');
            $('.plvcrm-csv-panel').removeClass('active');
            $('#panel-' + tab).addClass('active');
        });

        // Export toggle
        $('#export-all').change(function() {
            $('#export-filters').toggle(!this.checked);
        });

        // Dropzone
        var $drop = $('#dropzone'),
            $file = $('#csv-file');
        $drop.click(function(e) {
            if (e.target !== $file[0]) $file.click();
        });
        $drop.on('dragover dragenter', function(e) {
            e.preventDefault();
            $(this).addClass('dragover');
        });
        $drop.on('dragleave drop', function(e) {
            e.preventDefault();
            $(this).removeClass('dragover');
        });
        $drop.on('drop', function(e) {
            handleFile(e.originalEvent.dataTransfer.files[0]);
        });
        $file.change(function() {
            if (this.files[0]) handleFile(this.files[0]);
        });

        function handleFile(file) {
            if (!file.name.endsWith('.csv')) return alert('Please select a CSV file');
            var fd = new FormData();
            fd.append('action', 'plover_crm_upload_csv');
            fd.append('nonce', nonce);
            fd.append('file', file);
            $drop.html('<p>Uploading...</p>');
            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: fd,
                processData: false,
                contentType: false,
                success: function(r) {
                    if (r.success) showMapping(r.data);
                    else {
                        alert(r.data);
                        resetUpload();
                    }
                },
                error: function() {
                    alert('Upload failed');
                    resetUpload();
                }
            });
        }

        function showMapping(data) {
            importId = data.import_id;
            var $tb = $('#mapping-table tbody').empty(),
                unmapped = [];
            data.headers.forEach(function(h) {
                var sample = data.samples[0] ? (data.samples[0][h] || '').substring(0, 40) : '';
                var mapped = data.mapping[h] || '_skip';
                if (mapped === '_skip') unmapped.push(h);
                var $sel = $('<select>');
                data.fields.forEach(function(f) {
                    $sel.append($('<option>').val(f.value).text(f.label).prop('selected', f.value === mapped));
                });
                $tb.append($('<tr>').append($('<td>').text(h), $('<td>').text(sample), $('<td>').append($sel.data('col', h))));
            });
            if (unmapped.length) {
                $('#unmapped-list').text(unmapped.join(', '));
                $('#unmapped-msg').show();
            } else {
                $('#unmapped-msg').hide();
            }
            $('#import-upload').hide();
            $('#import-mapping').show();
        }

        function resetUpload() {
            $drop.html('<input type="file" id="csv-file" accept=".csv"><p><strong>Drop CSV file here or click to browse</strong></p><p class="description">CSV with headers in first row</p>');
            $('#csv-file').change(function() {
                if (this.files[0]) handleFile(this.files[0]);
            });
            importId = null;
        }

        $('#btn-cancel-map').click(function() {
            if (importId) $.post(ajaxurl, {
                action: 'plover_crm_cancel_import',
                nonce: nonce,
                import_id: importId
            });
            $('#import-mapping').hide();
            $('#import-upload').show();
            resetUpload();
        });

        $('#btn-import').click(function() {
            var mapping = {};
            $('#mapping-table select').each(function() {
                mapping[$(this).data('col')] = $(this).val();
            });
            var lists = [],
                tags = [];
            $('input[name="opt_lists[]"]:checked').each(function() {
                lists.push($(this).val());
            });
            $('input[name="opt_tags[]"]:checked').each(function() {
                tags.push($(this).val());
            });
            cancelled = false;
            $('#import-mapping').hide();
            $('#import-progress').show();
            $('#stat-created, #stat-updated, #stat-skipped, #stat-errors').text('0');
            processBatch(mapping, {
                duplicate: $('#opt-duplicate').val(),
                lists: lists,
                tags: tags
            });
        });

        function processBatch(mapping, opts) {
            if (cancelled) return;
            $.post(ajaxurl, {
                action: 'plover_crm_process_import',
                nonce: nonce,
                import_id: importId,
                mapping: mapping,
                duplicate: opts.duplicate,
                lists: opts.lists,
                tags: opts.tags
            }, function(r) {
                if (r.success) {
                    var d = r.data,
                        pct = Math.round((d.processed / d.total) * 100);
                    $('#progress-fill').css('width', pct + '%');
                    $('#progress-text').text(d.processed + ' / ' + d.total);
                    $('#stat-created').text(d.created);
                    $('#stat-updated').text(d.updated);
                    $('#stat-skipped').text(d.skipped);
                    $('#stat-errors').text(d.errors);
                    if (d.complete) showDone(d);
                    else processBatch(mapping, opts);
                } else {
                    alert(r.data);
                    resetAll();
                }
            });
        }

        function showDone(d) {
            $('#import-progress').hide();
            $('#final-stats').html(
                '<div class="plvcrm-csv-stat"><div class="plvcrm-csv-stat-val green">' + d.created + '</div><div class="plvcrm-csv-stat-lbl">Created</div></div>' +
                '<div class="plvcrm-csv-stat"><div class="plvcrm-csv-stat-val blue">' + d.updated + '</div><div class="plvcrm-csv-stat-lbl">Updated</div></div>' +
                '<div class="plvcrm-csv-stat"><div class="plvcrm-csv-stat-val orange">' + d.skipped + '</div><div class="plvcrm-csv-stat-lbl">Skipped</div></div>' +
                '<div class="plvcrm-csv-stat"><div class="plvcrm-csv-stat-val red">' + d.errors + '</div><div class="plvcrm-csv-stat-lbl">Errors</div></div>'
            );
            $('#import-done').show();
        }

        $('#btn-cancel-import').click(function() {
            cancelled = true;
            $.post(ajaxurl, {
                action: 'plover_crm_cancel_import',
                nonce: nonce,
                import_id: importId
            });
            resetAll();
        });

        $('#btn-new-import').click(function() {
            resetAll();
        });

        function resetAll() {
            $('#import-progress, #import-done, #import-mapping').hide();
            $('#import-upload').show();
            resetUpload();
        }

        // Export
        $('#btn-export').click(function() {
            var $btn = $(this).prop('disabled', true).text('Exporting...');
            var lists = [],
                tags = [];
            $('input[name="exp_lists[]"]:checked').each(function() {
                lists.push($(this).val());
            });
            $('input[name="exp_tags[]"]:checked').each(function() {
                tags.push($(this).val());
            });
            $.post(ajaxurl, {
                action: 'plover_crm_export_csv',
                nonce: nonce,
                all: $('#export-all').is(':checked'),
                lists: lists,
                tags: tags,
                date_from: $('#exp-from').val(),
                date_to: $('#exp-to').val(),
                include_custom: $('#export-custom').is(':checked')
            }, function(r) {
                $btn.prop('disabled', false).text('Export CSV');
                if (r.success) $('#export-result').html('<div class="plvcrm-csv-msg success"><strong>' + r.data.count + ' contacts exported.</strong><br><a href="' + r.data.url + '" class="button" download>Download CSV</a></div>');
                else $('#export-result').html('<div class="plvcrm-csv-msg warning">' + r.data + '</div>');
            });
        });
    });
</script>