<?php

namespace Clonable\Views;

use Clonable\Helpers\Html;
use Clonable\Traits\Forms;
use Clonable\models\EmailTranslations;
use Clonable\Objects\ClonableConfig;
use Clonable\Traits\PluginCheck;

class EmailTranslationsView implements ViewInterface
{
    use Forms;
    use PluginCheck;

    public function render(): void
    {
        wp_enqueue_media(); // make sure media library scripts are loaded
        Html::include_js("email-translations.js");
        Html::include_alpine();
        Html::flags();

        $this->render_fields(EmailTranslations::PAGE, EmailTranslations::$fields, 'Email Translations Settings');
        $this->render_form(EmailTranslations::PAGE);
    }

    public function description(): void
    {
        echo '<p style="max-width: 75%">Configure the email translation settings used by Clonable.</p>';
        /* if clonable advanced is installed, generate warning if the email translations are enabled */
        if ($this->clonable_advanced_installed() && $this->emailTranslationsEnabled()) {
            echo '<p class="warning" style="max-width: 75%; color: red; padding:10px; display:inline-block; border:1px solid red; margin:0;"><strong>Warning</strong> - Woocommerce email translations are enabled, but the Clonable Advanced module also seems to be used.<br>Be aware of potential conflicts regarding Woocommerce Email translations.</p>';
        }
    }

    public function emailTranslationsEnabled()
    {
        return get_option('clonable_email_translations_enabled', 'off') === 'on';
    }

    public function clonable_email_translations_enabled_field()
    {
        $this->create_checkbox('clonable_email_translations_enabled', 'off');
    }

    public function clonable_woocommerce_enable_pdf_invoice_translation_field()
    {
        $this->create_checkbox('clonable_woocommerce_enable_pdf_invoice_translation', 'off');
    }

    public function clonable_email_translations_excluded_addresses_field()
    {
        $option = get_option('clonable_email_translations_excluded_addresses', '');
        echo "<input style='min-width: 450px' placeholder='excluded1@email.ext, excluded2@email.ext' name='clonable_email_translations_excluded_addresses' type='text' value='$option'/>";
        $this->render_error("clonable_email_translations_excluded_addresses");
    }

