<?php
/**
 * Magento Configuration View
 */

use yii\helpers\Html;
use yii\widgets\ActiveForm;
use yii\bootstrap\Alert;
use yii\web\JsExpression;

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

$this->title = 'Magento Configuration';
$this->params['breadcrumbs'][] = $this->title;

// Register JavaScript for AJAX functionality
$this->registerJs("
    // Toggle authentication method fields
    function toggleAuthFields() {
        var authMethod = $('#configform-authmethod').val();
        
        if (authMethod === 'token') {
            $('#token-fields').show();
            $('#credential-fields').hide();
            // Clear credential field values when hidden
            $('#configform-adminusername').val('');
            $('#configform-adminpassword').val('');
        } else {
            $('#token-fields').hide();
            $('#credential-fields').show();
            // Clear token field when hidden
            $('#configform-accesstoken').val('');
        }
        
        // Trigger validation update
        $('#config-form').yiiActiveForm('validateAttribute', 'configform-accesstoken');
        $('#config-form').yiiActiveForm('validateAttribute', 'configform-adminusername');
        $('#config-form').yiiActiveForm('validateAttribute', 'configform-adminpassword');
    }
    
    // Initialize on page load
    toggleAuthFields();
    
    // Toggle when method changes
    $('#configform-authmethod').change(toggleAuthFields);

    // Test Connection
    $('#test-connection-btn').click(function() {
        var btn = $(this);
        var originalText = btn.text();
        var form = $('#config-form');
        
        btn.prop('disabled', true).text('Testing...');
        
        $.ajax({
            url: '" . \yii\helpers\Url::to(['config/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);
            }
        });
    });
    
    // Manual Sync
    $('#manual-sync-btn').click(function() {
        var btn = $(this);
        var originalText = btn.text();
        
        btn.prop('disabled', true).text('Syncing...');
        
        $.ajax({
            url: '" . \yii\helpers\Url::to(['config/sync']) . "',
            type: 'POST',
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    $('#sync-result').html('<div class=\"alert alert-success\">' + response.message + '</div>');
                } else {
                    $('#sync-result').html('<div class=\"alert alert-danger\">' + response.message + '</div>');
                }
            },
            error: function() {
                $('#sync-result').html('<div class=\"alert alert-danger\">Sync failed</div>');
            },
            complete: function() {
                btn.prop('disabled', false).text(originalText);
            }
        });
    });
    
    // Load Sync Status
    function loadSyncStatus() {
        $.ajax({
            url: '" . \yii\helpers\Url::to(['config/status']) . "',
            type: 'GET',
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    var status = response.stats;
                    var html = '<strong>Connection Status:</strong> ' + (status.is_connected ? 'Connected' : 'Disconnected') + '<br>';
                    html += '<strong>Module Configured:</strong> ' + (response.module_configured ? 'Yes' : 'No') + '<br>';
                    if (status.last_sync) {
                        html += '<strong>Last Sync:</strong> ' + status.last_sync + '<br>';
                    }
                    html += '<strong>Total Synced:</strong> ' + (status.total_synced || 0);
                    $('#status-info').html(html);
                }
            }
        });
    }
    
    // Load status on page load
    loadSyncStatus();
    
    // Auto-refresh status every 30 seconds
    setInterval(loadSyncStatus, 30000);
");
?>

