<?php
/**
 * Simple admin tab to push stock updates to VirtualStock.
 * Expected to be included from the backend product edit view.
 * Variables: $model (backend product model) with `supplier_sku` or `sku`.
 */
use yii\helpers\Html;
use yii\helpers\Url;
?>
<div class="virtualstock-product-tab">
    <h4>VirtualStock</h4>
    <div class="vs-current-stock">
        <strong>Supplier SKU:</strong> <?= Html::encode($model->supplier_sku ?? $model->sku ?? '') ?>
    </div>
    <div class="vs-actions">
        <label>Quantity to push:</label>
        <input type="number" id="vs_push_qty_<?= Html::encode($model->id ?? '0') ?>" value="0" min="0" />
        <button class="btn btn-primary" id="vs_push_btn_<?= Html::encode($model->id ?? '0') ?>">Push stock</button>
        <span id="vs_push_result_<?= Html::encode($model->id ?? '0') ?>"></span>
    </div>
    <div class="vs-get-product">
        <button class="btn btn-secondary" id="vs_get_btn_<?= Html::encode($model->id ?? '0') ?>">Get product from VirtualStock</button>
        <div id="vs_product_card_<?= Html::encode($model->id ?? '0') ?>" style="margin-top:10px;"></div>
    </div>
    <div class="vs-patch-product mt-3">
        <h5>Patch product (external REST ID)</h5>
        <label>REST ID</label>
        <input type="text" id="vs_rest_id_<?= Html::encode($model->id ?? '0') ?>" value="" class="form-control" />
        <label>Free stock</label>
        <input type="number" id="vs_free_stock_<?= Html::encode($model->id ?? '0') ?>" value="0" class="form-control" />
        <label>Backorder date (YYYY-MM-DD)</label>
        <input type="text" id="vs_bo_date_<?= Html::encode($model->id ?? '0') ?>" value="" class="form-control" />
        <button class="btn btn-outline-primary mt-2" id="vs_patch_btn_<?= Html::encode($model->id ?? '0') ?>">Update Stock</button>
        <div id="vs_patch_result_<?= Html::encode($model->id ?? '0') ?>" style="margin-top:8px;"></div>
    </div>

    <script>
    (function(){
        const btn = document.getElementById('vs_push_btn_<?= Html::encode($model->id ?? '0') ?>');
        const qtyEl = document.getElementById('vs_push_qty_<?= Html::encode($model->id ?? '0') ?>');
        const out = document.getElementById('vs_push_result_<?= Html::encode($model->id ?? '0') ?>');
        btn.addEventListener('click', async function(){
            out.textContent = 'Sending...';
            const sku = '<?= Html::encode($model->supplier_sku ?? $model->sku ?? '') ?>';
            const qty = parseInt(qtyEl.value, 10) || 0;
            try {
                const res = await fetch('<?= Url::to(['/virtualstock/virtualstock/update-product-stock']) ?>', {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json', 'X-CSRF-Token': '<?= Yii::$app->request->csrfToken ?>'},
                    body: JSON.stringify({ sku: sku, quantity: qty })
                });
                const data = await res.json();
                if (data.success) {
                    out.textContent = 'OK';
                } else {
                    out.textContent = 'Error: ' + (data.error || data.message || 'unknown');
                }
            } catch (e) {
                out.textContent = 'Error: ' + e.message;
            }
        });
        // Get product button
        const getBtn = document.getElementById('vs_get_btn_<?= Html::encode($model->id ?? '0') ?>');
        const card = document.getElementById('vs_product_card_<?= Html::encode($model->id ?? '0') ?>');
        getBtn.addEventListener('click', async function(){
            card.textContent = 'Loading...';
            const sku = '<?= Html::encode($model->data->virtualstock->supplier_sku ?? $model->stock_code ?? '') ?>';
            try {
                const url = '<?= Url::to(['/virtualstock/virtualstock/get-product-stock']) ?>?part_number=' + encodeURIComponent(sku);
                const res = await fetch(url, { method: 'GET', headers: {'Accept':'application/json'} });
                const data = await res.json();
                if (!data.success) {
                    card.innerHTML = '<div class="alert alert-danger">' + (data.error || 'Unknown error') + '</div>';
                    return;
                }
                // Render a simple card with JSON content
                const pretty = JSON.stringify(data.data, null, 2);
                card.innerHTML = '<pre style="background:#f8f9fa;padding:10px;border-radius:4px;">' + pretty + '</pre>';
            } catch (e) {
                card.innerHTML = '<div class="alert alert-danger">' + e.message + '</div>';
            }
        });
        // Patch product
        const patchBtn = document.getElementById('vs_patch_btn_<?= Html::encode($model->id ?? '0') ?>');
        const patchOut = document.getElementById('vs_patch_result_<?= Html::encode($model->id ?? '0') ?>');
        patchBtn.addEventListener('click', async function(){
            patchOut.textContent = 'Sending...';
            const restId = '<?= Html::encode($model->data->virtualstock->supplier_code ?? '') ?>';
            const freeStock = parseInt(document.getElementById('vs_free_stock_<?= Html::encode($model->id ?? '0') ?>').value, 10) || 0;
            const bo = document.getElementById('vs_bo_date_<?= Html::encode($model->id ?? '0') ?>').value.trim();
            const payload = { rest_id: restId, data: { free_stock: freeStock } };
            if (freeStock === 0 && bo !== '') { payload.data.backorder_date = bo; }
            try {
                const res = await fetch('<?= Url::to(['/virtualstock/virtualstock/patch-product']) ?>', {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json', 'X-CSRF-Token': '<?= Yii::$app->request->csrfToken ?>'},
                    body: JSON.stringify(payload)
                });
                const d = await res.json();
                if (d.success) {
                    patchOut.innerHTML = '<div class="alert alert-success">Patched OK</div>';
                } else {
                    patchOut.innerHTML = '<div class="alert alert-danger">' + (d.error || 'Failed') + '</div>';
                }
            } catch (e) {
                patchOut.innerHTML = '<div class="alert alert-danger">' + e.message + '</div>';
            }
        });
    })();
    </script>

</div>
