<?php
/**
 * Caterpoint Setup View
 */

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

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

$this->title = 'Caterpoint Setup';
$this->params['breadcrumbs'][] = $this->title;

$this->registerJs(
"    
    function renderStatus() {
        $.ajax({
            url: '" . Url::to(['config/status']) . "',
            type: 'GET',
            dataType: 'json',
            success: function(response) {
                if (!response.success) {
                    $('#status-info').html('<div class=\"text-danger\">' + (response.message || 'Unable to load status') + '</div>');
                    return;
                }

                var html = '';
                html += '<strong>Configured:</strong> ' + (response.configured ? 'Yes' : 'No') + '<br>';
                html += '<strong>Current Cursor:</strong> ' + (response.cursor ? response.cursor : 'Not set');
                $('#status-info').html(html);
            },
            error: function() {
                $('#status-info').html('<div class=\"text-danger\">Unable to load status</div>');
            }
        });
    }

    function runImport(dryRun) {
        var btn = dryRun ? $('#dry-run-import-btn') : $('#import-btn');
        var originalText = btn.text();
        btn.prop('disabled', true).text(dryRun ? 'Running dry run...' : 'Importing...');

        $.ajax({
            url: '" . Url::to(['config/import']) . "',
            type: 'POST',
            dataType: 'json',
            data: {
                dryRun: dryRun ? 1 : 0,
                limit: $('#configform-polllimit').val(),
                _csrf: yii.getCsrfToken()
            },
            success: function(response) {
                if (response.success) {
                    var result = response.result || {};
                    var html = '<div class=\"alert alert-success\">' + response.message + '</div>';
                    html += '<div><strong>Fetched:</strong> ' + (result.fetched || 0) + '</div>';
                    html += '<div><strong>Created:</strong> ' + (result.created || 0) + '</div>';
                    html += '<div><strong>Updated:</strong> ' + (result.updated || 0) + '</div>';
                    html += '<div><strong>Failed:</strong> ' + (result.failed || 0) + '</div>';
                    $('#import-result').html(html);
                    renderStatus();
                } else {
                    $('#import-result').html('<div class=\"alert alert-danger\">' + response.message + '</div>');
                }
            },
            error: function() {
                $('#import-result').html('<div class=\"alert alert-danger\">Import request failed</div>');
            },
            complete: function() {
                btn.prop('disabled', false).text(originalText);
            }
        });
    }

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

        $.ajax({
            url: '" . Url::to(['config/test-connection']) . "',
            type: 'POST',
            data: $('#config-form').serialize(),
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    $('#connection-result').html('<div class=\"alert alert-success\">' + response.message + '</div>');
                } else {
                    $('#connection-result').html('<div class=\"alert alert-danger\">' + response.message + '</div>');
                }
            },
            error: function() {
                $('#connection-result').html('<div class=\"alert alert-danger\">Connection test failed</div>');
            },
            complete: function() {
                btn.prop('disabled', false).text(originalText);
            }
        });
    });

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

    $('#import-btn').on('click', function() {
        runImport(false);
    });

    renderStatus();
    setInterval(renderStatus, 30000);
"
);
?>