    public function clonable_email_headers_by_domain_field()
    {
        // Get all clone domains from the "Allowed Origins" option (best effort).
        $site = ClonableConfig::get_site();
        $clones = $site ? $site->get_clones() : [];

        $domains = [];
        foreach ($clones as $clone) {
            $origin = trim((string) ($clone['domain']));
            $subfolder = trim((string) ($clone['subfolder_clone']));

            $key = $origin;
            if ($subfolder !== '') {
                $key .= '/' . trim($subfolder, '/');
            }
            $domains[$key] = $clone['id'];
        }

        // Load saved per-domain email settings (JSON).
        $saved_json = (string) \get_option('clonable_email_headers_by_domain', '[]');
        $saved_rows = json_decode($saved_json, true);

        if (!is_array($saved_rows)) {
            $saved_rows = [];
        }

        // Index saved rows by normalized domain for easy merge.
        $saved_by_domain = [];
        foreach ($saved_rows as $row) {
            if (!is_array($row) || empty($row['domain'])) {
                continue;
            }
            $saved_domain = trim((string) $row['domain']);
            $saved_by_domain[$saved_domain] = $row;
        }

        // Build rows for ALL available clone domains (clone_id always from current clone list).
        $rows = [];
        foreach ($domains as $domain => $clone_id) {
            $existing = $saved_by_domain[$domain] ?? [];
            $rows[] = [
                'clone_id'     => $clone_id, // always pre-filled from $clone['id']
                'domain'       => $domain,
                'from_address' => (string) ($existing['from_address'] ?? ''),
                'reply_to'     => (string) ($existing['reply_to'] ?? ''),
                'sender_name'  => (string) ($existing['sender_name'] ?? ''),
                'email_logo'   => (string) ($existing['email_logo'] ?? ''),
            ];
        }

        $output = esc_js(wp_json_encode($rows));

?>
        <p style="max-width: 75%">
            Configure the email "From address", "Reply-To" and "Sender name" and email logo per clone domain.
            Domains are fixed and based on the Allowed Origins list.
        </p>

        <div class="wrap">
            <div x-data="{ rows: <?php echo $output; ?> }">
                <!-- hidden input field for submitting the json value -->
                <label for="clonable_email_headers_by_domain"></label>
                <input
                    x-model="JSON.stringify(rows)"
                    name="clonable_email_headers_by_domain"
                    id="clonable_email_headers_by_domain"
                    style="display: none" />

                <table class="wp-list-table fat striped" style="width: 100%">
                    <thead>
                        <tr>
                            <th style="width: 16.6%">Clone ID</th>
                            <th style="width: 16.6%">Clone Domain</th>
                            <th style="width: 16.6%">From address</th>
                            <th style="width: 16.6%">Reply-To address</th>
                            <th style="width: 16.6%">Sender name</th>
                            <th style="width: 16.6%">Email logo</th>
                        </tr>
                    </thead>
                    <tbody>
                        <template x-for="(row, index) in rows" :key="index">
                            <tr>
                                <td>
                                    <input x-model="rows[index].clone_id" disabled readonly style="width: 100%" />
                                </td>
                                <td>
                                    <input x-model="rows[index].domain" disabled readonly style="width: 100%" />
                                </td>
                                <td>
                                    <input
                                        x-model="rows[index].from_address"
                                        type="email"
                                        placeholder="shop@example.com"
                                        style="width: 100%" />
                                </td>
                                <td>
                                    <input
                                        x-model="rows[index].reply_to"
                                        type="email"
                                        placeholder="support@example.com"
                                        style="width: 100%" />
                                </td>
                                <td>
                                    <input
                                        x-model="rows[index].sender_name"
                                        type="text"
                                        placeholder="Sender name"
                                        style="width: 100%" />
                                </td>
                                <td>
                                    <input
                                        x-model="rows[index].email_logo"
                                        type="hidden"
                                        class="email-logo-input"
                                        placeholder="https://example.com/logo.png"
                                        style="width:100%" />
                                    <div class="logo-preview-box" :data-clone-id="rows[index].clone_id" style="position: relative;">

                                        <template x-if="rows[index].email_logo">
                                            <!-- remove logo icon -->
                                            <i class="remove-logo dashicons dashicons-no-alt" :index="index"
                                                style="cursor: pointer; position: absolute; top: 5px; left: 5px; color: red;"
                                                @click="rows[index].email_logo = '';"></i>
                                        </template>

                                        <template x-if="rows[index].email_logo">
                                            <img
                                                :src="rows[index].email_logo"
                                                alt="Email logo"
                                                style="max-width: 150px; max-height: 80px; border: 1px solid #eee; padding: 5px;" />
                                        </template>

                                        <template x-if="!rows[index].email_logo">
                                            <div class="no-logo" :data-clone-id="rows[index].clone_id">
                                                <!-- set logo button / media library picker -->
                                                <button :index="index" class="button button-secondary open-media"
                                                    type="button">
                                                    Select logo
                                                </button>
                                            </div>
                                        </template>

                                    </div><!-- .logo-preview-box -->
                                </td>
                            </tr>
                        </template>
                    </tbody>
                </table>
            </div>
        </div>
    <?php

        $this->render_error('clonable_email_headers_by_domain');
    }


