<?php

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

/** @var yii\web\View $this */
/** @var yii\data\ArrayDataProvider $mainProvider */
/** @var yii\data\ArrayDataProvider $processedProvider */
/** @var string $mainPath */
/** @var string $processedPath */
/** @var string|null $error */

$this->title = 'Indicator Remote Files';
$this->params['breadcrumbs'][] = ['label' => 'Indicator Configuration', 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;

$csrfToken = Yii::$app->request->getCsrfToken();
?>

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

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

    <?php if (Yii::$app->session->hasFlash('error')): ?>
        <div class="alert alert-danger alert-dismissible fade show" role="alert">
            <?= Html::encode(Yii::$app->session->getFlash('error')) ?>
            <button type="button" class="close" data-dismiss="alert"><span>&times;</span></button>
        </div>
    <?php endif; ?>

    <?php if ($error): ?>
        <div class="alert alert-danger"><?= Html::encode($error) ?></div>
    <?php else: ?>

    <div class="card mb-4">
        <div class="card-header">
            <h5 class="mb-0">Main folder &mdash; <code><?= Html::encode($mainPath) ?></code></h5>
        </div>
        <div class="card-body p-0">
            <?= GridView::widget([
                'dataProvider' => $mainProvider,
                'tableOptions' => ['class' => 'table table-sm table-bordered table-hover mb-0'],
                'emptyText'    => 'No XML files found in main folder',
                'columns'      => [
                    [
                        'attribute' => 'name',
                        'label'     => 'Filename',
                    ],
                    [
                        'attribute' => 'size',
                        'label'     => 'Size',
                        'contentOptions' => ['class' => 'text-nowrap'],
                        'headerOptions' => ['style' => 'width:80px'],
                    ],
                    [
                        'attribute' => 'modified',
                        'label'     => 'Modified',
                        'contentOptions' => ['class' => 'text-nowrap'],
                        'headerOptions' => ['style' => 'width:150px'],
                    ],
                ],
            ]) ?>
        </div>
    </div>

    <div class="card mb-4">
        <div class="card-header d-flex justify-content-between align-items-center">
            <h5 class="mb-0">Processed folder &mdash; <code><?= Html::encode($processedPath) ?></code></h5>
            <button type="button" class="btn btn-sm btn-outline-warning" id="archive-btn">Archive files &gt;3 months old</button>
        </div>
        <div class="card-body p-0">
            <?= GridView::widget([
                'dataProvider' => $processedProvider,
                'tableOptions' => ['class' => 'table table-sm table-bordered table-hover mb-0'],
                'emptyText'    => 'No XML files found in processed folder',
                'columns'      => [
                    [
                        'attribute' => 'name',
                        'label'     => 'Filename',
                    ],
                    [
                        'attribute' => 'size',
                        'label'     => 'Size',
                        'contentOptions' => ['class' => 'text-nowrap'],
                        'headerOptions' => ['style' => 'width:80px'],
                    ],
                    [
                        'attribute' => 'modified',
                        'label'     => 'Modified',
                        'contentOptions' => ['class' => 'text-nowrap'],
                        'headerOptions' => ['style' => 'width:150px'],
                    ],
                    [
                        'class'    => 'yii\grid\ActionColumn',
                        'template' => '{move-back}',
                        'headerOptions' => ['style' => 'width:100px'],
                        'buttons'  => [
                            'move-back' => function ($url, $model, $key) {
                                return Html::beginForm(['/indicator/config/move-file'], 'post', ['style' => 'display:inline'])
                                    . Html::hiddenInput('file', $model['name'])
                                    . Html::hiddenInput('from', 'processed')
                                    . Html::submitButton('Move back', [
                                        'class' => 'btn btn-sm btn-warning',
                                        'onclick' => 'return confirm(\'Move "' . addslashes($model['name']) . '" back to the main folder?\');',
                                    ])
                                    . Html::endForm();
                            },
                        ],
                    ],
                ],
            ]) ?>
        </div>
    </div>

    <?php endif; ?>
</div>

<script>
document.addEventListener('DOMContentLoaded', function () {
    const archiveBtn = document.getElementById('archive-btn');
    if (!archiveBtn) return;

    archiveBtn.addEventListener('click', function () {
        if (!confirm('Archive processed XML files older than 3 months?\n\nFiles will be grouped into monthly ZIP archives uploaded to processed/archive/, then the originals will be deleted.')) return;

        archiveBtn.disabled = true;
        archiveBtn.textContent = 'Archiving...';

        fetch('<?= Yii::$app->urlManager->createUrl(['/indicator/config/archive-processed']) ?>', {
            method: 'POST',
            headers: {
                'X-Requested-With': 'XMLHttpRequest',
                'X-CSRF-Token': '<?= $csrfToken ?>',
            },
        })
        .then(r => r.json())
        .then(data => {
            alert((data.success ? '\u2713 ' : '\u2717 ') + data.message
                + (data.errors && data.errors.length ? '\n\nErrors:\n' + data.errors.join('\n') : ''));
            if (data.archived > 0) location.reload();
        })
        .catch(err => alert('Error: ' + err.message))
        .finally(() => {
            archiveBtn.disabled = false;
            archiveBtn.textContent = 'Archive files >3 months old';
        });
    });
});
</script>
