<?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 - Funkcje pomocnicze oferty taryf
 */

if (!defined('IBOK_CFG_DIR')) {
    define('IBOK_CFG_DIR', IBOK_ROOT . '/cfg');
}

define('IBOK_TARIFF_OFFERS_FILE', IBOK_CFG_DIR . '/tariff_offers.cfg');

/**
 * Domyślna konfiguracja oferty taryf
 */
function tariff_offers_default() {
    return [
        'enabled' => false,
        'excluded_clients' => [],
        'offers' => [],
    ];
}

/**
 * Wczytaj konfigurację oferty taryf
 */
function tariff_offers_load() {
    if (!file_exists(IBOK_TARIFF_OFFERS_FILE)) {
        return tariff_offers_default();
    }

    $data = json_decode(file_get_contents(IBOK_TARIFF_OFFERS_FILE), true);
    if (!is_array($data)) {
        return tariff_offers_default();
    }

    return array_merge(tariff_offers_default(), $data);
}

/**
 * Zapisz konfigurację oferty taryf
 */
function tariff_offers_save($config) {
    $save = [
        'enabled' => (bool)($config['enabled'] ?? false),
        'excluded_clients' => array_values(array_filter(
            array_map('trim', (array)($config['excluded_clients'] ?? [])),
            function($v) { return $v !== ''; }
        )),
        'offers' => [],
    ];

    foreach (($config['offers'] ?? []) as $offer) {
        if (empty(trim($offer['name'] ?? ''))) continue;
        $save['offers'][] = [
            'name'        => trim($offer['name'] ?? ''),
            'dl'          => trim($offer['dl'] ?? ''),
            'ul'          => trim($offer['ul'] ?? ''),
            'price'       => trim($offer['price'] ?? ''),
            'description' => trim($offer['description'] ?? ''),
        ];
    }

    if (!is_dir(IBOK_CFG_DIR)) {
        @mkdir(IBOK_CFG_DIR, 0750, true);
    }

    return file_put_contents(
        IBOK_TARIFF_OFFERS_FILE,
        json_encode($save, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE),
        LOCK_EX
    ) !== false;
}

/**
 * Sprawdź czy oferta taryf jest dostępna dla danego klienta
 */
function tariff_offers_enabled($client_id) {
    $config = tariff_offers_load();

    if (!$config['enabled']) {
        return false;
    }

    if (empty($config['offers'])) {
        return false;
    }

    $excluded = array_map('strval', $config['excluded_clients']);
    if (in_array((string)$client_id, $excluded, true)) {
        return false;
    }

    return true;
}
