<?php

/**
 * VirtualStock Module – Configuration View
 */

use yii\helpers\Html;
use yii\helpers\Url;
use yii\bootstrap4\ActiveForm;

/**
 * @var yii\web\View $this
 * @var PortalPeople\virtualstock\models\ConfigForm $model
 */

$this->title = 'VirtualStock Configuration';
$this->params['breadcrumbs'][] = ['label' => 'Integrations', 'url' => ['/']];
$this->params['breadcrumbs'][] = $this->title;

$testUrl   = Url::to(['/virtualstock/config/test-connection']);
$statusUrl = Url::to(['/virtualstock/config/status']);
$importUrl = Url::to(['/virtualstock/config/import']);

$this->registerJs(<<<JS
    // Safely escape arbitrary text before inserting into HTML context.
    function vsEsc(s) { return $('<span>').text(String(s)).html(); }

    // ---- Test Connection ----
    $('#vs-test-connection-btn').on('click', function () {
        var btn = $(this);
        btn.prop('disabled', true).text('Testing...');

        $.ajax({
            url:      '{$testUrl}',
            type:     'POST',
            data:     $('#vs-config-form').serialize(),
            dataType: 'json',
            success: function (resp) {
                var cls  = resp.success ? 'alert-success' : 'alert-danger';
                var icon = resp.success ? '&#10004;' : '&#10008;';
                $('#vs-connection-result').html('<div class="alert ' + cls + '">' + icon + ' ' + vsEsc(resp.message) + '</div>');
            },
            error: function () {
                $('#vs-connection-result').html('<div class="alert alert-danger">&#10008; Request failed. Check browser console.</div>');
            },
            complete: function () {
                btn.prop('disabled', false).text('Test Connection');
            }
        });
    });

    // ---- Import Status (loaded on page ready, refreshed every 30s) ----
    function loadVsStatus() {
        $.getJSON('{$statusUrl}', function (resp) {
            if (!resp.success) { return; }
            var configured = resp.configured
                ? '<span class="badge badge-success">Configured</span>'
                : '<span class="badge badge-secondary">Not configured</span>';
            var cursor = resp.cursor
                ? '<code>' + vsEsc(resp.cursor) + '</code>'
                : '<em class="text-muted">No cursor stored — next run will fetch from the beginning.</em>';
            $('#vs-status-configured').html(configured);
            $('#vs-status-cursor').html(cursor);
            $('#vs-status-poll-limit').text(resp.pollLimit || '—');
        });
    }
    loadVsStatus();
    setInterval(loadVsStatus, 30000);

    // ---- On-demand Import ----
    function triggerImport(dryRun) {
        var btn  = dryRun ? $('#vs-dry-run-btn') : $('#vs-import-btn');
        var limit = parseInt($('#vs-import-limit').val(), 10) || 0;
        btn.prop('disabled', true).text(dryRun ? 'Running dry run...' : 'Importing...');
        $('#vs-import-result').html('');

        $.ajax({
            url:      '{$importUrl}',
            type:     'POST',
            data:     { dryRun: dryRun ? 1 : 0, limit: limit, _csrf: yii.getCsrfToken() },
            dataType: 'json',
            success: function (resp) {
                var cls  = resp.success ? 'alert-success' : 'alert-danger';
                var icon = resp.success ? '&#10004;' : '&#10008;';
                var msg  = vsEsc(resp.message || '');
                if (resp.success && resp.stats) {
                    msg += ' (found: ' + parseInt(resp.stats.found || 0, 10) +
                           ', imported: ' + parseInt(resp.stats.imported || 0, 10) +
                           ', skipped: ' + parseInt(resp.stats.skipped || 0, 10) + ')';
                }
                $('#vs-import-result').html('<div class="alert ' + cls + '">' + icon + ' ' + msg + '</div>');
                if (resp.success) { loadVsStatus(); }
            },
            error: function () {
                $('#vs-import-result').html('<div class="alert alert-danger">&#10008; Import request failed. Check browser console.</div>');
            },
            complete: function () {
                btn.prop('disabled', false).text(dryRun ? 'Dry Run' : 'Run Import Now');
            }
        });
    }

    $('#vs-dry-run-btn').on('click', function () { triggerImport(true); });
    $('#vs-import-btn').on('click',  function () { triggerImport(false); });

    // ---- Queue component field visibility ----
    function toggleQueueComponent() {
        if ($('#configform-usequeue').is(':checked')) {
            $('#vs-queue-component-wrap').show();
        } else {
            $('#vs-queue-component-wrap').hide();
        }
    }
    toggleQueueComponent();
    $('#configform-usequeue').on('change', toggleQueueComponent);
JS
);
?>

