<?php
use yii\helpers\Html;
use yii\helpers\Url;

/* @var $this yii\web\View */
/* @var $model backend\models\Cartsbe */
?>

<div class="magento-sync-tab">
    <div class="row">
        <div class="col-md-12">
            <h4><?= Yii::t('app', 'Magento Synchronization') ?></h4>
            
            <?php 
            $magentoConfig = Yii::$app->params['plugins']['magento'] ?? [];
            $magentoEnabled = $magentoConfig['enabled'] ?? false;
            $hasMagentoId = !empty($model->magento_order_id);
            ?>
            
            <div class="card">
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-6">
                            <h5><?= Yii::t('app', 'Magento Configuration') ?></h5>
                            <div class="form-group">
                                <label class="font-weight-bold"><?= Yii::t('app', 'Status') ?>:</label>
                                <div>
                                    <?php if ($magentoEnabled): ?>
                                        <span class="badge badge-success">
                                            <i class="fas fa-check"></i> <?= Yii::t('app', 'Enabled') ?>
                                        </span>
                                    <?php else: ?>
                                        <span class="badge badge-danger">
                                            <i class="fas fa-times"></i> <?= Yii::t('app', 'Disabled') ?>
                                        </span>
                                    <?php endif; ?>
                                </div>
                            </div>
                            
                            <?php if ($magentoEnabled): ?>
                            <div class="form-group">
                                <label class="font-weight-bold"><?= Yii::t('app', 'API URL') ?>:</label>
                                <div><?= $magentoConfig['apiUrl'] ?? 'Not configured' ?></div>
                            </div>
                            
                            <div class="form-group">
                                <label class="font-weight-bold"><?= Yii::t('app', 'Store Code') ?>:</label>
                                <div><?= $magentoConfig['storeCode'] ?? 'default' ?></div>
                            </div>
                            
                            <div class="form-group">
                                <label class="font-weight-bold"><?= Yii::t('app', 'Auto Sync') ?>:</label>
                                <div>
                                    <?php if ($magentoConfig['autoSync'] ?? false): ?>
                                        <span class="badge badge-success"><?= Yii::t('app', 'Enabled') ?></span>
                                    <?php else: ?>
                                        <span class="badge badge-warning"><?= Yii::t('app', 'Disabled') ?></span>
                                    <?php endif; ?>
                                </div>
                            </div>
                            <?php endif; ?>
                        </div>
                        
                        <div class="col-md-6">
                            <h5><?= Yii::t('app', 'Sync Status') ?></h5>
                            
                            <div class="form-group">
                                <label class="font-weight-bold"><?= Yii::t('app', 'Magento Order ID') ?>:</label>
                                <div>
                                    <?php if ($hasMagentoId): ?>
                                        <span class="text-success">
                                            <i class="fas fa-check-circle"></i>
                                            <?= Html::a($model->magento_order_id, $magentoConfig['apiUrl'] . 'admin/sales/order/view/order_id/' . $model->magento_order_id, ['target' => '_blank', 'class' => 'text-primary']) ?>
                                        </span>
                                    <?php else: ?>
                                        <span class="text-warning">
                                            <i class="fas fa-exclamation-triangle"></i>
                                            <?= Yii::t('app', 'Not synced to Magento') ?>
                                        </span>
                                    <?php endif; ?>
                                </div>
                            </div>
                            
                            <div class="form-group">
                                <label class="font-weight-bold"><?= Yii::t('app', 'Last Sync') ?>:</label>
                                <div><?= $model->magento_sync_date ?? Yii::t('app', 'Never') ?></div>
                            </div>
                            
                            <div class="form-group">
                                <label class="font-weight-bold"><?= Yii::t('app', 'Customer Sync Status') ?>:</label>
                                <div>
                                    <?php if (!empty($model->magento_customer_id)): ?>
                                        <span class="badge badge-success"><?= Yii::t('app', 'Synced') ?></span>
                                        <small class="text-muted">(ID: <?= $model->magento_customer_id ?>)</small>
                                    <?php else: ?>
                                        <span class="badge badge-warning"><?= Yii::t('app', 'Not Synced') ?></span>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <?php if ($magentoEnabled && (Yii::$app->user->identity->inGroup('Global Admins') || Yii::$app->user->identity->inGroup('Sales Admin'))): ?>
    <div class="row mt-3">
        <div class="col-md-12">
            <h5><?= Yii::t('app', 'Sync Actions') ?></h5>
            <div class="card">
                <div class="card-body">
                    <div class="btn-group mb-2" role="group">
                        <?= Html::button(Yii::t('app', 'Sync Customer'), [
                            'class' => 'btn btn-primary',
                            'id' => 'sync-customer-btn',
                            'onclick' => 'syncCustomerToMagento("' . $model->id . '")'
                        ]) ?>
                        
                        <?= Html::button(Yii::t('app', 'Check Stock'), [
                            'class' => 'btn btn-warning',
                            'id' => 'check-stock-btn',
                            'onclick' => 'checkMagentoStock("' . $model->id . '")'
                        ]) ?>
                        
                        <?php if ($model->billingstatus === 'paid'): ?>
                        <?= Html::button(Yii::t('app', 'Create Magento Order'), [
                            'class' => 'btn btn-success',
                            'id' => 'create-order-btn',
                            'onclick' => 'createMagentoOrder("' . $model->id . '")',
                            'disabled' => $hasMagentoId
                        ]) ?>
                        <?php endif; ?>
                        
                        <?php if ($hasMagentoId): ?>
                        <?= Html::button(Yii::t('app', 'Refresh Status'), [
                            'class' => 'btn btn-secondary',
                            'id' => 'refresh-status-btn',
                            'onclick' => 'refreshMagentoStatus("' . $model->id . '")'
                        ]) ?>
                        <?php endif; ?>
                    </div>
                    
                    <div class="alert alert-info">
                        <i class="fas fa-info-circle"></i>
                        <?= Yii::t('app', 'Magento sync actions will create corresponding records in your Magento store.') ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <?php endif; ?>
    
    <div class="row mt-3">
        <div class="col-md-12">
            <h5><?= Yii::t('app', 'Cart Items Availability') ?></h5>
            <div class="card">
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-sm">
                            <thead>
                                <tr>
                                    <th><?= Yii::t('app', 'Product') ?></th>
                                    <th><?= Yii::t('app', 'SKU') ?></th>
                                    <th><?= Yii::t('app', 'Qty Ordered') ?></th>
                                    <th><?= Yii::t('app', 'Magento Stock') ?></th>
                                    <th><?= Yii::t('app', 'Status') ?></th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($model->cartlines as $line): ?>
                                <tr>
                                    <td><?= $line->product_name ?></td>
                                    <td><?= $line->product->sku ?? 'N/A' ?></td>
                                    <td><?= $line->qty ?></td>
                                    <td id="stock-<?= $line->id ?>">
                                        <span class="text-muted"><?= Yii::t('app', 'Not checked') ?></span>
                                    </td>
                                    <td id="status-<?= $line->id ?>">
                                        <span class="badge badge-secondary"><?= Yii::t('app', 'Unknown') ?></span>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
