<?php
/**
 * VirtualStock Module – API Explorer View
 */

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

/**
 * @var yii\web\View $this
 */

$this->title = 'VirtualStock API Explorer';
$this->params['breadcrumbs'][] = ['label' => 'Integrations', 'url' => ['/']];
$this->params['breadcrumbs'][] = ['label' => 'VirtualStock', 'url' => ['/virtualstock/config/index']];
$this->params['breadcrumbs'][] = $this->title;

$urls = [
    'getOrders'      => Url::to(['/virtualstock/config/api-get-orders']),
    'getOrder'       => Url::to(['/virtualstock/config/api-get-order']),
    'getItem'        => Url::to(['/virtualstock/config/api-get-item']),
    'listCustomers'  => Url::to(['/virtualstock/config/api-list-customers']),
];

$this->registerCss(<<<CSS
.vs-explorer-card .card-header { font-weight: 600; }
.vs-result-pre {
    background: #1e1e1e;
    color: #d4d4d4;
    border-radius: 4px;
    padding: 12px;
    font-size: 12px;
    max-height: 400px;
    overflow: auto;
    white-space: pre-wrap;
    word-break: break-all;
    display: none;
}
.vs-result-pre.visible { display: block; }
.vs-result-pre.is-error { border-left: 3px solid #dc3545; }
.vs-result-pre.is-success { border-left: 3px solid #28a745; }
.vs-spinner { display: none; }
.vs-running .vs-spinner { display: inline-block; }
CSS
);

$this->registerJs(<<<JS
var VS_CSRF = yii.getCsrfToken();

function vsRun(btn, url, data, resultId) {
    var card  = btn.closest('.vs-explorer-card');
    var pre   = $('#' + resultId);
    var badge = card.find('.vs-status-badge');

    card.addClass('vs-running');
    btn.prop('disabled', true);
    pre.removeClass('visible is-error is-success').text('');
    badge.text('').removeClass('badge badge-success badge-danger');

    data['_csrf'] = VS_CSRF;

    $.ajax({
        url:      url,
        type:     'POST',
        data:     data,
        dataType: 'json',
        success: function (resp) {
            if (resp.success) {
                pre.text(JSON.stringify(resp.data !== undefined ? resp.data : resp, null, 2))
                   .addClass('visible is-success');
                badge.text('OK').addClass('badge badge-success');
            } else {
                pre.text(resp.message || JSON.stringify(resp, null, 2))
                   .addClass('visible is-error');
                badge.text('Error').addClass('badge badge-danger');
            }
        },
        error: function (xhr) {
            pre.text('HTTP ' + xhr.status + ': ' + (xhr.responseText || 'Request failed'))
               .addClass('visible is-error');
            badge.text('Error').addClass('badge badge-danger');
        },
        complete: function () {
            card.removeClass('vs-running');
            btn.prop('disabled', false);
        }
    });
}

// ---- Get Orders Updated Since ----
$('#vs-get-orders-btn').on('click', function () {
    vsRun($(this), '{$urls['getOrders']}', {
        cursor: $('#vs-go-cursor').val().trim(),
        limit:  parseInt($('#vs-go-limit').val(), 10) || 100
    }, 'vs-get-orders-result');
});

// ---- Get Single Order ----
$('#vs-get-order-btn').on('click', function () {
    vsRun($(this), '{$urls['getOrder']}', {
        orderNo: $('#vs-order-no').val().trim()
    }, 'vs-get-order-result');
});

// ---- Get Item ----
$('#vs-get-item-btn').on('click', function () {
    vsRun($(this), '{$urls['getItem']}', {
        itemId: $('#vs-item-id').val().trim()
    }, 'vs-get-item-result');
});

// ---- List Customers ----
$('#vs-list-customers-btn').on('click', function () {
    vsRun($(this), '{$urls['listCustomers']}', {
        filters: $('#vs-customers-filters').val().trim() || '{}'
    }, 'vs-list-customers-result');
});
JS
);
?>

<div class="virtualstock-api-explorer">

    <div class="d-flex align-items-center mb-3">
        <h1 class="mb-0 mr-3"><?= Html::encode($this->title) ?></h1>
        <?= Html::a('&larr; Back to Config', ['/virtualstock/config/index'], ['class' => 'btn btn-sm btn-outline-secondary']) ?>
    </div>

    <p class="text-muted mb-4">
        Run live API calls directly against the configured VirtualStock endpoint. Results are returned as raw JSON.
    </p>

    <!-- ================================================================ -->
    <!-- 1. Get Orders Updated Since                                       -->
    <!-- ================================================================ -->
    <div class="card mb-4 vs-explorer-card">
        <div class="card-header d-flex justify-content-between align-items-center">
            <span>Get Orders Updated Since <code class="ml-2 font-weight-normal text-muted small">GET orders/</code></span>
            <span class="vs-status-badge"></span>
        </div>
        <div class="card-body">
            <p class="text-muted small mb-3">
                Fetches a page of orders. Leave <em>Cursor</em> blank to fetch from the beginning.
            </p>
            <div class="form-row align-items-end mb-3">
                <div class="col-sm-6">
                    <?= Html::label('Cursor (updatedSince)', 'vs-go-cursor', ['class' => 'col-form-label col-form-label-sm']) ?>
                    <?= Html::input('text', 'vs-go-cursor', '', [
                        'id'          => 'vs-go-cursor',
                        'class'       => 'form-control form-control-sm',
                        'placeholder' => 'e.g. 2026-01-01T00:00:00Z  (blank = all)',
                    ]) ?>
                </div>
                <div class="col-sm-2">
                    <?= Html::label('Limit', 'vs-go-limit', ['class' => 'col-form-label col-form-label-sm']) ?>
                    <?= Html::input('number', 'vs-go-limit', 100, [
                        'id'    => 'vs-go-limit',
                        'class' => 'form-control form-control-sm',
                        'min'   => 1,
                        'max'   => 500,
                    ]) ?>
                </div>
                <div class="col-sm-auto mt-2">
                    <?= Html::button('<span class="vs-spinner spinner-border spinner-border-sm mr-1" role="status"></span>Run', [
                        'id'    => 'vs-get-orders-btn',
                        'class' => 'btn btn-primary btn-sm',
                        'type'  => 'button',
                    ]) ?>
                </div>
            </div>
            <pre id="vs-get-orders-result" class="vs-result-pre"></pre>
        </div>
    </div>

    <!-- ================================================================ -->
    <!-- 2. Get Single Order                                               -->
    <!-- ================================================================ -->
    <div class="card mb-4 vs-explorer-card">
        <div class="card-header d-flex justify-content-between align-items-center">
            <span>Get Order <code class="ml-2 font-weight-normal text-muted small">GET orders/{id}/</code></span>
            <span class="vs-status-badge"></span>
        </div>
        <div class="card-body">
            <div class="form-row align-items-end mb-3">
                <div class="col-sm-6">
                    <?= Html::label('Order Number', 'vs-order-no', ['class' => 'col-form-label col-form-label-sm']) ?>
                    <?= Html::input('text', 'vs-order-no', '', [
                        'id'          => 'vs-order-no',
                        'class'       => 'form-control form-control-sm',
                        'placeholder' => 'e.g. VS-00123',
                    ]) ?>
                </div>
                <div class="col-sm-auto mt-2">
                    <?= Html::button('<span class="vs-spinner spinner-border spinner-border-sm mr-1" role="status"></span>Run', [
                        'id'    => 'vs-get-order-btn',
                        'class' => 'btn btn-primary btn-sm',
                        'type'  => 'button',
                    ]) ?>
                </div>
            </div>
            <pre id="vs-get-order-result" class="vs-result-pre"></pre>
        </div>
    </div>

    <!-- ================================================================ -->
    <!-- 3. Get Item                                                       -->
    <!-- ================================================================ -->
    <div class="card mb-4 vs-explorer-card">
        <div class="card-header d-flex justify-content-between align-items-center">
            <span>Get Item <code class="ml-2 font-weight-normal text-muted small">GET items/{id}/</code></span>
            <span class="vs-status-badge"></span>
        </div>
        <div class="card-body">
            <p class="text-muted small mb-3">
                Fetch a single order line item. Item IDs are numeric and appear in the
                <code>items[].url</code> field of each order (e.g. <code>…/items/<strong>577754</strong>/</code>).
            </p>
            <div class="form-row align-items-end mb-3">
                <div class="col-sm-4">
                    <?= Html::label('Item ID', 'vs-item-id', ['class' => 'col-form-label col-form-label-sm']) ?>
                    <?= Html::input('text', 'vs-item-id', '', [
                        'id'          => 'vs-item-id',
                        'class'       => 'form-control form-control-sm',
                        'placeholder' => 'e.g. 577754',
                    ]) ?>
                </div>
                <div class="col-sm-auto mt-2">
                    <?= Html::button('<span class="vs-spinner spinner-border spinner-border-sm mr-1" role="status"></span>Run', [
                        'id'    => 'vs-get-item-btn',
                        'class' => 'btn btn-primary btn-sm',
                        'type'  => 'button',
                    ]) ?>
                </div>
            </div>
            <pre id="vs-get-item-result" class="vs-result-pre"></pre>
        </div>
    </div>

    <!-- ================================================================ -->
    <!-- 4. List Customers                                                 -->
    <!-- ================================================================ -->
    <div class="card mb-4 vs-explorer-card">
        <div class="card-header d-flex justify-content-between align-items-center">
            <span>List Customers <code class="ml-2 font-weight-normal text-muted small">GET customers/</code></span>
            <span class="vs-status-badge"></span>
        </div>
        <div class="card-body">
            <p class="text-muted small mb-3">
                Lists the retailers/customers associated with this supplier account.
                Optional filters as JSON, e.g. <code>{"limit":5}</code>.
            </p>
            <div class="form-row align-items-end mb-3">
                <div class="col-sm-8">
                    <?= Html::label('Filters (JSON)', 'vs-customers-filters', ['class' => 'col-form-label col-form-label-sm']) ?>
                    <?= Html::input('text', 'vs-customers-filters', '', [
                        'id'          => 'vs-customers-filters',
                        'class'       => 'form-control form-control-sm',
                        'placeholder' => '{}',
                    ]) ?>
                </div>
                <div class="col-sm-auto mt-2">
                    <?= Html::button('<span class="vs-spinner spinner-border spinner-border-sm mr-1" role="status"></span>Run', [
                        'id'    => 'vs-list-customers-btn',
                        'class' => 'btn btn-primary btn-sm',
                        'type'  => 'button',
                    ]) ?>
                </div>
            </div>
            <pre id="vs-list-customers-result" class="vs-result-pre"></pre>
        </div>
    </div>

</div>
