<?php
/**
 * Field Mapping Interface View
 *
 * @var \yii\web\View $this
 * @var array $ngaugeFields
 * @var array $magentoFields  
 * @var array $suggestions
 * @var array $currentMapping
 */

use yii\helpers\Html;
use yii\helpers\Url;
use yii\web\JsExpression;

$this->title = 'Magento Field Mapping';
$this->params['breadcrumbs'][] = ['label' => 'Magento Integration', 'url' => ['/magento/config/index']];
$this->params['breadcrumbs'][] = $this->title;

// Register required assets
$this->registerCssFile('https://code.jquery.com/ui/1.13.2/themes/ui-lightness/jquery-ui.css');
$this->registerJsFile('https://code.jquery.com/ui/1.13.2/jquery-ui.min.js', ['depends' => [\yii\web\JqueryAsset::class]]);
?>

<div class="magento-field-mapping">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h1><?= Html::encode($this->title) ?></h1>
        <div class="btn-group">
            <?= Html::button('<i class="fas fa-magic"></i> Apply Suggestions', [
                'class' => 'btn btn-info',
                'id' => 'apply-suggestions-btn',
                'title' => 'Apply intelligent field mapping suggestions'
            ]) ?>
            <?= Html::button('<i class="fas fa-check-circle"></i> Validate', [
                'class' => 'btn btn-secondary',
                'id' => 'validate-mapping-btn',
                'title' => 'Validate current field mappings'
            ]) ?>
            <?= Html::button('<i class="fas fa-download"></i> Export', [
                'class' => 'btn btn-secondary',
                'onclick' => 'window.location.href="' . Url::to(['export']) . '"',
                'title' => 'Export current mapping configuration'
            ]) ?>
            <?= Html::button('<i class="fas fa-save"></i> Save Mapping', [
                'class' => 'btn btn-success',
                'id' => 'save-mapping-btn'
            ]) ?>
        </div>
    </div>

    <!-- Help Text -->
    <div class="alert alert-info">
        <h6><i class="fas fa-info-circle"></i> Field Mapping Instructions</h6>
        <p class="mb-2">Map NGauge product fields to corresponding Magento product attributes. Drag and drop fields or use the dropdown selectors to create mappings.</p>
        <ul class="mb-0">
            <li><strong>Suggestions:</strong> Click "Apply Suggestions" to use intelligent mapping recommendations</li>
            <li><strong>Required Fields:</strong> Magento fields marked with <span class="text-danger">*</span> are required</li>
            <li><strong>Validation:</strong> Mapping will be validated before saving</li>
        </ul>
    </div>

    <div class="row">
        <!-- NGauge Fields Column -->
        <div class="col-md-5">
            <div class="card">
                <div class="card-header bg-primary text-white">
                    <h5 class="mb-0"><i class="fas fa-database"></i> NGauge Fields</h5>
                </div>
                <div class="card-body p-0" style="max-height: 600px; overflow-y: auto;">
                    <?php foreach ($ngaugeFields as $categoryCode => $category): ?>
                        <div class="field-category">
                            <div class="category-header bg-light p-2 border-bottom">
                                <strong><?= Html::encode($category['label']) ?></strong>
                                <span class="badge badge-secondary ml-2"><?= count($category['fields']) ?></span>
                            </div>
                            <div class="field-list" data-category="<?= $categoryCode ?>">
                                <?php foreach ($category['fields'] as $fieldCode => $field): ?>
                                    <div class="field-item p-2 border-bottom" data-field="<?= $fieldCode ?>" data-type="<?= $field['type'] ?>">
                                        <div class="d-flex justify-content-between align-items-center">
                                            <div>
                                                <strong><?= Html::encode($field['label']) ?></strong>
                                                <small class="text-muted d-block"><?= Html::encode($fieldCode) ?></small>
                                            </div>
                                            <span class="badge badge-outline-secondary"><?= $field['type'] ?></span>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>

        <!-- Mapping Column -->
        <div class="col-md-2">
            <div class="text-center" style="padding-top: 100px;">
                <i class="fas fa-arrows-alt-h fa-2x text-muted"></i>
                <div class="mt-2">
                    <small class="text-muted">Drag & Drop<br>or Select</small>
                </div>
            </div>
        </div>

        <!-- Magento Fields Column -->
        <div class="col-md-5">
            <div class="card">
                <div class="card-header bg-success text-white">
                    <h5 class="mb-0"><i class="fab fa-magento"></i> Magento Fields</h5>
                </div>
                <div class="card-body p-0" style="max-height: 600px; overflow-y: auto;">
                    <?php foreach ($magentoFields as $categoryCode => $category): ?>
                        <div class="field-category">
                            <div class="category-header bg-light p-2 border-bottom">
                                <strong><?= Html::encode($category['label']) ?></strong>
                                <span class="badge badge-secondary ml-2"><?= count($category['fields']) ?></span>
                            </div>
                            <div class="field-list" data-category="<?= $categoryCode ?>">
                                <?php foreach ($category['fields'] as $fieldCode => $field): ?>
                                    <div class="field-item p-2 border-bottom" data-field="<?= $fieldCode ?>" data-type="<?= $field['type'] ?>">
                                        <div class="d-flex justify-content-between align-items-center">
                                            <div>
                                                <strong>
                                                    <?= Html::encode($field['label']) ?>
                                                    <?php if ($field['required'] ?? false): ?>
                                                        <span class="text-danger">*</span>
                                                    <?php endif; ?>
                                                </strong>
                                                <small class="text-muted d-block"><?= Html::encode($fieldCode) ?></small>
                                            </div>
                                            <span class="badge badge-outline-success"><?= $field['type'] ?></span>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>
    </div>

    <!-- Current Mappings -->
    <div class="row mt-4">
        <div class="col-12">
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-0">
                        <i class="fas fa-link"></i> Current Field Mappings
                        <span class="badge badge-info ml-2" id="mapping-count"><?= count($currentMapping) ?></span>
                    </h5>
                </div>
                <div class="card-body">
                    <div id="mapping-container">
                        <?php if (empty($currentMapping)): ?>
                            <div class="text-center text-muted py-4" id="no-mappings">
                                <i class="fas fa-link fa-2x mb-2"></i>
                                <p>No field mappings configured yet.</p>
                                <p>Use the "Apply Suggestions" button to get started or drag fields to create mappings.</p>
                            </div>
                        <?php else: ?>
                            <div class="table-responsive">
                                <table class="table table-striped" id="mappings-table">
                                    <thead>
                                        <tr>
                                            <th>NGauge Field</th>
                                            <th>Magento Field</th>
                                            <th>Type Compatibility</th>
                                            <th>Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody id="mappings-tbody">
                                        <?php foreach ($currentMapping as $ngaugeField => $magentoField): ?>
                                            <?= $this->render('_mapping_row', [
                                                'ngaugeField' => $ngaugeField,
                                                'magentoField' => $magentoField,
                                                'ngaugeFields' => $ngaugeFields,
                                                'magentoFields' => $magentoFields
                                            ]) ?>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Suggestions Panel -->
    <div class="row mt-4" id="suggestions-panel" style="display: none;">
        <div class="col-12">
            <div class="card">
                <div class="card-header bg-warning">
                    <h5 class="mb-0">
                        <i class="fas fa-lightbulb"></i> Intelligent Mapping Suggestions
                        <span class="badge badge-dark ml-2" id="suggestions-count"></span>
                    </h5>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-sm" id="suggestions-table">
                            <thead>
                                <tr>
                                    <th width="5%">
                                        <input type="checkbox" id="select-all-suggestions" class="form-check-input">
                                    </th>
                                    <th>NGauge Field</th>
                                    <th>Suggested Magento Field</th>
                                    <th>Confidence</th>
                                    <th>Reason</th>
                                </tr>
                            </thead>
                            <tbody id="suggestions-tbody">
                                <!-- Populated via JavaScript -->
                            </tbody>
                        </table>
                    </div>
                    <div class="mt-3">
                        <button type="button" class="btn btn-success" id="apply-selected-suggestions">
                            <i class="fas fa-check"></i> Apply Selected Suggestions
                        </button>
                        <button type="button" class="btn btn-secondary" id="hide-suggestions">
                            <i class="fas fa-times"></i> Hide Suggestions
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Validation Results -->
    <div id="validation-results" style="display: none;"></div>
