{% extends request.ajax ? 'layout_blank.html.twig' : 'layout_default.html.twig' %}

{% import 'macro_functions.html.twig' as mf %}

{% set active_menu = 'system' %}
{% set params = admin.extension_config_get({ 'ext': 'mod_currency' }) %}

{% block meta_title %}{{ 'Currency settings'|trans }}{% endblock %}

{% block breadcrumbs %}
    <ol class="breadcrumb">
        <li class="breadcrumb-item">
            <a href="{{ '/'|alink }}">
                <svg class="icon">
                    <use xlink:href="#home" />
                </svg>
            </a>
        </li>
        <li class="breadcrumb-item">
            <a href="{{ 'system'|alink }}">{{ 'Settings'|trans }}</a>
        </li>
        <li class="breadcrumb-item active" aria-current="page">{{ 'Currency settings'|trans }}</li>
    </ol>
{% endblock %}

{% block content %}
    <div class="card-tabs">
        <ul class="nav nav-tabs" role="tablist">
            <li class="nav-item" role="presentation">
                <a class="nav-link active" href="#tab-currencies" data-bs-toggle="tab" role="tab">{{ 'Currencies'|trans }}</a>
            </li>
            <li class="nav-item" role="presentation">
                <a class="nav-link" href="#tab-new-currency" data-bs-toggle="tab" role="tab">
                    <svg class="icon me-2">
                        <use xlink:href="#plus" />
                    </svg>
                    {{ 'Add new currency'|trans }}
                </a>
            </li>
            <li class="nav-item" role="presentation">
                <a class="nav-link" href="#tab-api-settings" data-bs-toggle="tab" role="tab">{{ 'Integrations / Automation'|trans }}</a>
            </li>
            <li class="nav-item" role="presentation">
                <a class="nav-link" href="#tab-converter" data-bs-toggle="tab" role="tab">{{ 'Converter'|trans }}</a>
            </li>
        </ul>
        <div class="card">
            <div class="tab-content">
                <div class="tab-pane fade show active" id="tab-currencies" role="tabpanel">
                    <div class="card-body border-bottom">
                        <h3 class="card-title">{{ 'Manage currencies'|trans }}</h3>
                        <p class="card-subtitle">{{ 'The default currency is the one you define product pricing in. If your client chooses a different currency, pricing will be recalculated according to the conversion rate. Changing the default currency after orders have been placed may have unexpected issues. Nothing is recalculated on default currency change. Your income is calculated in the default currency. Changing the default currency after you have paid invoices will distort income statistics.'|trans }}</p>
                    </div>
                    {% if params.sync_rate != 'never' %}
                        <div class="alert alert-success" role="alert">
                            {{ 'FOSSBilling is configured to automatically sync currency exchange rates.'|trans }}
                        </div>
                    {% else %}
                        <div class="alert alert-warning" role="alert">
                            {{ 'FOSSBilling is not configured to automatically sync currency exchange rates.'|trans }}
                        </div>
                    {% endif %}
                    <div class="table-responsive">
                        <table class="table card-table table-vcenter table-striped text-nowrap">
                            <thead>
                            <tr>
                                <th>{{ 'ISO code'|trans }}</th>
                                <th>{{ 'Title'|trans }}</th>
                                <th>{{ 'Conversion rate'|trans }}</th>
                                <th>{{ 'Example price'|trans }}</th>
                                <th class="w-1"></th>
                            </tr>
                            </thead>
                            <tbody>
                            {% for currency in admin.currency_get_list.list %}
                                <tr>
                                    <td>{% if currency.default %}<strong>{{ currency.code }}</strong>{% else %}{{ currency.code }}{% endif %}</td>
                                    <td>
                                        <a href="{{ '/currency/manage'|alink }}/{{ currency.code }}">{{ currency.title }}</a>
                                    </td>
                                    <td>{{ currency.conversion_rate }}</td>
                                    <td>{{ mf.currency_format(1) }} = {{ mf.currency(1, currency.code) }}</td>
                                    <td>
                                        <a class="btn btn-icon" href="{{ '/currency/manage'|alink }}/{{ currency.code }}"
                                           data-bs-toggle="tooltip" data-bs-title="{{ 'Edit'|trans }}">
                                            <svg class="icon">
                                                <use xlink:href="#edit" />
                                            </svg>
                                        </a>
                                        <a class="btn btn-icon api-link"
                                           href="{{ 'api/admin/currency/delete'|link({ 'code': currency.code, 'CSRFToken': CSRFToken }) }}"
                                           data-api-redirect="{{ 'extension/settings/currency'|alink }}"
                                           data-api-type="danger"
                                           data-api-confirm="{{ 'Are you sure you want to delete?'|trans }}"
                                           data-api-confirm-btn="{{ 'Delete'|trans }}"
                                           data-bs-toggle="tooltip" data-bs-title="{{ 'Delete'|trans }}">
                                            <svg class="icon">
                                                <use xlink:href="#delete" />
                                            </svg>
                                        </a>
                                        {% if not currency.default %}
                                            <a class="btn btn-icon api-link"
                                               data-api-redirect="{{ 'extension/settings/currency'|alink }}"
                                               href="{{'api/admin/currency/set_default'|link({ 'code': currency.code, 'CSRFToken': CSRFToken }) }}"
                                               data-bs-toggle="tooltip" data-bs-title="{{ 'Set as default'|trans }}">
                                                <svg class="icon">
                                                    <use xlink:href="#check" />
                                                </svg>
                                            </a>
                                        {% endif %}
                                    </td>
                                </tr>
                            {% else %}
                                <tr>
                                    <td colspan="5" class="text-muted">{{ 'The list is empty'|trans }}</td>
                                </tr>
                            {% endfor %}
                            </tbody>
                        </table>
                    </div>

                    <div class="card-footer text-center">
                        <a class="btn btn-primary api-link" href="{{ 'api/admin/currency/update_rates'|link({ 'CSRFToken': CSRFToken }) }}" data-api-redirect="{{ 'extension/settings/currency'|alink }}">
                            <svg class="icon icon-tabler" width="24" height="24">
                                <use xlink:href="#refresh" />
                            </svg>
                            <span>{{ 'Update Rates'|trans }}</span>
                        </a>
                        {% if params.provider|default('exchangerate-api') == "exchangerate-api" and not params.exchangerate_api_key %}
                            <a href="https://www.exchangerate-api.com" target="_blank"><p class="mt-1 mb-0">{{ 'Currency exchange rates By ExchangeRate-API.'|trans }}</p></a>
                        {% endif %}
                    </div>
                </div>

                <div class="tab-pane fade" id="tab-new-currency" role="tabpanel">
                    <form method="post" action="{{ 'api/admin/currency/create'|link }}" class="api-form" data-api-redirect="{{ 'extension/settings/currency'|alink }}">
                        <input type="hidden" name="CSRFToken" value="{{ CSRFToken }}">
                        <div class="card-body">
                            <div class="form-group mb-3 row">
                                <label class="col-md-3 col-form-label">{{ 'Code'|trans }}</label>
                                <div class="col-md-6">
                                    {{ mf.selectbox('code', admin.currency_get_pairs, 'USD', 1) }}
                                </div>
                            </div>
                            <div class="form-group mb-3 row">
                                <label class="col-md-3 col-form-label">{{ 'Title'|trans }}</label>
                                <div class="col-md-6">
                                    <input class="form-control" type="text" name="title" value="" required>
                                </div>
                            </div>
                            <div class="form-group mb-3 row">
                                <label class="col-md-3 col-form-label">{{ 'Conversion rate'|trans }}</label>
                                <div class="col-md-6">
                                    <input class="form-control" type="text" name="conversion_rate" value="1" required>
                                </div>
                            </div>
                            <div class="form-group mb-3 row">
                                <label class="col-md-3 col-form-label">{{ 'Format'|trans }}</label>
                                <div class="col-md-6">
                                    <input class="form-control" type="text" name="format" value="$ {{ '{{price}}' }}" required>
                                </div>
                            </div>
                        </div>
                        <div class="card-footer text-end">
                            <button class="btn btn-primary" type="submit">{{ 'Add'|trans }}</button>
                        </div>
                    </form>
                </div>

                <div class="tab-pane fade" id="tab-api-settings" role="tabpanel">
                    <form method="post" action="{{ 'api/admin/extension/config_save'|link }}" class="api-form" data-api-msg="{{ 'Successfully updated settings'|trans }}">
                        <input type="hidden" name="CSRFToken" value="{{ CSRFToken }}">
                        <input type="hidden" name="ext" value="mod_currency">
                        <div class="card-body">
                            <h3 class="card-title">{{ 'Available exchange rate data providers'|trans }}</h3>
                            <p>{{ 'FOSSBilling provides integration with various currency exchange rate data providers, allowing you to choose whichever one best suits your needs. By default, FOSSBilling will use the ExchangeRate-API "Open Access Endpoint" which does not require any configuration.'|trans }}</p>
                            <table class="table">
                                <thead>
                                    <tr>
                                        <th>{{ 'Provider'|trans }}</th>
                                        <th>{{ 'Authentication Required'|trans }}</th>
                                        <th>{{ 'Update Frequency'|trans }}</th>
                                        <th>{{ 'Supported Currencies'|trans }}</th>
                                        <th>{{ 'Pricing'|trans }}</th>
                                    </tr>
                                  </thead>
                                  <tbody>
                                    <tr>
                                      <th><a href="https://www.exchangerate-api.com/docs/free" target="_blank">{{ 'ExchangeRate-API (Open Access Endpoint)'|trans }}</a></th>
                                      <th>✖️</th>
                                      <th>{{ '1D'|trans }}</th>
                                      <th><a href="https://www.exchangerate-api.com/docs/supported-currencies" target="_blank">{{ 'Supported currencies'|trans }}</a></th>
                                      <th>{{ 'Free'|trans }}</th>
                                    </tr>
                                    <tr>
                                      <th><a href="https://www.exchangerate-api.com/#pricing" target="_blank">ExchangeRate-API</a></th>
                                      <th>☑️</th>
                                      <th>{{ '1D / 1H / 5M'|trans }}</th>
                                      <th><a href="https://www.exchangerate-api.com/docs/supported-currencies" target="_blank">{{ 'Supported currencies'|trans }}</a></th>
                                      <th>{{ 'Free / paid'|trans }}</th>
                                    </tr>
                                    <tr>
                                        <th><a href="https://apilayer.com/marketplace/currency_data-api" target="_blank">Currency Data API</a></th>
                                        <th>☑️</th>
                                        <th>{{ '1D / 1H / 10M / 1M'|trans }}</th>
                                        <th><a href="https://currencylayer.com/currencies" target="_blank">{{ 'Supported currencies'|trans }}</a></th>
                                        <th>{{ 'Free / paid'|trans }}</th>
                                    </tr>
                                    <tr>
                                        <th><a href="https://currencylayer.com/" target="_blank">currencylayer</a></th>
                                        <th>☑️</th>
                                        <th>{{ '1D / 1H / 10M / 1M'|trans }}</th>
                                        <th><a href="https://currencylayer.com/currencies" target="_blank">{{ 'Supported currencies'|trans }}</a></th>
                                        <th>{{ 'Free / paid'|trans }}</th>
                                    </tr>
                                  </tbody>                                    
                            </table>
                            <span class="text-muted">{{ 'When using ExchangeRate-API, their API informs FOSSBilling when the next update will occur which makes it more efficient for automated exchange rate syncing.'|trans }}</span>
                            <br/>
                            <span class="text-muted">{{ 'To the best of our knowledge, "Currency Data API" and "currencylayer" are both owned by APILayer and provide the same data, but through a different API.'|trans }}</span>
                            <div class="form-group mb-3 mt-3 row">
                                <label class="col-md-3 col-form-label">{{ 'Currency exchange rate data provider'|trans }}</label>
                                <div class="col-md-6">
                                    <select class="form-select" aria-label="Currency data provider selection" name="provider" id="provider_select">
                                        <option value="exchangerate-api" selected>ExchangeRate-API</option>
                                        <option value="currency_data_api">Currency Data API</option>
                                        <option value="currencylayer">currencylayer</option>
                                    </select>
                                </div>
                            </div>
                            <div class="form-group mb-3 row">
                                <label class="col-md-3 col-form-label">{{ 'API key'|trans }}</label>
                                <div class="col-md-6">
                                    <input class="form-control" type="text" name="exchangerate_api_key" id="exchangerate_api" value="{{ params.exchangerate_api_key }}" hidden="true">
                                    <input class="form-control" type="text" name="currencydata_key" id="currencydata" value="{{ params.currencydata_key }}" hidden="true">
                                    <input class="form-control" type="text" name="currencylayer_key" id="currencylayer" value="{{ params.currencylayer_key }}"  hidden="true">
                                    <span class="text-muted" id="exchangerate_api_help_text" hidden="true">{{ 'Leave this blank to use the ExchangeRate-API "Open Access Endpoint".'|trans }}</span>
                                </div>
                            </div>
                            <div class="form-group mb-3 row">
                                <label class="col-md-3 col-form-label">{{ 'Automatic sync rate'|trans }}</label>
                                <div class="col-md-6">
                                    <select class="form-select" aria-label="Currency data provider selection" name="sync_rate" id="sync_rate">
                                        <option value="auto" id="auto-sync" selected>{{ 'Auto'|trans }}</option>
                                        <option value="never">{{ 'Never'|trans }}</option>
                                        <option value="1d">{{ 'Daily'|trans }}</option>
                                        <option value="1h">{{ 'Hourly'|trans }}</option>
                                        <option value="10m">{{ 'Every 10 minutes'|trans }}</option>
                                        <option value="5m">{{ 'Every 5 minutes'|trans }}</option>
                                        <option value="1m" id="1m-sync">{{ 'Every minute'|trans }}</option>
                                    </select>
                                <p class="text-muted">{{ '"Auto" is only available for ExchangeRate-API and when used will cause API requests to be made only when new data is made available, preventing excess requests.'|trans }}</p>
                                <p class="text-muted">{{ 'Exchange rate syncing runs via the cronjob and as such is limited by the frequency of your cron schedule (typically 5 minutes).'|trans }}</p>
                                </div>
                            </div>
                        </div>
                        <div class="card-footer text-end">
                            <button class="btn btn-primary" type="submit">{{ 'Update'|trans }}</button>
                        </div>
                    </form>
                </div>

                <div class="tab-pane fade" id="tab-converter" role="tabpanel">
                    <form method="post" action="">
                        <input type="hidden" name="CSRFToken" value="{{ CSRFToken }}"/>
                        <div class="card-body">
                            <div class="input-group">
                                <span class="input-group-text">{{ guest.currency_get.code }}</span>
                                <input class="form-control" type="text" name="amount" value="" required placeholder="{{ 'Amount'|trans }}" onkeyup="doConvert();">
                                <span class="input-group-text">=</span>
                                <input class="form-control" type="text" id="converted_result" value="" placeholder="{{ 'Result'|trans }}" readonly>
                                <div>{{ mf.selectbox('to', guest.currency_get_pairs) }}</div>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
{% endblock %}

