<?php

use yii\helpers\Html;
use yii\bootstrap4\ActiveForm;

/** @var yii\web\View $this */
/** @var PortalPeople\indicator\models\ConfigForm $model */
/** @var yii\bootstrap4\ActiveForm $form */

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

<div class="indicator-config">
    <h1><?= Html::encode($this->title) ?></h1>

    <?php if (Yii::$app->session->hasFlash('success')): ?>
        <div class="alert alert-success alert-dismissible fade show" role="alert">
            <?= Yii::$app->session->getFlash('success') ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>

    <div class="row">
        <div class="col-md-8">
            <?php $form = ActiveForm::begin(['id' => 'indicator-config-form']); ?>

            <div class="card mb-4">
                <div class="card-header">
                    <h5 class="mb-0">Order Processing</h5>
                </div>
                <div class="card-body">
                    <?= $form->field($model, 'cartClass')->dropDownList(
                        \PortalPeople\indicator\models\ConfigForm::cartClassOptions(),
                        ['prompt' => '-- Select Cart Class --']
                    )->hint('The Cart model used to create orders from imported files') ?>
                </div>
            </div>

            <div class="card mb-4">
                <div class="card-header">
                    <h5 class="mb-0">FTP/SFTP Connection</h5>
                </div>
                <div class="card-body">
                    <?= $form->field($model, 'protocol')->dropDownList([
                        'ftp' => 'FTP',
                        'ftps' => 'FTPS (explicit TLS)',
                        'sftp' => 'SFTP',
                    ]) ?>

                    <?= $form->field($model, 'ftpHost') ?>
                    <?= $form->field($model, 'ftpPort') ?>
                    <?= $form->field($model, 'ftpUser') ?>
                    <?= $form->field($model, 'ftpPassword')->passwordInput() ?>
                    <?= $form->field($model, 'ftpPath') ?>

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

                    <hr>
                    <p class="text-muted small">After download, choose one action:</p>
                    <?= $form->field($model, 'deleteAfterDownload')->checkbox() ?>
                    <?= $form->field($model, 'moveAfterDownload')->checkbox(['id' => 'move-after-download-cb']) ?>
                    <div id="move-to-path-wrap"<?= $model->moveAfterDownload ? '' : ' style="display:none"' ?>>
                        <?= $form->field($model, 'moveToPath')->textInput(['placeholder' => '/processed'])->hint('Remote path to move files to after download') ?>
                    </div>
                </div>
            </div>

            <div class="card mb-4">
                <div class="card-header">
                    <h5 class="mb-0">Scheduling</h5>
                </div>
                <div class="card-body">
                    <?= $form->field($model, 'downloadInterval')->hint('Seconds between file downloads') ?>
                    <?= $form->field($model, 'processInterval')->hint('Seconds between order processing') ?>
                </div>
            </div>

            <div class="card mb-4">
                <div class="card-header">
                    <h5 class="mb-0">Notifications</h5>
                </div>
                <div class="card-body">
                    <?= $form->field($model, 'summaryEmail')->hint('Optional: Email address for import summaries') ?>
                </div>
            </div>

            <div class="form-group">
                <?= Html::submitButton('Save Configuration', ['class' => 'btn btn-primary']) ?>
                <?= Html::button('Test Connection', ['class' => 'btn btn-secondary', 'id' => 'test-btn']) ?>
                <?= Html::button('Dry Run', ['class' => 'btn btn-info', 'id' => 'dry-run-btn']) ?>
            </div>

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

        <div class="col-md-4">
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-0">Status</h5>
                </div>
                <div class="card-body">
                    <p><strong>Inbox:</strong> <span id="status-inbox">-</span> files</p>
                    <p><strong>Processed:</strong> <span id="status-processed">-</span> files</p>
                    <p><strong>Failed:</strong> <span id="status-failed">-</span> files</p>
                    <?= Html::button('Refresh Status', ['class' => 'btn btn-sm btn-outline-secondary', 'id' => 'refresh-status-btn']) ?>
                </div>
            </div>
        </div>
    </div>

    <div class="row mt-4">
        <div class="col-12">
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-0">Remote Files</h5>
                </div>
                <div class="card-body">
                    <p class="text-muted">Browse and manage XML files on the remote FTP server.</p>
                    <?= Html::a('View Remote Files', ['/indicator/config/files'], ['class' => 'btn btn-outline-primary']) ?>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const form = document.getElementById('indicator-config-form');
    const testBtn = document.getElementById('test-btn');
    const dryRunBtn = document.getElementById('dry-run-btn');
    const refreshBtn = document.getElementById('refresh-status-btn');
    const moveCb = document.getElementById('move-after-download-cb');
    const moveWrap = document.getElementById('move-to-path-wrap');

    if (moveCb && moveWrap) {
        moveCb.addEventListener('change', function() {
            moveWrap.style.display = this.checked ? '' : 'none';
        });
    }

    refreshStatus();

    testBtn.addEventListener('click', function(e) {
        e.preventDefault();
        if (!form.checkValidity()) {
            alert('Please fix validation errors first');
            return;
        }

        const formData = new FormData(form);
        fetch('<?= Yii::$app->urlManager->createUrl(['/indicator/config/test-connection']) ?>', {
            method: 'POST',
            body: formData,
            headers: {
                'X-Requested-With': 'XMLHttpRequest'
            }
        })
        .then(r => r.json())
        .then(data => {
            if (data.success) {
                alert('✓ Connection successful!');
            } else {
                alert('✗ Connection failed:\n' + (data.errors ? Object.values(data.errors).flat().join('\n') : data.message));
            }
        })
        .catch(err => alert('Error: ' + err.message));
    });

    dryRunBtn.addEventListener('click', function(e) {
        e.preventDefault();
        dryRunBtn.disabled = true;
        dryRunBtn.textContent = 'Running...';

        fetch('<?= Yii::$app->urlManager->createUrl(['/indicator/config/dry-run']) ?>', {
            method: 'POST',
            headers: {
                'X-Requested-With': 'XMLHttpRequest',
                'X-CSRF-Token': '<?= Yii::$app->request->getCsrfToken() ?>'
            }
        })
        .then(r => r.json())
        .then(data => {
            if (data.success) {
                alert('✓ Dry run complete\nFound ' + data.downloaded + ' files to download');
            } else {
                alert('✗ Dry run failed: ' + data.message);
            }
        })
        .catch(err => alert('Error: ' + err.message))
        .finally(() => {
            dryRunBtn.disabled = false;
            dryRunBtn.textContent = 'Dry Run';
        });
    });

    refreshBtn.addEventListener('click', refreshStatus);

    function refreshStatus() {
        fetch('<?= Yii::$app->urlManager->createUrl(['/indicator/config/status']) ?>', {
            headers: {'X-Requested-With': 'XMLHttpRequest'}
        })
        .then(r => r.json())
        .then(data => {
            if (data.success) {
                document.getElementById('status-inbox').textContent = data.inbox;
                document.getElementById('status-processed').textContent = data.processed;
                document.getElementById('status-failed').textContent = data.failed;
            }
        });
    }
});
</script>