</div>

<!-- Mapping Row Template -->
<script type="text/template" id="mapping-row-template">
    <tr data-ngauge-field="{ngaugeField}" data-magento-field="{magentoField}">
        <td>
            <strong>{ngaugeLabel}</strong>
            <small class="text-muted d-block">{ngaugeField}</small>
        </td>
        <td>
            <select class="form-control form-control-sm magento-field-select" data-ngauge="{ngaugeField}">
                <option value="">-- Select Magento Field --</option>
                {magentoOptions}
            </select>
        </td>
        <td>
            <span class="compatibility-badge">{compatibility}</span>
        </td>
        <td>
            <button type="button" class="btn btn-sm btn-outline-danger remove-mapping" data-ngauge="{ngaugeField}">
                <i class="fas fa-trash"></i>
            </button>
        </td>
    </tr>
</script>

<?php
// Pass data to JavaScript
$jsData = [
    'ngaugeFields' => $ngaugeFields,
    'magentoFields' => $magentoFields,
    'suggestions' => $suggestions,
    'currentMapping' => $currentMapping,
    'urls' => [
        'getSuggestions' => Url::to(['get-suggestions']),
        'validateMapping' => Url::to(['validate-mapping']),
        'save' => Url::to(['save']),
        'resetToSuggestions' => Url::to(['reset-to-suggestions'])
    ]
];

