<?php
use yii\helpers\Html;
use yii\helpers\Url;
/** @var \backend\models\Cartsbe $model */
/** @var \PortalPeople\virtualstock\Module $module */
$vsId = $model->data->virtualstock->orderurl ?? 'n/a';
?>
<div class="virtualstock-tab">
    
    <p><strong><?= Html::encode(Yii::t('app', 'VirtualStock Order')) ?>:</strong> <?= Html::encode($vsId) ?></p>
    <p><strong><?= Html::encode(Yii::t('app', 'Status')) ?>:</strong> <?= Html::encode($model->status) ?></p>
    <div class="mb-2">
        <?= Html::button(Yii::t('app', 'Refresh from VirtualStock'), ['class' => 'btn btn-primary mr-2', 'id' => 'vs-refresh-' . $model->id]) ?>
        <?= Html::button('Get order from VirtualStock', ['class' => 'btn btn-outline-secondary mr-2', 'id' => 'vs-get-order-' . $model->id]) ?>
        <?= Html::a(Yii::t('app', 'Open in VirtualStock UI'), $module->apiEndpoint ? rtrim($module->apiEndpoint, '/') . '/orders/' . rawurlencode($vsId) : '#', ['class' => 'btn btn-secondary', 'target' => '_blank']) ?>
        <?= Html::button(Yii::t('app', 'Acknowledge'), ['class' => 'btn btn-warning ml-2', 'id' => 'vs-ack-' . $model->id, 'data-vs-order' => $vsId]) ?>
        <?= Html::button(Yii::t('app', 'Dispatch'), ['class' => 'btn btn-warning ml-2', 'id' => 'vs-dispatch-' . $model->id, 'data-vs-order' => $vsId]) ?>
    </div>

    <div class="form-inline mb-2">
        <label class="mr-2"><?= Html::encode(Yii::t('app', 'Set Status')) ?>:</label>
        <?php
        $statusOptions = is_array($module->statusMap) ? $module->statusMap : [];
        $selectOptions = [];
        foreach ($statusOptions as $k => $v) {
            $selectOptions[$k] = $v;
        }
        echo Html::dropDownList('vs-status-' . $model->id, null, $selectOptions, ['class' => 'form-control mr-2', 'id' => 'vs-status-' . $model->id]);
        ?>
        <?= Html::button(Yii::t('app', 'Push Status'), ['class' => 'btn btn-success mr-2', 'id' => 'vs-push-status-' . $model->id]) ?>
        <?= Html::button(Yii::t('app', 'Push Custom Payload'), ['class' => 'btn btn-outline-secondary', 'id' => 'vs-push-payload-' . $model->id]) ?>
    </div>
</div>
<div id="vs-order-card-<?= $model->id ?>" style="margin-top:10px;"></div>

<div class="mt-2">
    <label><strong><?= Html::encode(Yii::t('app', 'Last API Response')) ?>:</strong></label>
    <pre id="vs-api-response-<?= $model->id ?>" style="background:#f8f9fa;padding:8px;border:1px solid #ddd;max-height:300px;overflow:auto;">(no response yet)</pre>
</div>