<div class="caterpoint-config-index">
    <div class="row">
        <div class="col-md-8">
            <?php $form = ActiveForm::begin([
                'id' => 'config-form',
                'action' => Url::to(['config/index']),
                'method' => 'post',
                'options' => ['class' => 'form-horizontal'],
                'enableAjaxValidation' => true,
                'enableClientValidation' => true,
                'validationUrl' => Url::to(['config/validate']),
                'fieldConfig' => [
                    'template' => "{label}\n<div class=\"col-sm-8\">{input}\n{hint}\n{error}</div>",
                    'labelOptions' => ['class' => 'col-sm-4 control-label'],
                ],
            ]); ?>

            <div class="card border-info">
                <div class="card-header bg-info text-white">
                    <h5 class="card-title mb-0">API Connection Settings</h5>
                </div>
                <div class="card-body">
                    <?= $form->field($model, 'enabled')->checkbox() ?>

                    <?= $form->field($model, 'apiEndpoint')->textInput([
                        'placeholder' => 'https://cp3-bayley-test.caterpoint.co.uk/api'
                    ]) ?>

                    <?= $form->field($model, 'apiToken')->passwordInput([
                        'placeholder' => 'Enter Caterpoint API token',
                        'autocomplete' => 'off'
                    ]) ?>

                    <?= $form->field($model, 'requestTimeout')->input('number', [
                        'min' => 5,
                        'max' => 300
                    ]) ?>
                </div>
            </div>

            <div class="card border-warning">
                <div class="card-header bg-warning text-dark">
                    <h5 class="card-title mb-0">Order Import Settings</h5>
                </div>
                <div class="card-body">
                    <?= $form->field($model, 'pollLimit')->input('number', [
                        'min' => 1,
                        'max' => 500
                    ]) ?>

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

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

                    <?= $form->field($model, 'statusMap')->textarea([
                        'rows' => 8,
                        'placeholder' => json_encode($model->getDefaultStatusMapping(), JSON_PRETTY_PRINT)
                    ])->hint('JSON mapping format: {"caterpoint_status": "local_status"}') ?>
                </div>
            </div>

            <div class="card border-secondary">
                <div class="card-header bg-secondary text-white">
                    <h5 class="card-title mb-0">Advanced Settings</h5>
                </div>
                <div class="card-body">
                    <?= $form->field($model, 'debug')->checkbox() ?>
                </div>
            </div>

            <div class="form-group">
                <div class="col-sm-offset-4 col-sm-8">
                    <?= Html::submitButton('Save Setup', ['class' => 'btn btn-primary']) ?>
                    <?= Html::button('Test Connection', ['class' => 'btn btn-info', 'id' => 'test-connection-btn']) ?>
                    <?= Html::a('Reset to Defaults', ['config/reset'], [
                        'class' => 'btn btn-warning',
                        'data-confirm' => 'Are you sure you want to reset Caterpoint setup to defaults?'
                    ]) ?>
                </div>
            </div>

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

            <div id="connection-result"></div>
        </div>

        <div class="col-md-4">
            <div class="card border-success">
                <div class="card-header bg-success text-white">
                    <h5 class="card-title mb-0">Import Status</h5>
                </div>
                <div class="card-body">
                    <div id="status-info">
                        <p>Loading status...</p>
                    </div>

                    <hr>

                    <?= Html::button('Dry Run Import', ['class' => 'btn btn-default btn-block', 'id' => 'dry-run-import-btn']) ?>
                    <?= Html::button('Import Orders', ['class' => 'btn btn-success btn-block', 'id' => 'import-btn']) ?>

                    <div id="import-result" style="margin-top: 10px;"></div>
                </div>
            </div>

            <div class="card border-info">
                <div class="card-header bg-info text-white">
                    <h5 class="card-title mb-0">Quick Actions</h5>
                </div>
                <div class="card-body">
                    <?= Html::a('Export Setup', ['config/export'], [
                        'class' => 'btn btn-default btn-block',
                        'title' => 'Export current Caterpoint setup (token masked)'
                    ]) ?>

                    <?= Html::a('API Documentation', 'https://cp3-bayley-test.caterpoint.co.uk/api/documentation', [
                        'class' => 'btn btn-default btn-block',
                        'target' => '_blank',
                        'rel' => 'noopener noreferrer'
                    ]) ?>
                </div>
            </div>

            <div class="card">
                <div class="card-header">
                    <h5 class="card-title mb-0">Help</h5>
                </div>
                <div class="card-body">
                    <ul class="small">
                        <li><strong>Endpoint:</strong> Use your Caterpoint base API URL.</li>
                        <li><strong>Token:</strong> Must have permission to read distributor orders.</li>
                        <li><strong>Dry Run:</strong> Validates fetch and mapping without writes.</li>
                        <li><strong>Batch Size:</strong> Start small (e.g. 25) for initial tests.</li>
                        <li><strong>Status Map:</strong> Controls local status output per Caterpoint status.</li>
                    </ul>
                </div>
            </div>
        </div>
    </div>
</div>