function syncCustomerToMagento(cartId) {
    $.ajax({
        url: '<?= Url::to(['/magento/sync-customer']) ?>',
        type: 'POST',
        data: { cartId: cartId },
        success: function(response) {
            if (response.success) {
                alert('<?= Yii::t('app', 'Customer synced to Magento successfully') ?>');
                location.reload();
            } else {
                alert('<?= Yii::t('app', 'Error syncing customer') ?>: ' + response.message);
            }
        },
        error: function() {
            alert('<?= Yii::t('app', 'Network error occurred') ?>');
        }
    });
}

function checkMagentoStock(cartId) {
    $('#check-stock-btn').prop('disabled', true).text('<?= Yii::t('app', 'Checking...') ?>');
    
    $.ajax({
        url: '<?= Url::to(['/magento/check-stock']) ?>',
        type: 'GET',
        data: { cartId: cartId },
        success: function(response) {
            if (response.success) {
                // Update stock information in the table
                $.each(response.stock, function(lineId, stockInfo) {
                    $('#stock-' + lineId).html(stockInfo.qty);
                    $('#status-' + lineId).html('<span class="badge badge-' + 
                        (stockInfo.available ? 'success' : 'danger') + '">' + 
                        (stockInfo.available ? '<?= Yii::t('app', 'Available') ?>' : '<?= Yii::t('app', 'Out of Stock') ?>') + 
                        '</span>');
                });
                alert('<?= Yii::t('app', 'Stock check completed') ?>');
            } else {
                alert('<?= Yii::t('app', 'Error checking stock') ?>: ' + response.message);
            }
        },
        error: function() {
            alert('<?= Yii::t('app', 'Network error occurred') ?>');
        },
        complete: function() {
            $('#check-stock-btn').prop('disabled', false).text('<?= Yii::t('app', 'Check Stock') ?>');
        }
    });
}

function createMagentoOrder(cartId) {
    if (confirm('<?= Yii::t('app', 'Create a new order in Magento for this cart?') ?>')) {
        $.ajax({
            url: '<?= Url::to(['/magento/create-order']) ?>',
            type: 'POST',
            data: { cartId: cartId },
            success: function(response) {
                if (response.success) {
                    alert('<?= Yii::t('app', 'Magento order created successfully') ?>');
                    location.reload();
                } else {
                    alert('<?= Yii::t('app', 'Error creating Magento order') ?>: ' + response.message);
                }
            },
            error: function() {
                alert('<?= Yii::t('app', 'Network error occurred') ?>');
            }
        });
    }
}

function refreshMagentoStatus(cartId) {
    $.ajax({
        url: '<?= Url::to(['/magento/refresh-status']) ?>',
        type: 'GET',
        data: { cartId: cartId },
        success: function(response) {
            if (response.success) {
                alert('<?= Yii::t('app', 'Magento status refreshed') ?>');
                location.reload();
            } else {
                alert('<?= Yii::t('app', 'Error refreshing status') ?>');
            }
        },
        error: function() {
            alert('<?= Yii::t('app', 'Network error occurred') ?>');
        }
    });
}
</script>