<div class="virtualstock-config">

    <h1><?= Html::encode($this->title) ?></h1>

    <?php if (Yii::$app->session->hasFlash('success')) : ?>
        <div class="alert alert-success"><?= Html::encode(Yii::$app->session->getFlash('success')) ?></div>
    <?php endif; ?>
    <?php if (Yii::$app->session->hasFlash('error')) : ?>
        <div class="alert alert-danger"><?= Html::encode(Yii::$app->session->getFlash('error')) ?></div>
    <?php endif; ?>

    <?php $form = ActiveForm::begin([
        'id'     => 'vs-config-form',
        'action' => ['/virtualstock/config/index'],
    ]); ?>

    <!-- ================================================================ -->
    <!-- Card 1: API Connection Settings                                   -->
    <!-- ================================================================ -->
    <div class="card mb-4">
        <div class="card-header">API Connection Settings</div>
        <div class="card-body">

            <?= $form->field($model, 'enabled')->checkbox() ?>

            <?= $form->field($model, 'environment')->dropDownList([
                'sandbox'    => 'Sandbox (Test)',
                'production' => 'Production (Live)',
            ])->hint($model->getAttributeHint('environment')) ?>

            <?= $form->field($model, 'apiEndpoint')->textInput([
                'placeholder' => 'https://api.virtualstock.com/… (leave blank to use environment default)',
                'autocomplete' => 'off',
            ])->hint($model->getAttributeHint('apiEndpoint')) ?>

            <?= $form->field($model, 'apiKey')->textInput([
                'placeholder'  => 'API key provided by VirtualStock',
                'autocomplete' => 'off',
            ])->hint($model->getAttributeHint('apiKey')) ?>

            <?= $form->field($model, 'apiSecret')->passwordInput([
                'placeholder'  => 'API secret (stored encrypted)',
                'autocomplete' => 'new-password',
            ])->hint($model->getAttributeHint('apiSecret')) ?>

        </div>
    </div>

    <!-- ================================================================ -->
    <!-- Card 2: Import & Order Settings                                   -->
    <!-- ================================================================ -->
    <div class="card mb-4">
        <div class="card-header">Import &amp; Order Settings</div>
        <div class="card-body">

            <?= $form->field($model, 'pollLimit')->textInput([
                'type' => 'number',
                'min'  => 1,
                'max'  => 500,
            ])->hint($model->getAttributeHint('pollLimit')) ?>

            <?= $form->field($model, 'orderNumberPrefix')->textInput([
                'placeholder' => 'VS-',
            ])->hint($model->getAttributeHint('orderNumberPrefix')) ?>

        </div>
    </div>

    <!-- ================================================================ -->
    <!-- Card 3: Advanced Settings                                         -->
    <!-- ================================================================ -->
    <div class="card mb-4">
        <div class="card-header">Advanced Settings</div>
        <div class="card-body">

            <?= $form->field($model, 'requestTimeout')->textInput([
                'type' => 'number',
                'min'  => 5,
                'max'  => 120,
            ])->hint($model->getAttributeHint('requestTimeout')) ?>

            <?= $form->field($model, 'debug')->checkbox()->hint('Logs all API requests and responses to the application log.') ?>

        </div>
    </div>

    <!-- ================================================================ -->
    <!-- Card 4: Queue Settings                                            -->
    <!-- ================================================================ -->
    <div class="card mb-4">
        <div class="card-header">Queue Settings</div>
        <div class="card-body">

            <?= $form->field($model, 'useQueue')->checkbox()->hint($model->getAttributeHint('useQueue')) ?>

            <div id="vs-queue-component-wrap">
                <?= $form->field($model, 'queueComponent')->textInput([
                    'placeholder' => 'virtualstock-queue',
                ])->hint($model->getAttributeHint('queueComponent')) ?>

                <div class="alert alert-info py-2 px-3 small">
                    <strong>Setup required:</strong> Add a <code>virtualstock-queue</code> component to your
                    application config using <code>portalpeople/ngauge-queue</code>. Example:
                    <pre class="mb-0 mt-2 small">'components' => [
    'virtualstock-queue' => [
        'class' => \PortalPeople\NGaugeQueue\Queue::class,
    ],
]</pre>
                </div>
            </div>

        </div>
    </div>

    <!-- ================================================================ -->
    <!-- Save + Test actions                                               -->
    <!-- ================================================================ -->
    <div class="form-group mb-4">
        <?= Html::submitButton('Save Configuration', ['class' => 'btn btn-primary mr-2']) ?>
        <?= Html::button('Test Connection', [
            'id'    => 'vs-test-connection-btn',
            'class' => 'btn btn-secondary',
            'type'  => 'button',
        ]) ?>
    </div>

    <div id="vs-connection-result" class="mb-4"></div>

    <?php ActiveForm::end(); ?>

    <!-- ================================================================ -->
    <!-- Card 4: Module Status                                             -->
    <!-- ================================================================ -->
    <div class="card mb-4 border-info">
        <div class="card-header bg-info text-white">Module Status</div>
        <div class="card-body">
            <table class="table table-sm table-borderless mb-0">
                <tbody>
                    <tr>
                        <th style="width:200px">Status</th>
                        <td id="vs-status-configured"><span class="text-muted">Loading…</span></td>
                    </tr>
                    <tr>
                        <th>Import Cursor</th>
                        <td id="vs-status-cursor"><span class="text-muted">Loading…</span></td>
                    </tr>
                    <tr>
                        <th>Poll Limit</th>
                        <td id="vs-status-poll-limit"><span class="text-muted">Loading…</span></td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>

    <!-- ================================================================ -->
    <!-- Card 5: On-demand Import                                          -->
    <!-- ================================================================ -->
    <div class="card mb-4">
        <div class="card-header">On-demand Order Import</div>
        <div class="card-body">
            <p class="text-muted small mb-3">
                Trigger an immediate import run. Use <strong>Dry Run</strong> to preview what would be imported
                without making any changes. Orders are normally imported automatically via the console command
                <code>./yii virtualstock/order-import/run</code>.
            </p>
            <div class="form-inline mb-3">
                <label class="mr-2" for="vs-import-limit">Limit</label>
                <?= Html::input('number', 'vs-import-limit', (string) $model->pollLimit, [
                    'id'    => 'vs-import-limit',
                    'class' => 'form-control form-control-sm mr-3',
                    'min'   => 1,
                    'max'   => 500,
                    'style' => 'width:90px',
                ]) ?>
                <?= Html::button('Dry Run', [
                    'id'    => 'vs-dry-run-btn',
                    'class' => 'btn btn-outline-secondary btn-sm mr-2',
                    'type'  => 'button',
                ]) ?>
                <?= Html::button('Run Import Now', [
                    'id'    => 'vs-import-btn',
                    'class' => 'btn btn-warning btn-sm',
                    'type'  => 'button',
                ]) ?>
            </div>
            <div id="vs-import-result"></div>
        </div>
    </div>

    <!-- ================================================================ -->
    <!-- Card 6: Notes                                                     -->
    <!-- ================================================================ -->
    <div class="card border-secondary">
        <div class="card-header bg-secondary text-white">Notes</div>
        <div class="card-body">
            <ul class="mb-0">
                <li>The <strong>API Key</strong> and <strong>API Secret</strong> are provided by VirtualStock during onboarding.</li>
                <li>Use the <strong>Sandbox</strong> environment for testing. Switch to <strong>Production</strong> only when ready to go live.</li>
                <li>The <strong>Import Cursor</strong> tracks the last-fetched timestamp. Clearing it will re-import all orders from the beginning on the next run.</li>
                <li>The console command <code>./yii virtualstock/order-import/run</code> should be scheduled via cron for automated imports.</li>
                <li>Set <strong>Debug Logging</strong> only in development — it logs full request/response payloads which may contain sensitive data.</li>
            </ul>
        </div>
    </div>

</div>