<div class="magento-config-index">
    <div class="row">
        <div class="col-md-8">
            <?php $form = ActiveForm::begin([
                'id' => 'config-form',
                'action' => \yii\helpers\Url::to(['config/index']),
                'method' => 'post',
                'options' => ['class' => 'form-horizontal'],
                'enableAjaxValidation' => true,
                'enableClientValidation' => true,
                'validationUrl' => \yii\helpers\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, 'apiUrl')->textInput(['placeholder' => 'https://yourstore.com']) ?>

                            <?= $form->field($model, 'authMethod')->dropDownList([
                                'token' => 'API Access Token (Recommended)',
                                'credentials' => 'Username/Password'
                            ], ['id' => 'configform-authmethod']) ?>

                            <div id="token-fields" style="display: none;">
                                <?= $form->field($model, 'accessToken')->textarea([
                                    'rows' => 3,
                                    'placeholder' => 'Enter your Magento API access token here...'
                                ]) ?>
                            </div>

                            <div id="credential-fields" style="display: none;">
                                <?= $form->field($model, 'adminUsername')->textInput(['placeholder' => 'admin']) ?>
                                <?= $form->field($model, 'adminPassword')->passwordInput(['placeholder' => 'Enter password']) ?>
                            </div>

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

                            <?= $form->field($model, 'timeout')->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">Sync Settings</h5>
                        </div>
                        <div class="card-body">
                            <?= $form->field($model, 'autoSync')->checkbox() ?>

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

                            <?= $form->field($model, 'priceFields')->textInput(['placeholder' => 'price1,price2,price3']) ?>

                            <?= $form->field($model, 'fieldMapping')->textarea([
                                'rows' => 8, 
                                'placeholder' => json_encode($model->getDefaultFieldMapping(), JSON_PRETTY_PRINT)
                            ])->hint('JSON mapping: <strong>"ngauge_field": "magento_field"</strong><br>
                                <em>Left side = NGauge/Yii field names, Right side = Magento field names</em><br>
                                Example: "price1": "price" maps NGauge price1 field to Magento price field') ?>
                        </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 Configuration', ['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 all settings to defaults?'
                            ]) ?>
                        </div>
                    </div>

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

                    <!-- Field Mapping Link -->
                    <div class="mt-4">
                        <div class="card border-info">
                            <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 class="mb-3">Configure intelligent field mapping between NGauge and Magento product attributes.</p>
                                <div class="d-flex justify-content-between align-items-center">
                                    <?= Html::a(
                                        '<i class="fas fa-cog"></i> Configure Field Mapping', 
                                        ['/magento/mapping/index'], 
                                        [
                                            'class' => 'btn btn-primary',
                                            'title' => 'Setup field mapping between NGauge and Magento'
                                        ]
                                    ) ?>
                                    <small class="text-muted">
                                        <?php 
                                        $config = Yii::$app->params['plugins']['magento'] ?? [];
                                        $mappingCount = count($config['field_mapping'] ?? []);
                                        echo $mappingCount > 0 ? "$mappingCount fields mapped" : "No fields mapped yet";
                                        ?>
                                    </small>
                                </div>
                            </div>
                        </div>
                    </div>

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

        <div class="col-md-4">
            <!-- Status Card -->
            <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>
                    
                    <hr>
                    
                    <?= Html::button('Manual Sync', ['class' => 'btn btn-success btn-block', 'id' => 'manual-sync-btn']) ?>
                    
                    <div id="sync-result" style="margin-top: 10px;"></div>
                </div>
            </div>

            <!-- Quick Actions Card -->
            <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 Config', ['config/export'], [
                        'class' => 'btn btn-default btn-block',
                        'title' => 'Export current configuration (excluding password)'
                    ]) ?>
                    
                    <?= Html::a('View Logs', '#', [
                        'class' => 'btn btn-default btn-block disabled',
                        'title' => 'View sync logs (coming soon)'
                    ]) ?>
                    
                    <?= Html::a('Documentation', '#', [
                        'class' => 'btn btn-default btn-block disabled',
                        'title' => 'View module documentation (coming soon)'
                    ]) ?>
                </div>
            </div>

            <!-- Help Card -->
            <div class="card">
                <div class="card-header">
                    <h5 class="card-title mb-0">Help</h5>
                </div>
                <div class="card-body">
                    <h5>Configuration Tips:</h5>
                    <ul class="small">
                        <li><strong>API URL:</strong> Should point to your Magento root (e.g., https://store.com)</li>
                        <li><strong>Access Token:</strong> Get from Magento Admin → System → Extensions → Integrations</li>
                        <li><strong>Authentication:</strong> Token method is more secure than username/password</li>
                        <li><strong>Store Code:</strong> Use 'default' for main store or specific store view code</li>
                        <li><strong>Price Fields:</strong> Local database fields that trigger Magento updates</li>
                        <li><strong>Field Mapping:</strong> JSON mapping of local to Magento field names</li>
                    </ul>
                    
                    <h5>How to Get API Token:</h5>
                    <ol class="small">
                        <li>Login to Magento Admin</li>
                        <li>Go to System → Extensions → Integrations</li>
                        <li>Click "Add New Integration"</li>
                        <li>Fill in Name and Admin Password</li>
                        <li>Go to API tab and select resources</li>
                        <li>Save and Activate integration</li>
                        <li>Copy the Access Token</li>
                    </ol>
                    
                    <h5>Troubleshooting:</h5>
                    <ul class="small">
                        <li>Enable debug mode for detailed logs</li>
                        <li>Test connection before saving</li>
                        <li>Check Magento API permissions</li>
                        <li>Verify SSL certificate for HTTPS</li>
                    </ul>
                </div>
            </div>
        </div>
    </div>
</div>