<?php
/**
 * (c) ININOUT & PYXIS. All Rights Reserved.
 * Wszelkie modyfikacje tego pliku wymagaja zgloszenia oraz zgody autorow.
 * Any modifications to this file require notification and consent of the authors.
 */
/**
 * i-BOK 5 - Edycja plików tekstowych (admin)
 */

$editable_files = [
    'naglowek.txt'          => __('admin_edit.header'),
    'naglowek_form.txt'     => __('admin_edit.header_form'),
    'stopka.txt'            => __('admin_edit.footer'),
    'stopka_form.txt'       => __('admin_edit.footer_form'),
    'aktualnosci_start.txt' => __('admin_edit.news'),
    'pomoc_faq.txt'         => __('admin_edit.faq'),
    'termin_platnosci.txt'  => __('admin_edit.payment_terms'),
];

$save_msg = '';

// Obsługa zapisu
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_file'])) {
    if (ibok_is_demo()) {
        $save_msg = __('demo.save_blocked');
    } elseif (csrf_validate()) {
        $file_key = basename($_POST['filename'] ?? '');
        if (array_key_exists($file_key, $editable_files)) {
            $content = $_POST['content'] ?? '';
            $path = IBOK_ADMIN_DIR . '/' . $file_key;

            if (@file_put_contents($path, $content, LOCK_EX) !== false) {
                $save_msg = __('admin_edit.saved');
                ibok_log("Edycja pliku: {$file_key}", 'info');
            } else {
                $save_msg = __('admin_edit.error_save');
            }
        }
    }
}

// Aktualnie edytowany plik
$current_file = $_GET['file'] ?? '';
$current_content = '';
if (!empty($current_file) && array_key_exists($current_file, $editable_files)) {
    $path = IBOK_ADMIN_DIR . '/' . $current_file;
    if (file_exists($path)) {
        $current_content = file_get_contents($path);
        $current_content = convert_to_utf8($current_content);
    }
}
?>

<div class="fade-in">
    <h4 class="mb-4">
        <i class="bi bi-pencil me-2"></i> <?= __('admin_edit.title') ?>
    </h4>

    <?= ibok_help_section('admin_edycja', __('help.show_help'), __('help_admin.edycja_section_content')) ?>

    <?php if ($save_msg): ?>
        <div class="alert alert-<?= strpos($save_msg, 'Błąd') !== false || strpos($save_msg, 'Failed') !== false ? 'danger' : 'success' ?> alert-dismissible fade show">
            <?= e($save_msg) ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>

    <div class="row g-4">
        <!-- Lista plików -->
        <div class="col-lg-3">
            <div class="card">
                <div class="card-header">
                    <i class="bi bi-files me-1"></i> Pliki
                </div>
                <div class="list-group list-group-flush">
                    <?php foreach ($editable_files as $fname => $label):
                        $fpath = IBOK_ADMIN_DIR . '/' . $fname;
                        $ftext = file_exists($fpath) ? convert_to_utf8(@file_get_contents($fpath)) : '';
                        $fvisible = mb_strlen(strip_tags(trim($ftext))) >= 15;
                    ?>
                    <a href="admin.php?page=edycja&file=<?= urlencode($fname) ?>"
                       class="list-group-item list-group-item-action <?= $current_file === $fname ? 'active' : '' ?>">
                        <i class="bi bi-file-text me-1"></i> <?= e($label) ?>
                        <?php if (!$fvisible): ?>
                            <span class="badge bg-secondary ms-1"><?= __('admin_edit.not_visible') ?></span>
                        <?php endif; ?>
                        <br><small class="text-muted"><?= e($fname) ?></small>
                    </a>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>

        <!-- Edytor -->
        <div class="col-lg-9">
            <?php if (!empty($current_file) && array_key_exists($current_file, $editable_files)): ?>
            <div class="card">
                <div class="card-header">
                    <i class="bi bi-pencil-square me-1"></i>
                    <?= e($editable_files[$current_file]) ?>
                    <small class="text-muted ms-2">(<?= e($current_file) ?>)</small>
                </div>
                <div class="card-body">
                    <form method="post" action="admin.php?page=edycja&file=<?= urlencode($current_file) ?>">
                        <?= csrf_field() ?>
                        <input type="hidden" name="save_file" value="1">
                        <input type="hidden" name="filename" value="<?= e($current_file) ?>">

                        <div class="mb-3">
                            <textarea class="form-control font-monospace" name="content" rows="15"
                                      style="font-size: 0.9rem;"><?= e($current_content) ?></textarea>
                            <small class="form-text text-muted">
                                HTML dozwolony. <?= __('admin_edit.min_length') ?>
                            </small>
                        </div>

                        <button type="submit" class="btn btn-primary">
                            <i class="bi bi-check-lg me-1"></i> <?= __('common.save') ?>
                        </button>
                        <a href="admin.php?page=edycja" class="btn btn-outline-secondary ms-2">
                            <?= __('common.cancel') ?>
                        </a>
                    </form>
                </div>
            </div>
            <?php else: ?>
            <div class="card">
                <div class="card-body text-center text-muted py-5">
                    <i class="bi bi-arrow-left-circle" style="font-size: 2rem;"></i>
                    <p class="mt-2">Wybierz plik do edycji z listy po lewej stronie.</p>
                </div>
            </div>
            <?php endif; ?>
        </div>
    </div>
</div>
