<div class="row wrapper border-bottom white-bg page-heading pjBaseTheme-<?php echo $tpl['option_arr']['o_base_theme'];?>">
    <div class="col-sm-12">
        <div class="row">
            <div class="col-lg-9 col-md-8 col-sm-6">
                <h2><?php __('import_title'); ?></h2>
            </div>
        </div><!-- /.row -->
        <p class="m-b-none"><i class="fa fa-info-circle"></i> <?php __('import_desc'); ?></p>
    </div>
</div>
<div class="row wrapper wrapper-content animated fadeInRight">
    <div class="col-lg-12">

        <?php if (!empty($tpl['import_error'])) { ?>
            <div class="alert alert-danger">
                <i class="fa fa-exclamation-triangle m-r-xs"></i>
                <strong><?php __('import_failed'); ?></strong> <?php echo pjSanitize::html($tpl['import_error']); ?>
            </div>
        <?php } ?>

        <?php if (!empty($tpl['results'])) {
            // Server-rendered results (non-JavaScript fallback path).
            $s = $tpl['summary'];
            ?>
            <div class="alert <?php echo $s['failed'] > 0 ? 'alert-warning' : 'alert-success'; ?>">
                <i class="fa fa-check m-r-xs"></i>
                <strong><?php __('import_finished'); ?></strong>
                <?php echo (int) $s['total']; ?> <?php __('import_processed'); ?> &mdash;
                <strong><?php echo (int) $s['created']; ?></strong> <?php __('import_created'); ?>,
                <strong><?php echo (int) $s['updated']; ?></strong> <?php __('import_updated'); ?>,
                <strong><?php echo (int) $s['failed']; ?></strong> <?php __('import_skipped'); ?>.
            </div>
        <?php } ?>

        <div class="ibox">
            <div class="ibox-title">
                <h5><i class="fa fa-upload m-r-xs"></i> <?php __('import_file_label'); ?></h5>
            </div>
            <div class="ibox-content">

                <div id="pjImportAjaxError" class="alert alert-danger" style="display:none;">
                    <i class="fa fa-exclamation-triangle m-r-xs"></i> <span></span>
                </div>

                <form id="pjImportForm" action="<?php echo $_SERVER['PHP_SELF']; ?>?controller=pjAdminProducts&amp;action=pjActionImportProduct" method="post" enctype="multipart/form-data">
                    <input type="hidden" name="csrf_token" value="<?php echo pjAppController::getCsrfToken(); ?>">
                    <input type="hidden" name="product_import" value="1" />

                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label class="control-label font-bold" for="pjImportFile"><?php __('import_file_label'); ?></label>
                                <input type="file" id="pjImportFile" name="csv_file" accept=".csv" class="form-control" required />
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label class="control-label font-bold" for="pjImportDelimiter"><?php __('import_delimiter_label'); ?></label>
                                <select name="csv_delimiter" id="pjImportDelimiter" class="form-control">
                                    <option value="auto"><?php __('import_delimiter_auto'); ?></option>
                                    <option value=","><?php __('import_delimiter_comma'); ?></option>
                                    <option value=";"><?php __('import_delimiter_semicolon'); ?></option>
                                </select>
                                <span class="help-block m-t-xs m-b-none" style="font-size:12px;"><i class="fa fa-info-circle"></i> <?php __('import_delimiter_hint'); ?></span>
                            </div>
                        </div>
                    </div>

                    <div class="hr-line-dashed"></div>

                    <div class="form-group m-b-none">
                        <button type="submit" id="pjImportSubmit" class="btn btn-primary"><i class="fa fa-upload m-r-xs"></i> <?php __('import_btn_upload'); ?></button>
                        <a href="<?php echo $_SERVER['PHP_SELF']; ?>?controller=pjAdminProducts&amp;action=pjActionIndex" class="btn btn-white"><?php __('import_btn_cancel'); ?></a>
                    </div>
                </form>
            </div>
        </div>

        <!-- results: rendered in the same datagrid the product list uses -->
        <div id="pjImportResultsWrap" class="ibox" style="display:none;">
            <div class="ibox-content">
                <div id="pjImportLiveSummary" class="m-b-sm"></div>
                <div id="pjImportGrid" class="pj-products-list-grid"></div>
                <a href="<?php echo $_SERVER['PHP_SELF']; ?>?controller=pjAdminProducts&amp;action=pjActionIndex" class="btn btn-primary m-t-sm"><i class="fa fa-list m-r-xs"></i> <?php __('import_back'); ?></a>
            </div>
        </div>

        <!-- CSV format help -->
        <div class="ibox">
            <div class="ibox-title">
                <h5><i class="fa fa-info-circle m-r-xs"></i> <?php __('import_format_title'); ?></h5>
                <div class="ibox-tools">
                    <a href="<?php echo $_SERVER['PHP_SELF']; ?>?controller=pjAdminProducts&amp;action=pjActionSampleCsv" class="btn btn-sm btn-primary"><i class="fa fa-download m-r-xs"></i> <?php __('import_sample_download'); ?></a>
                </div>
            </div>
            <div class="ibox-content">
                <p class="text-muted"><?php __('import_format_intro'); ?></p>

                <div class="alert alert-warning m-b-md" style="margin-top:5px;">
                    <i class="fa fa-asterisk m-r-xs"></i> <?php __('import_help_required'); ?>
                </div>

                <div class="row">
                    <div class="col-md-6">
                        <ul class="m-b-none">
                            <li><?php __('import_help_name'); ?></li>
                            <li><?php __('import_help_sku'); ?></li>
                            <li><?php __('import_help_status'); ?></li>
                            <li><?php __('import_help_categories'); ?></li>
                            <li><?php __('import_help_flags'); ?></li>
                            <li><?php __('import_help_desc'); ?></li>
                            <li><?php __('import_help_digital'); ?></li>
                        </ul>
                    </div>
                    <div class="col-md-6">
                        <ul class="m-b-none">
                            <li><?php __('import_help_price'); ?></li>
                            <li><?php __('import_help_extras'); ?></li>
                            <li><?php __('import_help_attrs'); ?></li>
                            <li><?php __('import_help_photos'); ?></li>
                            <li><?php __('import_help_similar'); ?></li>
                        </ul>
                    </div>
                </div>

                <div class="hr-line-dashed"></div>

                <p class="font-bold m-b-xs"><i class="fa fa-lightbulb-o m-r-xs"></i> <?php __('import_help_notes_title'); ?></p>
                <ul class="text-muted m-b-none">
                    <li>
                        <?php __('import_help_sample'); ?>
                        <a href="<?php echo $_SERVER['PHP_SELF']; ?>?controller=pjAdminProducts&amp;action=pjActionSampleCsv"><i class="fa fa-download"></i> <?php __('import_sample_download'); ?></a>
                    </li>
                    <li><?php __('import_help_note_validation'); ?></li>
                    <li><?php __('import_help_note_separator'); ?></li>
                    <li><?php __('import_help_note_images'); ?></li>
                    <li><?php __('import_help_ignored'); ?></li>
                </ul>
            </div>
        </div>

    </div>
