<?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 - Zarządzanie ofertą taryf (admin)
 */

require_once __DIR__ . '/../inc/tariff_offers.php';

$config = tariff_offers_load();
$msg = '';
$msg_type = '';

// Obsługa zapisu
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_tariff_offers'])) {
    if (ibok_is_demo()) {
        $msg = __('demo.save_blocked');
        $msg_type = 'warning';
    } elseif (!csrf_validate()) {
        $msg = __('login.error_csrf');
        $msg_type = 'danger';
    } else {
        $config['enabled'] = !empty($_POST['enabled']);

        // Parse excluded clients (one per line)
        $config['excluded_clients'] = array_values(array_filter(
            array_map('trim', explode("\n", $_POST['excluded_clients'] ?? '')),
            function($v) { return $v !== ''; }
        ));

        // Parse offers from POST arrays
        $offers = [];
        $names = $_POST['offer_name'] ?? [];
        $dls = $_POST['offer_dl'] ?? [];
        $uls = $_POST['offer_ul'] ?? [];
        $prices = $_POST['offer_price'] ?? [];
        $descs = $_POST['offer_description'] ?? [];

        for ($i = 0; $i < count($names); $i++) {
            if (empty(trim($names[$i] ?? ''))) continue;
            $offers[] = [
                'name'        => trim($names[$i] ?? ''),
                'dl'          => trim($dls[$i] ?? ''),
                'ul'          => trim($uls[$i] ?? ''),
                'price'       => trim($prices[$i] ?? ''),
                'description' => trim($descs[$i] ?? ''),
            ];
        }
        $config['offers'] = $offers;

        if (tariff_offers_save($config)) {
            $config = tariff_offers_load();
            $msg = __('tariff_change.admin_saved');
            $msg_type = 'success';
            ibok_log("Tariff offers configuration saved", 'info');
        } else {
            $msg = __('common.error');
            $msg_type = 'danger';
        }
    }
}

$excluded_text = implode("\n", $config['excluded_clients'] ?? []);
?>