    public function clonable_wpo_replacements_by_domain_field()
    {
        // Get all clone domains from the "Allowed Origins" option (best effort).
        $site = ClonableConfig::get_site();
        $clones = $site ? $site->get_clones() : [];

        // Load saved per-domain email settings (JSON).
        $saved_json = (string) get_option('clonable_wpo_replacements_by_domain', '[]');
        $saved_rows = json_decode($saved_json, true);

        if (!is_array($saved_rows)) {
            $saved_rows = [];
        }

        // Index saved rows by normalized domain for easy merge.
        $saved_by_domain = [];
        foreach ($saved_rows as $row) {
            if (!is_array($row) || empty($row['domain'])) {
                continue;
            }
            $saved_domain = $row['domain'];
            $saved_by_domain[$saved_domain] = $row;
        }

        // Build rows for ALL available clone domains (clone_id always from current clone list).
        $rows = [];
        foreach ($clones as $clone) {
            $save_key = $clone['domain'] . $clone['subfolder_clone'];
            $existing = $saved_by_domain[$save_key] ?? [];
            $rows[] = [
                'clone_id'     => $clone['id'], // always pre-filled from $clone['id']
                'domain'       => $clone['domain'] . $clone['subfolder_clone'],
                'locale'       => $clone['lang_code'],
                'shop_phone_number' => (string) ($existing['shop_phone_number'] ?? ''),
                'shop_email_address'     => (string) ($existing['shop_email_address'] ?? ''),
                'shop_name'  => (string) ($existing['shop_name'] ?? ''),
                'vat_number'   => (string) ($existing['vat_number'] ?? ''),
                'coc_number'   => (string) ($existing['coc_number'] ?? ''),
                'shop_address_line_1'   => (string) ($existing['shop_address_line_1'] ?? ''),
                'shop_address_line_2'   => (string) ($existing['shop_address_line_2'] ?? ''),
                'shop_address_country'   => (string) ($existing['shop_address_country'] ?? ''),
                'shop_address_state'   => (string) ($existing['shop_address_state'] ?? ''),
                'shop_address_city'   => (string) ($existing['shop_address_city'] ?? ''),
                'shop_address_postcode'   => (string) ($existing['shop_address_postcode'] ?? ''),
                'shop_address_additional'   => (string) ($existing['shop_address_additional'] ?? ''),
            ];
        }

        $output = esc_js(wp_json_encode($rows));

    ?>
        <p style="max-width: 75%">
            Configure order PDF fields for specific clone domains.
            Domains are fixed and based on the Allowed Origins list.
            <br />
            Leave the fields empty to use the same PDF fields for the
            translated version, as the default version.
        </p>

        <style>
            .wide-table-wrapper table,
            .wide-table-wrapper thead,
            .wide-table-wrapper tbody,
            .wide-table-wrapper th,
            .wide-table-wrapper td,
            .wide-table-wrapper tr {
                display: block;
            }

            .wide-table-wrapper thead {
                display: none;
            }

            .wide-table-wrapper tr {
                margin-bottom: 1rem;
                border: 1px solid #ddd;
                padding: 0.5rem;
                background: #fff;
            }

            .wide-table-wrapper td {
                position: relative;
                padding-left: 50%;
                border: none;
            }

            .wide-table-wrapper td::before {
                position: absolute;
                top: 0;
                left: 0;
                width: 45%;
                padding-left: 0.5rem;
                white-space: nowrap;
                font-weight: bold;
                content: attr(data-label);
            }


            .wide-table-wrapper tbody {
                display: flex !important;
                gap: 2%;
            }

            .wide-table-wrapper table {
                width: 100%;
            }

            .wide-table-wrapper table,
            .wide-table-wrapper thead,
            .wide-table-wrapper tbody,
            .wide-table-wrapper th,
            .wide-table-wrapper td,
            .wide-table-wrapper tr {
                display: block;
            }

            .wide-table-wrapper thead {
                display: none;
            }

            .wide-table-wrapper tr {
                width: 18%;
                margin-bottom: 1rem;
                border: 1px solid #ddd;
                padding: 0.5rem;
            }

            .wide-table-wrapper td {
                display: flex;
                justify-content: space-between;
                padding: 0.25rem 0;
            }

            .wide-table-wrapper td::before {
                content: attr(data-label);
                font-weight: bold;
            }

            @media (max-width: 991px) {
                .wide-table-wrapper tbody {
                    flex-direction: column;
                }

                .wide-table-wrapper tr {
                    width: 75%;
                }
            }
        </style>

        <div class="wrap">
            <div class="wide-table-wrapper" x-data="{ rows: <?php echo $output; ?> }">
                <!-- hidden input field for submitting the json value -->
                <label for="clonable_wpo_replacements_by_domain"></label>
                <input
                    x-model="JSON.stringify(rows)"
                    name="clonable_wpo_replacements_by_domain"
                    id="clonable_wpo_replacements_by_domain"
                    style="display: none" />

                <table class="wp-list-table fat striped" style="width: 100%">
                    <thead>
                        <tr>
                            <th>Shop phone number</th>
                            <th>Shop email address</th>
                            <th>Shop name</th>
                            <th>VAT number</th>
                            <th>CoC number</th>
                            <th>Address line 1</th>
                            <th>Address line 2</th>
                            <th>Country</th>
                            <th>State</th>
                            <th>City</th>
                            <th>Postcode</th>
                            <th>Additional address info</th>
                        </tr>
                    </thead>
                    <tbody>
                        <template x-for="(row, index) in rows" :key="index">
                            <tr>
                                <input type="hidden" x-model="rows[index].domain" disabled readonly style="width: 100%" />
                                <input type="hidden" x-model="rows[index].clone_id" disabled readonly style="width: 100%" />
                                <td style="justify-content: start; font-size: 13px">
                                    <i class="fflag ff-sm" :class="`fflag-${rows[index].locale.split('_')[1]}`" style="margin-right: 0.5rem; margin-bottom: 0.125rem; margin-top: .3rem"></i>
                                    <span x-text="rows[index].domain"></span>
                                </td>
                                <td>
                                    <input
                                        x-model="rows[index].shop_phone_number"
                                        type="text"
                                        placeholder="Shop phone number"
                                        style="width: 100%" />
                                </td>
                                <td>
                                    <input
                                        x-model="rows[index].shop_email_address"
                                        type="email"
                                        placeholder="Shop email address"
                                        style="width: 100%" />
                                </td>
                                <td>
                                    <input
                                        x-model="rows[index].shop_name"
                                        type="text"
                                        placeholder="Shop name"
                                        style="width: 100%" />
                                </td>
                                <td>
                                    <input
                                        x-model="rows[index].vat_number"
                                        type="text"
                                        placeholder="VAT number"
                                        style="width: 100%" />
                                </td>
                                <td>
                                    <input
                                        x-model="rows[index].coc_number"
                                        type="text"
                                        placeholder="CoC number"
                                        style="width: 100%" />
                                </td>
                                <td>
                                    <input
                                        x-model="rows[index].shop_address_line_1"
                                        type="text"
                                        placeholder="Address line 1"
                                        style="width: 100%" />
                                </td>
                                <td>
                                    <input
                                        x-model="rows[index].shop_address_line_2"
                                        type="text"
                                        placeholder="Address line 2"
                                        style="width: 100%" />
                                </td>
                                <td>
                                    <input
                                        x-model="rows[index].shop_address_country"
                                        type="text"
                                        placeholder="Country"
                                        style="width: 100%" />
                                </td>
                                <td>
                                    <input
                                        x-model="rows[index].shop_address_state"
                                        type="text"
                                        placeholder="State"
                                        style="width: 100%" />
                                </td>
                                <td>
                                    <input
                                        x-model="rows[index].shop_address_city"
                                        type="text"
                                        placeholder="City"
                                        style="width: 100%" />
                                </td>
                                <td>
                                    <input
                                        x-model="rows[index].shop_address_postcode"
                                        type="text"
                                        placeholder="Postcode"
                                        style="width: 100%" />
                                </td>
                                <td>
                                    <input
                                        x-model="rows[index].shop_address_additional"
                                        type="text"
                                        placeholder="Additional address info"
                                        style="width: 100%" />
                                </td>

                            </tr>
                        </template>
                    </tbody>
                </table>
            </div>
        </div>
<?php

        $this->render_error('clonable_wpo_replacements_by_domain');
    }
}