</div>

<!-- progress modal (vanilla, no Bootstrap/jQuery dependency) -->
<div id="pjImportModal" style="display:none;position:fixed;inset:0;z-index:20000;background:rgba(0,0,0,.45);">
    <div style="max-width:520px;margin:12% auto 0;background:#fff;border-radius:6px;box-shadow:0 10px 40px rgba(0,0,0,.3);overflow:hidden;">
        <div style="padding:16px 20px;border-bottom:1px solid #e7eaec;">
            <h3 id="pjImportModalTitle" style="margin:0;font-size:18px;"></h3>
        </div>
        <div style="padding:20px;">
            <p id="pjImportProgressStatus" style="margin:0 0 10px;"></p>
            <div class="progress" style="height:26px;margin:0 0 10px;background:#f3f4f6;border-radius:4px;overflow:hidden;">
                <div id="pjImportProgressBar" style="width:0%;height:26px;line-height:26px;text-align:center;color:#fff;font-weight:600;background:#ff6600;transition:width .25s ease;">0%</div>
            </div>
            <p id="pjImportModalSub" class="text-muted" style="margin:0;font-size:12px;"></p>
        </div>
    </div>
</div>

<script type="text/javascript">
(function () {
    var L = {
        title:      <?php x__encode('import_progress_title'); ?>,
        preparing:  <?php x__encode('import_progress_preparing'); ?>,
        status:     <?php x__encode('import_progress_status'); ?>,
        finished:   <?php x__encode('import_finished'); ?>,
        processed:  <?php x__encode('import_processed'); ?>,
        created:    <?php x__encode('import_created'); ?>,
        updated:    <?php x__encode('import_updated'); ?>,
        skipped:    <?php x__encode('import_skipped'); ?>,
        st_created: <?php x__encode('import_state_created'); ?>,
        st_updated: <?php x__encode('import_state_updated'); ?>,
        st_skipped: <?php x__encode('import_state_skipped'); ?>,
        err:        <?php x__encode('import_failed'); ?>
    };
    var COL = {
        row:     <?php x__encode('import_col_row'); ?>,
        sku:     <?php x__encode('import_col_sku'); ?>,
        product: <?php x__encode('import_col_product'); ?>,
        result:  <?php x__encode('import_col_result'); ?>,
        details: <?php x__encode('import_col_details'); ?>
    };
    // Fall back to sensible defaults if a label key has not been applied to the
    // database yet (__() returns the raw key when a label is missing).
    function pick(v, key, def) { return (!v || v === key) ? def : v; }
    L.title     = pick(L.title, "import_progress_title", "Importing products");
    L.preparing = pick(L.preparing, "import_progress_preparing", "Preparing import, please wait...");
    L.status    = (L.status && L.status.indexOf("{processed}") !== -1) ? L.status : "{processed} of {total} rows processed";
    L.finished  = pick(L.finished, "import_finished", "Import finished:");
    L.processed = pick(L.processed, "import_processed", "rows processed");
    L.created   = pick(L.created, "import_created", "created");
    L.updated   = pick(L.updated, "import_updated", "updated");
    L.skipped   = pick(L.skipped, "import_skipped", "skipped");
    L.st_created = pick(L.st_created, "import_state_created", "Created");
    L.st_updated = pick(L.st_updated, "import_state_updated", "Updated");
    L.st_skipped = pick(L.st_skipped, "import_state_skipped", "Skipped");

    var csrf    = "<?php echo pjAppController::getCsrfToken(); ?>";
    var baseUrl = "<?php echo $_SERVER['PHP_SELF']; ?>?controller=pjAdminProducts&action=pjActionImportProductBatch";
    var gridUrl = "<?php echo $_SERVER['PHP_SELF']; ?>?controller=pjAdminProducts&action=pjActionGetImportResult";

    function $(id) { return document.getElementById(id); }
    function esc(s) { var d = document.createElement("div"); d.textContent = (s == null ? "" : String(s)); return d.innerHTML; }

    function showModal(show) { $("pjImportModal").style.display = show ? "block" : "none"; }

    function setProgress(processed, total) {
        var pct = total > 0 ? Math.round(Math.min(processed, total) / total * 100) : 0;
        if (pct > 100) { pct = 100; }
        var bar = $("pjImportProgressBar");
        bar.style.width = pct + "%";
        bar.textContent = pct + "%";
        $("pjImportProgressStatus").innerHTML = "<strong>" +
            esc(L.status.replace("{processed}", processed).replace("{total}", total)) + "</strong>";
    }

    // Smooth counter: the server still processes in batches (efficient and safe
    // for 10000+ rows), but the displayed number advances a fixed amount each
    // animation frame so it visibly counts up. The per-frame step depends on the
    // TOTAL (not on how fast batches arrive), so small imports count 1, 2, 3 ...
    // one-by-one, while very large imports still finish within a few seconds.
    var _shown = 0, _target = 0, _total = 0, _step = 1, _raf = false, _onArrive = null;
    var _hasRaf = (typeof window.requestAnimationFrame === "function");
    function _schedule() { if (_hasRaf) { window.requestAnimationFrame(_tick); } else { setTimeout(_tick, 16); } }
    function _arrive() { if (_onArrive) { var f = _onArrive; _onArrive = null; f(); } }
    function _tick() {
        if (_shown < _target) {
            _shown += _step;
            if (_shown > _target) { _shown = _target; }
            setProgress(_shown, _total);
            _schedule();
        } else {
            _raf = false;
            setProgress(_target, _total);
            _arrive();
        }
    }
    // ~ANIM_FRAMES frames to cover the whole bar at most (≈ that many * 16ms).
    // Up to ANIM_FRAMES products => step 1 => every number is shown.
    var ANIM_FRAMES = 300;
    function animateProgress(target, total, onArrive) {
        _total = total;
        _step = Math.max(1, Math.ceil((total || 1) / ANIM_FRAMES));
        _target = target;
        if (target < _shown) { _shown = target; } // never count backwards on a reset
        if (onArrive) { _onArrive = onArrive; }
        if (_shown >= _target) { _arrive(); return; }
        if (!_raf) { _raf = true; _schedule(); }
    }
    function resetProgress(total) {
        _shown = 0; _target = 0; _total = total || 0; _step = 1; _raf = false; _onArrive = null;
        setProgress(0, _total);
    }

    function showSummary(s) {
        if (!s) { return; }
        var cls = (s.failed > 0) ? "alert-warning" : "alert-success";
        $("pjImportLiveSummary").innerHTML = "<div class='alert " + cls + "' style='margin-bottom:0;'>" +
            "<i class='fa fa-check m-r-xs'></i> <strong>" + esc(L.finished) + "</strong> " +
            esc(s.total) + " " + esc(L.processed) + " &mdash; <strong>" + esc(s.created) + "</strong> " +
            esc(L.created) + ", <strong>" + esc(s.updated) + "</strong> " + esc(L.updated) +
            ", <strong>" + esc(s.failed) + "</strong> " + esc(L.skipped) + ".</div>";
    }

    function showError(msg) {
        showModal(false);
        var box = $("pjImportAjaxError");
        box.querySelector("span").textContent = msg || L.err;
        box.style.display = "block";
        $("pjImportSubmit").disabled = false;
    }

    // ----- the same datagrid component the product list uses -----
    var gridInited = false;
    function stateRenderer(val) {
        var badge, label;
        if (val === "created") { badge = "label-primary"; label = L.st_created; }
        else if (val === "updated") { badge = "label-info"; label = L.st_updated; }
        else { badge = "label-danger"; label = L.st_skipped; }
        return "<span class='label " + badge + "'>" + esc(label) + "</span>";
    }
    function showResultGrid() {
        $("pjImportResultsWrap").style.display = "block";
        var jq = window.jQuery;
        if (!jq || !jq.fn || !jq.fn.datagrid) { return; }
        if (gridInited) {
            var content = jq("#pjImportGrid").datagrid("option", "content");
            var rc = (content && content.rowCount) ? content.rowCount : 25;
            jq("#pjImportGrid").datagrid("load", gridUrl, "line", "ASC", 1, rc);
            return;
        }
        gridInited = true;
        jq("#pjImportGrid").datagrid({
            columns: [
                { text: COL.row,     type: "text", sortable: true,  editable: false },
                { text: COL.sku,     type: "text", sortable: true,  editable: false },
                { text: COL.product, type: "text", sortable: true,  editable: false },
                { text: COL.result,  type: "text", sortable: true,  editable: false, renderer: stateRenderer },
                { text: COL.details, type: "text", sortable: false, editable: false }
            ],
            dataUrl: gridUrl,
            dataType: "json",
            fields: ["line", "sku", "name", "state", "message"],
            paginator: { gotoPage: true, paginate: true, total: true, rowCount: true }
        });
    }

    function sendBatch(offset, file) {
        var fd = new FormData();
        fd.append("offset", offset);
        fd.append("csrf_token", csrf);
        if (offset === 0 && file) {
            fd.append("csv_file", file);
            var sel = $("pjImportDelimiter");
            fd.append("csv_delimiter", sel ? sel.value : "auto");
        }

        fetch(baseUrl, {
            method: "POST",
            body: fd,
            credentials: "same-origin",
            headers: { "X-Requested-With": "XMLHttpRequest" }
        }).then(function (resp) {
            return resp.text().then(function (txt) {
                var d;
                try { d = JSON.parse(txt); } catch (e) { throw new Error(txt.slice(0, 200)); }
                return d;
            });
        }).then(function (d) {
            if (!d || !d.status) { showError(L.err); return; }
            if (d.status === "ERR") { showError(d.text); return; }

            animateProgress(d.processed, d.total);

            if (d.status === "OK") {
                sendBatch(d.offset, null);
            } else if (d.status === "DONE") {
                showSummary(d.summary);
                showResultGrid();
                // Let the counter finish reaching the total, then close.
                animateProgress(d.total, d.total, function () {
                    setTimeout(function () {
                        showModal(false);
                        $("pjImportSubmit").disabled = false;
                    }, 350);
                });
            }
        }).catch(function (e) {
            showError((e && e.message) ? e.message : L.err);
        });
    }

    function start() {
        var form = $("pjImportForm");
        if (!form) { return; }
        form.addEventListener("submit", function (e) {
            var input = $("pjImportFile");
            if (!input || !input.files || !input.files.length) { return; } // let native required-validation run
            e.preventDefault();

            // reset UI
            $("pjImportAjaxError").style.display = "none";
            $("pjImportResultsWrap").style.display = "none";
            $("pjImportLiveSummary").innerHTML = "";
            var bar = $("pjImportProgressBar");
            bar.style.background = "#ff6600";
            bar.style.width = "0%";
            bar.textContent = "0%";
            resetProgress(0);
            $("pjImportModalTitle").textContent = L.title;
            $("pjImportProgressStatus").innerHTML = "<strong>" + esc(L.preparing) + "</strong>";
            $("pjImportModalSub").textContent = input.files[0].name;
            $("pjImportSubmit").disabled = true;
            showModal(true);

            sendBatch(0, input.files[0]);
        });
    }

    if (document.readyState === "loading") {
        document.addEventListener("DOMContentLoaded", start);
    } else {
        start();
    }
})();
</script>
