
<?php
$this->title = 'NetSuite Configuration';
$this->params['breadcrumbs'][] = $this->title;

$this->registerJs(<<<JS
// Test Connection AJAX
$('#test-connection-btn').click(function() {
    var btn = $(this);
    var originalText = btn.text();
    var form = $('#netsuite-settings-form');
    btn.prop('disabled', true).text('Testing...');
    $.ajax({
        url: 'settings/test-connection',
        type: 'POST',
        data: 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);
        }
    });
});
JS
);
?>

<div class="netsuite-config-index">
    <div class="row">
        <div class="col-md-8">
            <?php $form = ActiveForm::begin([
                'id' => 'netsuite-settings-form',
                'action' => ['settings/index'],
                'method' => 'post',
                'options' => ['class' => 'form-horizontal'],
                'enableAjaxValidation' => true,
                'enableClientValidation' => true,
                'validationUrl' => ['settings/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(['label' => 'Enable NetSuite Integration']) ?>
                    <?= $form->field($model, 'environment')->dropDownList([
                        'sandbox' => 'Sandbox (Testing)',
                        'production' => 'Production (Live)',
                    ], ['prompt' => 'Select Environment...']) ?>
                    <?= $form->field($model, 'account_id')->textInput(['maxlength' => true, 'placeholder' => 'e.g., 1234567']) ?>
                    <?= $form->field($model, 'consumer_key')->textInput(['maxlength' => true, 'placeholder' => 'Consumer Key from NetSuite Integration']) ?>
                    <?= $form->field($model, 'consumer_secret')->passwordInput(['maxlength' => true, 'placeholder' => 'Consumer Secret', 'autocomplete' => 'new-password']) ?>
                    <?= $form->field($model, 'token_id')->textInput(['maxlength' => true, 'placeholder' => 'Token ID']) ?>
                    <?= $form->field($model, 'token_secret')->passwordInput(['maxlength' => true, 'placeholder' => 'Token Secret', 'autocomplete' => 'new-password']) ?>
                </div>
            </div>

            <!-- Sync Settings Card (placeholder, extend as needed) -->
            <div class="card border-warning mt-4">
                <div class="card-header bg-warning text-dark">
                    <h5 class="card-title mb-0">Sync Settings</h5>
                </div>
                <div class="card-body">
                    <p>Sync settings and options for NetSuite integration can be configured here.</p>
                    <!-- Add sync options as needed -->
                </div>
            </div>

            <!-- Field Mapping Card (placeholder, extend as needed) -->
            <div class="card border-info mt-4">
                <div class="card-header bg-info text-white">
                    <h5 class="card-title mb-0"><i class="fas fa-exchange-alt"></i> Field Mapping</h5>
                </div>
                <div class="card-body">
                    <p>Configure field mapping between your system and NetSuite records.</p>
                    <?= Html::a('<i class="fas fa-cog"></i> Configure Field Mapping', ['#'], [
                        'class' => 'btn btn-primary',
                        'style' => 'color: #fff;',
                        'title' => 'Setup field mapping (coming soon)'
                    ]) ?>
                </div>
            </div>

            <div class="form-group mt-4">
                <div class="col-sm-offset-4 col-sm-8">
                    <?= Html::submitButton('Save Configuration', ['class' => 'btn btn-primary']) ?>
                    <?= Html::button('Test Connection', ['class' => 'btn btn-info', 'id' => 'test-connection-btn']) ?>
                </div>
            </div>

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

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

        <div class="col-md-4">
            <!-- Sync Status Card (placeholder, extend as needed) -->
            <div class="card border-success">
                <div class="card-header bg-success text-white">
                    <h5 class="card-title mb-0">Sync Status</h5>
                </div>
                <div class="card-body">
                    <div id="status-info">
                        <p><i class="fa fa-spinner fa-spin"></i> Loading status...</p>
                    </div>
                    <!-- Add sync status AJAX/auto-refresh as needed -->
                </div>
            </div>

            <!-- Help Card -->
            <div class="card mt-4">
                <div class="card-header">
                    <h5 class="card-title mb-0">Help & Documentation</h5>
                </div>
                <div class="card-body">
                    <h5>Configuration Tips:</h5>
                    <ul class="small">
                        <li><strong>Account ID:</strong> Your NetSuite Account ID (e.g., 1234567)</li>
                        <li><strong>Consumer Key/Secret:</strong> From NetSuite Integration setup</li>
                        <li><strong>Token ID/Secret:</strong> From NetSuite Token-Based Authentication</li>
                        <li><strong>Environment:</strong> Use 'sandbox' for testing, 'production' for live</li>
                    </ul>
                    <h5>How to Get Credentials:</h5>
                    <ol class="small">
                        <li>Login to NetSuite</li>
                        <li>Go to Setup → Integration → Manage Integrations</li>
                        <li>Create/select integration, copy Consumer Key/Secret</li>
                        <li>Go to Setup → Users/Roles → Access Tokens</li>
                        <li>Create/select token, copy Token ID/Secret</li>
                    </ol>
                    <h5>Security Note:</h5>
                    <ul class="small">
                        <li>Credentials are stored in <code>modules/netsuite/config/ns.php</code></li>
                        <li>Do not commit this file to version control</li>
                        <li>Set proper file permissions</li>
                    </ul>
                    <h5>Documentation:</h5>
                    <ul>
                        <li><a href="https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_4247337262.html" target="_blank">NetSuite OAuth 1.0 Guide</a></li>
                        <li><a href="https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_157771733782.html" target="_blank">Token-Based Authentication</a></li>
                    </ul>
                </div>
            </div>
        </div>
    </div>
</div>

<?php
$testUrl = Url::to(['settings/test-connection']);
$this->registerJs(<<<JS
$('#test-connection-btn').on('click', function() {
    var btn = $(this);
    var originalHtml = btn.html();
    
    btn.prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i> Testing...');
    
    $.ajax({
        url: '{$testUrl}',
        type: 'POST',
        dataType: 'json',
        success: function(response) {
            if (response.success) {
                alert('✓ ' + response.message);
            } else {
                alert('✗ ' + response.message);
            }
        },
        error: function() {
            alert('✗ Failed to test connection. Please try again.');
        },
        complete: function() {
            btn.prop('disabled', false).html(originalHtml);
        }
    });
});
JS
);
?>

<style>
.form-section {
    margin-bottom: 30px;
    padding-bottom: 20px;
    border-bottom: 1px solid #e0e0e0;
}

.form-section:last-child {
    border-bottom: none;
}

.section-title {
    margin-bottom: 20px;
    color: #333;
    font-size: 16px;
    font-weight: 600;
}

.section-title i {
    margin-right: 8px;
    color: #007bff;
}

.info-box {
    margin-top: 15px;
}

.info-box h5 {
    font-size: 14px;
    font-weight: 600;
    margin-bottom: 10px;
}

.info-box ul {
    padding-left: 20px;
}

.info-box li {
    margin-bottom: 5px;
}

.alert h5 {
    font-size: 14px;
    font-weight: 600;
    margin-bottom: 10px;
}

.alert ol {
    padding-left: 20px;
    margin-bottom: 0;
}

.alert ol li {
    margin-bottom: 5px;
}

#save-settings-btn {
    margin-right: 10px;
}
</style>
