<?php

use yii\helpers\Html;
use yii\grid\GridView;
use yii\widgets\Pjax;

$this->title = 'Package Manager';
$this->params['breadcrumbs'][] = $this->title;
?>

<div class="package-manager-index">
    <h1><?= Html::encode($this->title) ?></h1>

    <div class="row">
        <div class="col-md-12">
            <div class="box box-primary">
                <div class="box-header with-border">
                    <h3 class="box-title">Available Packages from Satis Repository</h3>
                </div>
                <div class="box-body">
                    <?php Pjax::begin(['id' => 'packages-pjax']); ?>
                    
                    <table class="table table-striped table-bordered">
                        <thead>
                            <tr>
                                <th>Package Name</th>
                                <th>Description</th>
                                <th>Latest Version</th>
                                <th>Installed Version</th>
                                <th>Status</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($satisPackages)): ?>
                                <tr>
                                    <td colspan="6" class="text-center">
                                        <em>No packages available from Satis repository</em>
                                    </td>
                                </tr>
                            <?php else: ?>
                                <?php foreach ($satisPackages as $packageName => $packageData): ?>
                                    <?php
                                    $isInstalled = isset($installedPackages[$packageName]);
                                    $installedVersion = $isInstalled ? $installedPackages[$packageName] : null;
                                    ?>
                                    <tr>
                                        <td><strong><?= Html::encode($packageName) ?></strong></td>
                                        <td><?= Html::encode($packageData['description'] ?? 'No description') ?></td>
                                        <td>
                                            <span class="label label-info">
                                                <?= Html::encode($packageData['version'] ?? 'N/A') ?>
                                            </span>
                                        </td>
                                        <td>
                                            <?php if ($isInstalled): ?>
                                                <span class="label label-success">
                                                    <?= Html::encode($installedVersion) ?>
                                                </span>
                                            <?php else: ?>
                                                <span class="label label-default">Not installed</span>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <?php if ($isInstalled): ?>
                                                <span class="badge badge-success">
                                                    <i class="fa fa-check"></i> Installed
                                                </span>
                                            <?php else: ?>
                                                <span class="badge badge-secondary">
                                                    <i class="fa fa-times"></i> Not installed
                                                </span>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <?php if ($isInstalled): ?>
                                                <?= Html::button('<i class="fa fa-refresh"></i> Update', [
                                                    'class' => 'btn btn-warning btn-sm btn-update',
                                                    'data-package' => $packageName,
                                                ]) ?>
                                                <?= Html::button('<i class="fa fa-trash"></i> Remove', [
                                                    'class' => 'btn btn-danger btn-sm btn-delete',
                                                    'data-package' => $packageName,
                                                ]) ?>
                                            <?php else: ?>
                                                <?= Html::button('<i class="fa fa-download"></i> Install', [
                                                    'class' => 'btn btn-success btn-sm btn-install',
                                                    'data-package' => $packageName,
                                                    'data-version' => $packageData['version'] ?? '*',
                                                ]) ?>
                                            <?php endif; ?>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                    
                    <?php Pjax::end(); ?>
                </div>
            </div>
        </div>
    </div>

    <!-- Output Modal -->
    <div class="modal fade" id="outputModal" tabindex="-1" role="dialog">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                    <h4 class="modal-title">Composer Output</h4>
                </div>
                <div class="modal-body">
                    <pre id="composer-output" style="max-height: 400px; overflow-y: auto;"></pre>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>
</div>

<?php
$installUrl = \yii\helpers\Url::to(['package-manager/install']);
$updateUrl = \yii\helpers\Url::to(['package-manager/update']);
$deleteUrl = \yii\helpers\Url::to(['package-manager/delete']);

$js = <<<JS
// Install package
$(document).on('click', '.btn-install', function() {
    var btn = $(this);
    var packageName = btn.data('package');
    var version = btn.data('version');
    
    if (!confirm('Install package "' + packageName + '"?')) {
        return;
    }
    
    btn.prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i> Installing...');
    
    $.ajax({
        url: '{$installUrl}',
        type: 'POST',
        data: {
            package: packageName,
            version: version,
            _csrf: yii.getCsrfToken()
        },
        success: function(response) {
            if (response.success) {
                $('#composer-output').text(response.output);
                $('#outputModal').modal('show');
                $.pjax.reload({container: '#packages-pjax'});
            } else {
                alert('Error: ' + response.message);
                btn.prop('disabled', false).html('<i class="fa fa-download"></i> Install');
            }
        },
        error: function() {
            alert('An error occurred');
            btn.prop('disabled', false).html('<i class="fa fa-download"></i> Install');
        }
    });
});

// Update package
$(document).on('click', '.btn-update', function() {
    var btn = $(this);
    var packageName = btn.data('package');
    
    if (!confirm('Update package "' + packageName + '"?')) {
        return;
    }
    
    btn.prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i> Updating...');
    
    $.ajax({
        url: '{$updateUrl}',
        type: 'POST',
        data: {
            package: packageName,
            _csrf: yii.getCsrfToken()
        },
        success: function(response) {
            if (response.success) {
                $('#composer-output').text(response.output);
                $('#outputModal').modal('show');
                $.pjax.reload({container: '#packages-pjax'});
            } else {
                alert('Error: ' + response.message);
                btn.prop('disabled', false).html('<i class="fa fa-refresh"></i> Update');
            }
        },
        error: function() {
            alert('An error occurred');
            btn.prop('disabled', false).html('<i class="fa fa-refresh"></i> Update');
        }
    });
});

// Delete package
$(document).on('click', '.btn-delete', function() {
    var btn = $(this);
    var packageName = btn.data('package');
    
    if (!confirm('Remove package "' + packageName + '"? This will also update composer.json.')) {
        return;
    }
    
    btn.prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i> Removing...');
    
    $.ajax({
        url: '{$deleteUrl}',
        type: 'POST',
        data: {
            package: packageName,
            _csrf: yii.getCsrfToken()
        },
        success: function(response) {
            if (response.success) {
                $('#composer-output').text(response.output);
                $('#outputModal').modal('show');
                $.pjax.reload({container: '#packages-pjax'});
            } else {
                alert('Error: ' + response.message);
                btn.prop('disabled', false).html('<i class="fa fa-trash"></i> Remove');
            }
        },
        error: function() {
            alert('An error occurred');
            btn.prop('disabled', false).html('<i class="fa fa-trash"></i> Remove');
        }
    });
});
JS;

$this->registerJs($js);
?>
