<?php

use yii\helpers\Html;
use yii\helpers\Url;

$this->title = 'Zupa Import';
$previewUrl   = Url::to(['/zupa/import/preview']);
?>

<!-- Preview modal -->
<div class="modal fade" id="preview-modal" tabindex="-1" role="dialog" aria-labelledby="preview-modal-label" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-scrollable" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="preview-modal-label">Preview</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body p-0">
                <pre id="preview-body" class="mb-0 p-3" style="background:#f8f9fa;font-size:.8rem;max-height:70vh;overflow:auto;white-space:pre-wrap;word-break:break-word;">Loading…</pre>
            </div>
        </div>
    </div>
</div>

<div class="card mb-2 text-center sticky-top page-title">
    <div class="card-header d-flex justify-content-between align-items-center">
        <span>Zupa — Import Orders from Inbox</span>
        <?= Html::a('Download 10 from FTP', ['/zupa/import/download'], [
            'class'  => 'btn btn-sm btn-outline-secondary',
            'data'   => ['confirm' => 'Fetch up to 10 files from the Zupa FTP now?'],
            'method' => 'post',
        ]) ?>
    </div>
</div>

<?php foreach (Yii::$app->session->getAllFlashes() as $type => $messages): ?>
    <?php foreach ((array) $messages as $message): ?>
        <div class="alert alert-<?= Html::encode($type) ?> mt-2"><?= Html::encode($message) ?></div>
    <?php endforeach; ?>
<?php endforeach; ?>

<?php if ($result !== null): ?>
    <div class="alert alert-<?= $result['failed'] === 0 ? 'success' : 'warning' ?> mt-2">
        <strong>Import complete:</strong>
        <?= (int) $result['processed'] ?> file(s) processed,
        <?= (int) $result['created'] ?> order(s) created,
        <?= (int) $result['failed'] ?> failed.
        <?php if (!empty($result['errors'])): ?>
            <ul class="mb-0 mt-2">
                <?php foreach ($result['errors'] as $err): ?>
                    <li><?= Html::encode($err['file']) ?>: <?= Html::encode($err['error']) ?></li>
                <?php endforeach; ?>
            </ul>
        <?php endif; ?>
    </div>
<?php endif; ?>

<?php if (empty($files)): ?>
    <div class="alert alert-info mt-3">No XML files found in the inbox.</div>
<?php else: ?>
    <?= Html::beginForm(['/zupa/import/index'], 'post', ['id' => 'zupa-import-form']) ?>
    <div class="card mt-2">
        <div class="card-body p-0">
            <table class="table table-sm table-hover mb-0">
                <thead class="thead-light">
                    <tr>
                        <th style="width:42px;" class="text-center">
                            <input type="checkbox" id="select-all" title="Select / deselect all">
                        </th>
                        <th>Filename</th>
                        <th class="text-right" style="width:100px;">Size</th>
                        <th style="width:160px;">Modified</th>
                        <th style="width:60px;"></th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($files as $file): ?>
                    <tr>
                        <td class="text-center">
                            <input type="checkbox" name="files[]"
                                   value="<?= Html::encode($file['name']) ?>"
                                   class="file-check">
                        </td>
                        <td><?= Html::encode($file['name']) ?></td>
                        <td class="text-right"><?= Yii::$app->formatter->asShortSize($file['size'], 1) ?></td>
                        <td><?= date('d M Y H:i', $file['modified']) ?></td>
                        <td class="text-center">
                            <button type="button" class="btn btn-sm btn-outline-info preview-btn"
                                    data-file="<?= Html::encode($file['name']) ?>"
                                    title="Preview">
                                <i class="fa fa-eye"></i>
                            </button>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        <div class="card-footer d-flex justify-content-between align-items-center">
            <span class="text-muted small" id="selected-count">0 files selected</span>
            <?= Html::submitButton('Import Selected', [
                'class' => 'btn btn-primary',
                'id'    => 'import-btn',
            ]) ?>
        </div>
    </div>
    <?= Html::endForm() ?>

    <script>
    (function () {
        var previewUrl = <?= json_encode($previewUrl) ?>;
        var modal      = document.getElementById('preview-modal');
        var modalTitle = document.getElementById('preview-modal-label');
        var modalBody  = document.getElementById('preview-body');

        document.querySelectorAll('.preview-btn').forEach(function (btn) {
            btn.addEventListener('click', function () {
                var file = btn.getAttribute('data-file');
                modalTitle.textContent = file;
                modalBody.textContent  = 'Loading…';
                $(modal).modal('show');

                fetch(previewUrl + '?file=' + encodeURIComponent(file))
                    .then(function (r) { return r.json(); })
                    .then(function (data) {
                        modalBody.textContent = JSON.stringify(data, null, 2);
                    })
                    .catch(function (e) {
                        modalBody.textContent = 'Error: ' + e.message;
                    });
            });
        });

        var selectAll = document.getElementById('select-all');
        var checks    = document.querySelectorAll('.file-check');
        var countEl   = document.getElementById('selected-count');
        var importBtn = document.getElementById('import-btn');

        function updateCount() {
            var n = document.querySelectorAll('.file-check:checked').length;
            countEl.textContent = n + ' file' + (n !== 1 ? 's' : '') + ' selected';
            importBtn.disabled  = (n === 0);
        }

        selectAll.addEventListener('change', function () {
            checks.forEach(function (c) { c.checked = selectAll.checked; });
            updateCount();
        });

        checks.forEach(function (c) {
            c.addEventListener('change', function () {
                selectAll.checked = (document.querySelectorAll('.file-check:checked').length === checks.length);
                updateCount();
            });
        });

        updateCount();
    }());
    </script>
<?php endif; ?>