$this->registerJs("
var fieldMappingData = " . \yii\helpers\Json::encode($jsData) . ";
", \yii\web\View::POS_HEAD);
?>

<?php $this->registerJsFile('@web/js/magento-field-mapping.js', ['depends' => [\yii\web\JqueryAsset::class]]); ?>

<style>
.field-item {
    cursor: pointer;
    transition: background-color 0.2s;
}

.field-item:hover {
    background-color: #f8f9fa;
}

.field-item.dragging {
    opacity: 0.5;
}

.field-item.drag-over {
    background-color: #e3f2fd;
    border-left: 4px solid #2196f3;
}

.compatibility-good {
    color: #28a745;
}

.compatibility-warning {
    color: #ffc107;
}

.compatibility-error {
    color: #dc3545;
}

.category-header {
    font-weight: 600;
    position: sticky;
    top: 0;
    z-index: 1;
}

.confidence-bar {
    height: 4px;
    border-radius: 2px;
    margin-top: 2px;
}

.confidence-high {
    background-color: #28a745;
}

.confidence-medium {
    background-color: #ffc107;
}

.confidence-low {
    background-color: #dc3545;
}

#mappings-table tbody tr {
    border-left: 4px solid transparent;
}

#mappings-table tbody tr.mapping-valid {
    border-left-color: #28a745;
}

#mappings-table tbody tr.mapping-warning {
    border-left-color: #ffc107;
}

#mappings-table tbody tr.mapping-error {
    border-left-color: #dc3545;
}

.field-item.clickable {
    cursor: pointer;
    border: 2px dashed transparent;
    transition: all 0.2s;
}

.field-item.clickable:hover {
    border-color: #007bff;
    background-color: #f8f9fa;
}

.field-item.selected {
    border-color: #28a745;
    background-color: #d4edda;
}

.mapping-mode-notice {
    background-color: #fff3cd;
    border: 1px solid #ffeaa7;
    color: #856404;
    padding: 10px;
    border-radius: 4px;
    margin-bottom: 20px;
}
</style>