<?php
/*
 *  WordPress Contact Form 7 Creamailer extension
 *  Copyright (C) 2026 Creamailer

 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.

 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.

 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */
namespace Gurumedia\CF7CMStandalone\Views;

use \Gurumedia\CF7CMStandalone\Views\IndexBase as Base;
use \Gurumedia\CF7CMStandalone\Utility\UtilityBase as Utility;

class Index extends Base {
    public static function form($api_data, $options, $plugin_options) {
        $prefix = $options['input'];
        $api_inputs = [
            [
                'label'     => __('Access Token', 'cf7cm'),
                'name'      => 'key',
                'value'     => $api_data['key'],
                'help'      => __('Your access token (asiakastunnus)', 'cf7cm'),
                'required'  => true,
                'condition' => !empty($api_data['key']),
                'prefix'    => $prefix,
            ],
            [
                'label'     => __('Shared Secred', 'cf7cm'),
                'name'      => 'shared_key',
                'value'     => $api_data['shared_key'],
                'help'      => __('Your shared secred (yhteinen tunniste)', 'cf7cm'),
                'required'  => true,
                'type'      => 'password',
                'condition' => !empty($api_data['shared_key']),
                'prefix'    => $prefix,
            ],
        ];

        $api_list_select_options = [
            '&nbsp;' => '',
        ];

        foreach ((array)$api_data['lists'] as $list) {
            $api_list_select_options[$list->name] = $list->id;
        }

        $api_list_select = [
            'label'             => __('List', 'cf7cm'),
            'name'              => 'list_id',
            'required'          => true,
            'condition'         => !empty($api_data['list_id']),
            'select_options'    => $api_list_select_options,
            'selected'          => $api_data['list_id'],
            'help'              => __('Select list for subscribers', 'cf7cm'),
            'prefix'            => $prefix,
        ];

        $select_options = [
            '&nbsp;' => '',
        ];

        foreach (Utility::getCF7TagNames() as $tag) {
            $v = $tag;
            $select_options["[$v]"] = $v;
        }

        $selects = [
            [
                'label'             => __('Email', 'cf7cm'),
                'name'              => 'email',
                'required'          => true,
                'condition'         => !empty($api_data['email']),
                'select_options'    => $select_options,
                'selected'          => $api_data['email'],
                'help'              => implode(" ", [__('Email', 'cf7cm'), __('tag', 'cf7cm')]),
                'prefix'            => $prefix,
            ],
            [
                'label'             => __('Opt-in', 'cf7cm'),
                'name'              => 'opt-in',
                'required'          => true,
                'condition'         => !empty($api_data['opt-in']),
                'select_options'    => $select_options,
                'selected'          => $api_data['opt-in'],
                'help'              => implode(" ", [__('Opt-in', 'cf7cm'), __('tag', 'cf7cm')]),
                'prefix'            => $prefix,
            ],
        ];


        $optional_selects = [
            ['name', __('Name', 'cf7cm')],
            ['company', __('Company', 'cf7cm')],
            ['address', __('Address', 'cf7cm')],
            ['city', __('City', 'cf7cm')],
            ['zip_code', __('Zip code', 'cf7cm')],
            ['country', __('Country', 'cf7cm')],
            ['phone', __('Phone', 'cf7cm')],
            ['customer_number', __('Customer number', 'cf7cm')],
        ];

        foreach ($optional_selects as $item) {
            list($name, $title) = $item;
            $selects[] = [
                'label'             => $title,
                'name'              => $name,
                'select_options'    => $select_options,
                'selected'          => $api_data[$name],
                'help'              => implode(" ", [$title, __("tag", 'cf7cm')]),
                'prefix'            => $prefix,
            ];
        }

        $status = $api_data['status'];
        $success = isset($status['success']) && $status['success'];
        $status_text = $success
            ? __('Connected', 'cf7cm')
            : __('No connection', 'cf7cm');
        $status_class = $success
            ? 'info'
            : 'danger';
        $is_hidden = !$success
            ? 'is-hidden'
            : '';

        $data_title = __("Data", "cf7cm");
        $data_text = __("Available tags", "cf7cm");
        $data_html = "
            <h3>$data_title</h3>
            <p>$data_text</p>";
        $plugin_title = __("Plugin options", "cf7cm");
        $plugin_html = "<h3>$plugin_title</h3>";

        $send_autoresponders = [
            [
                'label' => __('Send list automatic messages', 'cf7cm'),
                'name' => 'send_autoresponders',
                'type' => 'checkbox',
                'value' => 1,
                'prefix' => $prefix,
                'classes' => ['label-after-control'],
                'attributes' => array_merge(
                    ['data-send-autoresponders' => (int)(bool)$api_data['send_autoresponders']],
                    array_filter([
                        'checked' => (bool)$api_data['send_autoresponders']
                    ])
                )
            ],
            [
                'label' => __('Send list automatic messages also if subscriber exists', 'cf7cm'),
                'name' => 'send_autoresponders_if_exists',
                'type' => 'checkbox',
                'prefix' => $prefix,
                'value' => 1,
                'classes' => array_keys(array_filter([
                    'disabled' => !(bool)$api_data['send_autoresponders'],
                    'label-after-control' => true
                ])),
                'attributes' => array_merge(
                    [
                        'data-send-autoresponders-if-exists' => (int)(bool)$api_data['send_autoresponders_if_exists'],
                    ],
                    array_filter([
                        'checked' => (bool)$api_data['send_autoresponders_if_exists'],
                        'disabled' => empty($api_data['send_autoresponders'])
                    ])
                )
            ],
        ];

        $api_settings = implode('', array_map('self::inputField', $send_autoresponders));

        $plugin_settings = implode("", array_map('self::inputField', [[
            "label" => __("Enable logging", "cf7cm"),
            "name" => "logging",
            "type" => "checkbox",
            "prefix" => $prefix,
            "value" => 1,
            "classes" => ["label-after-control"],
            "attributes" => array_filter(["checked" => (bool)$plugin_options["logging"]])
        ]]));
        ?>
        <div class="form">
            <fieldset>
                <div class='level'>
                    <div class='level-left'>
                        <div class='level-item'>
                            <h3><?php _e("API settings", "cf7cm"); ?></h3>
                        </div>
                    </div>
                    <div class='level-right'>
                        <div class='level-item'>
                            <small class="tag <?php echo 'is-'.$status_class; ?>">
                                <?php echo $status_text; ?>
                            </small>
                        </div>
                    </div>
                </div>
                <?php foreach ($api_inputs as $input) : ?>
                    <?php echo Index::inputField($input); ?>
                <?php endforeach; ?>
                <div class="<?php echo $is_hidden; ?>">
                    <?php echo Index::selectField($api_list_select); ?>
                </div>
            </fieldset>

            <hr class="<?php echo $is_hidden; ?>">

            <fieldset class="<?php echo $is_hidden; ?>">
                <?php echo $api_settings; ?>
                <?php echo $data_html; ?>
                <div class="tags">
                    <?php foreach (Utility::getCF7TagNames() as $tag) : ?>
                        <span class="tag is-black">
                            <tt>[<?php echo $tag; ?>]</tt>
                        </span>
                    <?php endforeach; ?>
                </div>

                <div class='level-grid'>
                <?php foreach ($selects as $select) : ?>
                    <div class='level-grid-item'>
                    <?php echo Index::selectField($select); ?>
                    </div>
                <?php endforeach; ?>
                </div>
            </fieldset>

            <hr>

            <fieldset>
                <?php echo $plugin_html; ?>
                <?php echo $plugin_settings; ?>
            </fieldset>
        </div>
        <?php
    }