<div class="fade-in">
    <h4 class="mb-4">
        <i class="bi bi-arrow-left-right me-2"></i> <?= __('tariff_change.admin_title') ?>
    </h4>

    <?= ibok_help_section('admin_tariff', __('help.show_help'), __('help_admin.tariff_section_content')) ?>

    <?php if ($msg): ?>
        <div class="alert alert-<?= $msg_type ?> alert-dismissible fade show">
            <i class="bi bi-<?= $msg_type === 'success' ? 'check-circle' : 'exclamation-triangle' ?> me-1"></i>
            <?= e($msg) ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>

    <form method="post" action="admin.php?page=tariff_offers" id="tariffForm">
        <?= csrf_field() ?>
        <input type="hidden" name="save_tariff_offers" value="1">

        <!-- Ustawienia ogólne -->
        <div class="card mb-4">
            <div class="card-header">
                <i class="bi bi-gear me-1"></i> <?= __('tariff_change.admin_settings') ?>
            </div>
            <div class="card-body">
                <div class="form-check form-switch mb-3">
                    <input class="form-check-input" type="checkbox" id="enabled" name="enabled" value="1"
                           <?= $config['enabled'] ? 'checked' : '' ?>>
                    <label class="form-check-label" for="enabled">
                        <?= __('tariff_change.admin_enabled') ?>
                    </label>
                    <div class="form-text"><?= __('tariff_change.admin_enabled_desc') ?></div>
                </div>

                <div class="mb-0">
                    <label for="excluded_clients" class="form-label"><?= __('tariff_change.admin_excluded') ?></label>
                    <textarea class="form-control font-monospace" id="excluded_clients" name="excluded_clients"
                              rows="3" placeholder="<?= __('tariff_change.admin_excluded_placeholder') ?>"><?= e($excluded_text) ?></textarea>
                    <div class="form-text"><?= __('tariff_change.admin_excluded_desc') ?></div>
                </div>
            </div>
        </div>

        <!-- Oferty taryf -->
        <div class="card mb-4">
            <div class="card-header d-flex justify-content-between align-items-center">
                <span><i class="bi bi-list-ul me-1"></i> <?= __('tariff_change.admin_offers') ?></span>
                <button type="button" class="btn btn-sm btn-outline-primary" id="addOffer">
                    <i class="bi bi-plus-lg me-1"></i> <?= __('tariff_change.admin_add_offer') ?>
                </button>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-sm align-middle mb-0" id="offersTable">
                        <thead class="table-light">
                            <tr>
                                <th style="width: 30px"></th>
                                <th><?= __('tariff_change.offer_name') ?><?= ibok_tooltip(__('help_admin.tooltip_tariff_name')) ?></th>
                                <th><?= __('tariff_change.offer_dl') ?><?= ibok_tooltip(__('help_admin.tooltip_tariff_speed')) ?></th>
                                <th><?= __('tariff_change.offer_ul') ?></th>
                                <th><?= __('tariff_change.offer_price') ?><?= ibok_tooltip(__('help_admin.tooltip_tariff_price')) ?></th>
                                <th><?= __('tariff_change.offer_description') ?></th>
                                <th style="width: 50px"></th>
                            </tr>
                        </thead>
                        <tbody id="offersBody">
                            <?php foreach ($config['offers'] as $i => $offer): ?>
                            <tr>
                                <td class="text-muted text-center"><i class="bi bi-grip-vertical"></i></td>
                                <td><input type="text" class="form-control form-control-sm" name="offer_name[]" value="<?= e($offer['name']) ?>" required></td>
                                <td><input type="text" class="form-control form-control-sm" name="offer_dl[]" value="<?= e($offer['dl']) ?>" placeholder="np. 100 Mb/s"></td>
                                <td><input type="text" class="form-control form-control-sm" name="offer_ul[]" value="<?= e($offer['ul']) ?>" placeholder="np. 20 Mb/s"></td>
                                <td><input type="text" class="form-control form-control-sm" name="offer_price[]" value="<?= e($offer['price']) ?>" placeholder="np. 59,99 zł/mies."></td>
                                <td><input type="text" class="form-control form-control-sm" name="offer_description[]" value="<?= e($offer['description']) ?>"></td>
                                <td><button type="button" class="btn btn-sm btn-outline-danger remove-offer" title="<?= __('common.delete') ?>"><i class="bi bi-trash"></i></button></td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
                <div id="noOffers" class="text-center text-muted py-3 <?= !empty($config['offers']) ? 'd-none' : '' ?>">
                    <?= __('tariff_change.admin_no_offers') ?>
                </div>
            </div>
        </div>

        <button type="submit" class="btn btn-primary">
            <i class="bi bi-check-lg me-1"></i> <?= __('common.save') ?>
        </button>
    </form>
</div>

<script nonce="<?= csp_nonce() ?>">
(function() {
    var body = document.getElementById('offersBody');
    var noMsg = document.getElementById('noOffers');

    function updateNoMsg() {
        if (body.querySelectorAll('tr').length === 0) {
            noMsg.classList.remove('d-none');
        } else {
            noMsg.classList.add('d-none');
        }
    }

    function createRow(name, dl, ul, price, desc) {
        var tr = document.createElement('tr');
        tr.innerHTML =
            '<td class="text-muted text-center"><i class="bi bi-grip-vertical"></i></td>' +
            '<td><input type="text" class="form-control form-control-sm" name="offer_name[]" value="' + (name||'') + '" required></td>' +
            '<td><input type="text" class="form-control form-control-sm" name="offer_dl[]" value="' + (dl||'') + '" placeholder="np. 100 Mb/s"></td>' +
            '<td><input type="text" class="form-control form-control-sm" name="offer_ul[]" value="' + (ul||'') + '" placeholder="np. 20 Mb/s"></td>' +
            '<td><input type="text" class="form-control form-control-sm" name="offer_price[]" value="' + (price||'') + '" placeholder="np. 59,99 zł/mies."></td>' +
            '<td><input type="text" class="form-control form-control-sm" name="offer_description[]" value="' + (desc||'') + '"></td>' +
            '<td><button type="button" class="btn btn-sm btn-outline-danger remove-offer" title="<?= __('common.delete') ?>"><i class="bi bi-trash"></i></button></td>';
        return tr;
    }

    document.getElementById('addOffer').addEventListener('click', function() {
        body.appendChild(createRow('', '', '', '', ''));
        updateNoMsg();
        body.lastElementChild.querySelector('input').focus();
    });

    body.addEventListener('click', function(e) {
        var btn = e.target.closest('.remove-offer');
        if (btn) {
            btn.closest('tr').remove();
            updateNoMsg();
        }
    });
})();
</script>