<script>
(function(){
        var vsExamplePayload = JSON.stringify({
            items: [
                {
                    part_number: "572JJ",
                    line_ref: "ci247922457387",
                    quantity: 5,
                    sub_status: "Booked",
                    supplier_dispatch_date: "2019-10-10T12:00:00",
                    supplier_delivery_date: "2019-10-10T12:00:00"
                },
                {
                    part_number: "461KJ",
                    line_ref: "ci247922493997",
                    quantity: 1,
                    sub_status: "Booked",
                    supplier_dispatch_date: "2019-10-10T12:00:00",
                    supplier_delivery_date: "2019-10-10T12:00:00"
                }
            ]
        }, null, 2);
        $('#vs-refresh-<?= $model->id ?>').on('click', function(e){
        e.preventDefault();
        var btn = $(this);
        btn.prop('disabled', true).text('<?= Html::encode(Yii::t('app','Refreshing...')) ?>');
        $.post('<?= Url::to(['/virtualstock/virtualstock/refresh']) ?>', {id: '<?= $model->id ?>'})
            .done(function(resp){
                try { $('#vs-api-response-<?= $model->id ?>').text(JSON.stringify(resp, null, 2)); } catch (e) { $('#vs-api-response-<?= $model->id ?>').text(String(resp)); }
                if (resp && resp.success) {
                    location.reload();
                } else {
                    alert(resp && resp.error ? resp.error : 'Refresh failed');
                    btn.prop('disabled', false).text('<?= Html::encode(Yii::t('app','Refresh from VirtualStock')) ?>');
                }
            }).fail(function(xhr){
                var text = xhr && xhr.responseText ? xhr.responseText : 'Request failed';
                $('#vs-api-response-<?= $model->id ?>').text(text);
                alert('Request failed');
                btn.prop('disabled', false).text('<?= Html::encode(Yii::t('app','Refresh from VirtualStock')) ?>');
            });
    });

    // Get order without applying it — render into a card like product UI
    $('#vs-get-order-<?= $model->id ?>').on('click', function(e){
        e.preventDefault();
        var btn = $(this);
        btn.prop('disabled', true).text('Loading...');
        var orderNo = '<?= Html::encode($vsId) ?>';
        $.ajax({
            url: '<?= Url::to(['/virtualstock/config/api-get-order']) ?>',
            method: 'POST',
            data: { orderNo: orderNo, _csrf: yii.getCsrfToken() },
            dataType: 'json'
        }).done(function(resp){
            var card = $('#vs-order-card-<?= $model->id ?>');
            if (!resp || !resp.success) {
                card.html('<div class="alert alert-danger">' + (resp && resp.message ? resp.message : 'Failed to fetch order') + '</div>');
                btn.prop('disabled', false).text('Get order from VirtualStock');
                return;
            }
            var pretty = JSON.stringify(resp.data, null, 2);
            card.html('<pre style="background:#f8f9fa;padding:10px;border-radius:4px;">' + pretty + '</pre>');
            btn.prop('disabled', false).text('Get order from VirtualStock');
        }).fail(function(xhr){
            var card = $('#vs-order-card-<?= $model->id ?>');
            var text = xhr && xhr.responseText ? xhr.responseText : 'Request failed';
            card.html('<div class="alert alert-danger">' + text + '</div>');
            btn.prop('disabled', false).text('Get order from VirtualStock');
        });
    });

        $('#vs-push-status-<?= $model->id ?>').on('click', function(e){
            e.preventDefault();
            var btn = $(this);
            var status = $('#vs-status-<?= $model->id ?>').val();
            if (!status) {
                alert('Please select a status');
                return;
            }
            btn.prop('disabled', true).text('<?= Html::encode(Yii::t('app','Pushing...')) ?>');
            $.post('<?= Url::to(['/virtualstock/virtualstock/vsupdate']) ?>', {id: '<?= $model->id ?>', status: status})
                .done(function(resp){
                    try { $('#vs-api-response-<?= $model->id ?>').text(JSON.stringify(resp, null, 2)); } catch (e) { $('#vs-api-response-<?= $model->id ?>').text(String(resp)); }
                    if (resp && resp.success) {
                        location.reload();
                    } else {
                        alert(resp && resp.error ? resp.error : 'Push failed');
                        btn.prop('disabled', false).text('<?= Html::encode(Yii::t('app','Push Status')) ?>');
                    }
                }).fail(function(xhr){
                    var text = xhr && xhr.responseText ? xhr.responseText : 'Request failed';
                    $('#vs-api-response-<?= $model->id ?>').text(text);
                    alert('Request failed');
                    btn.prop('disabled', false).text('<?= Html::encode(Yii::t('app','Push Status')) ?>');
                });
        });

        $('#vs-push-payload-<?= $model->id ?>').on('click', function(e){
            e.preventDefault();
            var payload = prompt('Enter JSON payload to send to VirtualStock (edit the example if needed):', vsExamplePayload);
            if (!payload) { return; }
            try { var data = JSON.parse(payload); } catch (ex) { alert('Invalid JSON'); return; }
            var btn = $(this);
            btn.prop('disabled', true).text('<?= Html::encode(Yii::t('app','Pushing...')) ?>');
            $.post('<?= Url::to(['/virtualstock/virtualstock/vsupdate']) ?>', {id: '<?= $model->id ?>', payload: JSON.stringify(data)})
                .done(function(resp){
                    try { $('#vs-api-response-<?= $model->id ?>').text(JSON.stringify(resp, null, 2)); } catch (e) { $('#vs-api-response-<?= $model->id ?>').text(String(resp)); }
                    if (resp && resp.success) {
                        location.reload();
                    } else {
                        alert(resp && resp.error ? resp.error : 'Push failed');
                        btn.prop('disabled', false).text('<?= Html::encode(Yii::t('app','Push Custom Payload')) ?>');
                    }
                }).fail(function(xhr){
                    var text = xhr && xhr.responseText ? xhr.responseText : 'Request failed';
                    $('#vs-api-response-<?= $model->id ?>').text(text);
                    alert('Request failed');
                    btn.prop('disabled', false).text('<?= Html::encode(Yii::t('app','Push Custom Payload')) ?>');
                });
        });

                $('#vs-ack-<?= $model->id ?>').on('click', function(e){
                    e.preventDefault();
                    if (!confirm('Acknowledge this order on VirtualStock?')) { return; }
                    var btn = $(this);
                    btn.prop('disabled', true).text('<?= Html::encode(Yii::t('app','Acknowledging...')) ?>');
                    var order = btn.data('vs-order') || '';
                    var payload = prompt('Enter JSON payload to send with acknowledge (edit the example if needed):', vsExamplePayload);
                    var pdata = null;
                    if (payload) {
                        try { pdata = JSON.parse(payload); } catch (ex) { alert('Invalid JSON'); btn.prop('disabled', false).text('<?= Html::encode(Yii::t('app','Acknowledge')) ?>'); return; }
                    }
                    $.post('<?= Url::to(['/virtualstock/virtualstock/acknowledge']) ?>', {id: '<?= $model->id ?>', order: order, payload: pdata ? JSON.stringify(pdata) : ''})
                        .done(function(resp){
                            if (resp && resp.success) {
                                location.reload();
                            } else {
                                alert(resp && resp.error ? resp.error : 'Acknowledge failed');
                                btn.prop('disabled', false).text('<?= Html::encode(Yii::t('app','Acknowledge')) ?>');
                            }
                        }).fail(function(){
                            alert('Request failed');
                            btn.prop('disabled', false).text('<?= Html::encode(Yii::t('app','Acknowledge')) ?>');
                        });
                });
                $('#vs-dispatch-<?= $model->id ?>').on('click', function(e){
                    e.preventDefault();
                    if (!confirm('Dispatch this order on VirtualStock?')) { return; }
                    var btn = $(this);
                    btn.prop('disabled', true).text('<?= Html::encode(Yii::t('app','Dispatching...')) ?>');
                    var order = btn.data('vs-order') || '';
                    var payload = prompt('Enter JSON payload to send with dispatch (edit the example if needed):', vsExamplePayload);
                    var pdata = null;
                    if (payload) {
                        try { pdata = JSON.parse(payload); } catch (ex) { alert('Invalid JSON'); btn.prop('disabled', false).text('<?= Html::encode(Yii::t('app','Dispatch')) ?>'); return; }
                    }
                    $.post('<?= Url::to(['/virtualstock/virtualstock/dispatch']) ?>', {id: '<?= $model->id ?>', order: order, payload: pdata ? JSON.stringify(pdata) : ''})
                        .done(function(resp){
                            if (resp && resp.success) {
                                console.log(resp);
                                location.reload();
                            } else {
                                alert(resp && resp.error ? resp.error : 'Dispatch failed');
                                btn.prop('disabled', false).text('<?= Html::encode(Yii::t('app','Dispatch')) ?>');
                            }
                        }).fail(function(){
                            alert('Request failed');
                            btn.prop('disabled', false).text('<?= Html::encode(Yii::t('app','Dispatch')) ?>');
                        });
                });
})();
</script>