{% block js %}
<script>
    function doConvert() {
        var price = $('input[name="amount"]').val();
        var code = $('select[name="to"]').val();

        bb.post('guest/currency/format', { price: price, code: code, CSRFToken: "{{ CSRFToken }}" }, function(result) {
            $('#converted_result').val(result);
        });

        return false;
    };

    function switchKeyBox(value){
        if(value === 'currencylayer'){
            document.getElementById("currencydata").hidden = true;
            document.getElementById("currencylayer").hidden = false;
            document.getElementById("exchangerate_api").hidden = true;
            document.getElementById("exchangerate_api_help_text").hidden = true;
            document.getElementById("auto-sync").disabled = true;
            document.getElementById("1m-sync").disabled = false;
        } else if(value === 'currency_data_api'){
            document.getElementById("currencydata").hidden = false;
            document.getElementById("currencylayer").hidden = true;
            document.getElementById("exchangerate_api").hidden = true;
            document.getElementById("exchangerate_api_help_text").hidden = true;
            document.getElementById("auto-sync").disabled = true;
            document.getElementById("1m-sync").disabled = false;
        } else {
            document.getElementById("currencydata").hidden = true;
            document.getElementById("currencylayer").hidden = true;
            document.getElementById("exchangerate_api").hidden = false;
            document.getElementById("exchangerate_api_help_text").hidden = false;
            document.getElementById("auto-sync").disabled = false;
            document.getElementById("1m-sync").disabled = true;
        }

        if(value === 'exchangerate-api'){
            if(document.getElementById("sync_rate").value === '1m'){
                document.getElementById("sync_rate").value = 'auto';
            }
        } else {
            if(document.getElementById("sync_rate").value === 'auto'){
                document.getElementById("sync_rate").value = '1d';
            }
        }
    }

    document.getElementById("provider_select").onchange = function() {
        switchKeyBox(this.value);
    };
    document.addEventListener("DOMContentLoaded", (event) => {
        document.getElementById("sync_rate").value = "{{ params.sync_rate }}";
        document.getElementById("provider_select").value = "{{ params.provider }}";
        switchKeyBox("{{ params.provider }}");
    });

</script>
{% endblock %}