    public static function log($api_options, $plugin_options) {
        list($a, $b, $c) = array_map(function ($x) use ($api_options) {
            return $api_options[$x];
        }, ["key", "shared_key", "list_id"]);
        $enabled = (bool)$plugin_options["logging"];
        $result_file = Utility::getLog($a, $b, $c);
        $lines = $result_file->is_ok
            ? array_reverse(array_filter(explode("\n", $result_file->value)))
            : [];
        $items = implode("", array_map(function ($line) {
            return "<li class='item'><code>$line</code></li>";
        }, $lines));
        ?>
        <details>
            <summary>
                <?php echo __("Log", "cf7cm"); ?>
            </summary>
            <div class="log">
                <ul class="items">
                    <?php echo $items ?>
                </ul>
            </div>
        </details>
        <?php
    }

    public static function render($api_data, $options, $plugin_options) {
        $help_title = __("Need help?", "cf7cm");
        $help_text = __("See the official help article", "cf7cm");
        $help_href = "https://tuki.creamailer.fi/hc/fi/articles/360022745512";
        $help = "
            <h3>$help_title</h3>
            <p><a href='$help_href' target='_blank'>$help_text</a></p>
            ";
        ?>
        <div id="cf7-creamailer-extension">
            <div class='level extension-header'>
                <div class='level-left'>
                    <div class='level-item'>
                        <img src="<?php echo \CF7CMSTANDALONE_CF7CM_URL . 'assets/images/logo.png'; ?>" />
                    </div>
                </div>
                <div class='level-right'>
                    <div class='level-item'>
                        <sup>Version <?php echo \CF7CMSTANDALONE_CF7CM_VERSION; ?></sup>
                    </div>
                </div>
            </div>
            <hr>
            <?php echo Index::form($api_data, $options, $plugin_options); ?>
            <?php echo Index::log($api_data, $plugin_options); ?>
            <hr>
            <?php echo $help; ?>
        </div>
        <?php
    }
}
