<?php
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

add_action( 'admin_post_elementsell_send_gmail_test_email', 'elementsell_handle_send_gmail_test_email' );

/**
 * @return string
 */
function elementsell_get_gmail_app_password() {
    $password = get_option( 'elementsell_gmail_app_password', '' );

    return preg_replace( '/\s+/', '', is_string( $password ) ? $password : '' );
}

/**
 * @return bool
 */
function elementsell_gmail_smtp_is_configured() {
    $email = sanitize_email( (string) get_option( 'elementsell_gmail_address', '' ) );

    return $email !== ''
        && is_email( $email )
        && elementsell_get_gmail_app_password() !== '';
}

/**
 * @return void
 */
function elementsell_handle_send_gmail_test_email() {
    if ( ! current_user_can( 'manage_options' ) ) {
        wp_die( esc_html__( 'Nemáte oprávnění.', 'platebni-formular' ) );
    }

    check_admin_referer( 'elementsell_send_gmail_test_email' );

    $email = isset( $_POST['elementsell_gmail_test_email'] )
        ? sanitize_email( wp_unslash( (string) $_POST['elementsell_gmail_test_email'] ) )
        : '';

    if ( $email === '' || ! is_email( $email ) ) {
        wp_safe_redirect(
            add_query_arg(
                [
                    'page'                  => 'elementsell',
                    'es_gmail_test_result'  => 'failed',
                    'es_gmail_test_error'   => rawurlencode( 'Zadejte platnou e-mailovou adresu.' ),
                ],
                admin_url( 'admin.php' )
            ) . '#elementsell-gmail-smtp'
        );
        exit;
    }

    if ( ! elementsell_gmail_smtp_is_configured() ) {
        wp_safe_redirect(
            add_query_arg(
                [
                    'page'                  => 'elementsell',
                    'es_gmail_test_result'  => 'failed',
                    'es_gmail_test_error'   => rawurlencode( 'Nejdříve uložte Gmail adresu a heslo aplikace.' ),
                ],
                admin_url( 'admin.php' )
            ) . '#elementsell-gmail-smtp'
        );
        exit;
    }

    $reply_to_hint = function_exists( 'elementsell_get_test_email_reply_to_hint' )
        ? elementsell_get_test_email_reply_to_hint()
        : '';
    $from_name = function_exists( 'elementsell_get_test_email_from_name' )
        ? elementsell_get_test_email_from_name()
        : ( function_exists( 'elementsell_get_sender_name' ) ? elementsell_get_sender_name() : get_bloginfo( 'name' ) );
    $email_content = function_exists( 'elementsell_build_test_delivery_email' )
        ? elementsell_build_test_delivery_email()
        : [
            'subject' => 'Test: doručení e-mailu (ElementSell)',
            'message' => 'Testovací e-mail.',
        ];

    $sent = elementsell_send_email(
        $email,
        $email_content['subject'],
        $email_content['message'],
        [],
        [],
        $from_name,
        $reply_to_hint
    );

    $meta      = elementsell_get_last_email_send_meta();
    $from      = (string) ( $meta['from_email'] ?? '' );
    $reply_to  = (string) ( $meta['reply_to'] ?? '' );
    $transport = (string) ( $meta['transport'] ?? '' );
    $error     = trim( (string) ( $meta['error'] ?? '' ) );
    $warning   = trim( (string) ( $meta['deliverability_warning'] ?? '' ) );

    if ( $sent && function_exists( 'elementsell_log_sent_email' ) ) {
        elementsell_log_sent_email( 0, $email, $email_content['subject'], $email_content['message'] );
    } elseif ( ! $sent && function_exists( 'elementsell_log_failed_email' ) ) {
        if ( $error === '' ) {
            $error = 'E-mail se nepodařilo odeslat (SMTP).';
        }

        elementsell_log_failed_email( 0, $email, $email_content['subject'], $email_content['message'] );
    }

    $args = [
        'page'                   => 'elementsell',
        'es_gmail_test_result'   => $sent ? 'ok' : 'failed',
        'es_gmail_test_to'       => rawurlencode( $email ),
        'es_gmail_test_from'     => rawurlencode( $from ),
        'es_gmail_test_reply_to' => rawurlencode( $reply_to ),
        'es_gmail_test_transport'=> rawurlencode( $transport ),
        'es_gmail_test_warning'  => rawurlencode( $warning ),
    ];

    if ( ! $sent && $error !== '' ) {
        $args['es_gmail_test_error'] = rawurlencode( $error );
    }

    wp_safe_redirect( add_query_arg( $args, admin_url( 'admin.php' ) ) . '#elementsell-gmail-smtp' );
    exit;
}

/**
 * @return void
 */
function elementsell_render_gmail_smtp_test_notices() {
    if ( ! isset( $_GET['es_gmail_test_result'] ) ) {
        return;
    }

    $result    = sanitize_key( wp_unslash( (string) $_GET['es_gmail_test_result'] ) );
    $to        = isset( $_GET['es_gmail_test_to'] ) ? sanitize_email( wp_unslash( (string) $_GET['es_gmail_test_to'] ) ) : '';
    $from      = isset( $_GET['es_gmail_test_from'] ) ? sanitize_email( wp_unslash( (string) $_GET['es_gmail_test_from'] ) ) : '';
    $reply_to  = isset( $_GET['es_gmail_test_reply_to'] ) ? sanitize_email( wp_unslash( (string) $_GET['es_gmail_test_reply_to'] ) ) : '';
    $transport = isset( $_GET['es_gmail_test_transport'] ) ? sanitize_key( wp_unslash( (string) $_GET['es_gmail_test_transport'] ) ) : '';
    $error     = isset( $_GET['es_gmail_test_error'] ) ? sanitize_text_field( wp_unslash( (string) $_GET['es_gmail_test_error'] ) ) : '';
    $warning   = isset( $_GET['es_gmail_test_warning'] ) ? sanitize_text_field( wp_unslash( (string) $_GET['es_gmail_test_warning'] ) ) : '';

    $transport_label = function_exists( 'elementsell_format_email_log_transport_label' )
        ? elementsell_format_email_log_transport_label( $transport )
        : $transport;

    if ( $result === 'ok' ) {
        echo '<div class="notice notice-success is-dismissible"><p>';
        echo esc_html(
            sprintf(
                'Testovací e-mail odeslán na %s. From: %s. Reply-To: %s. Kanál: %s.',
                $to,
                $from !== '' ? $from : '—',
                $reply_to !== '' ? $reply_to : '—',
                $transport_label !== '' && $transport_label !== '—' ? $transport_label : '—'
            )
        );
        echo '</p>';

        if ( $warning !== '' ) {
            echo '<p class="description"><strong>Upozornění:</strong> ' . esc_html( $warning ) . '</p>';
        }

        echo '</div>';
        return;
    }

    echo '<div class="notice notice-error is-dismissible"><p>';

    if ( $error !== '' ) {
        echo esc_html( $error );
    } else {
        echo esc_html( 'Testovací e-mail se nepodařilo odeslat.' );
    }

    echo ' ';
    echo esc_html(
        sprintf(
            'From: %s. Kanál: %s.',
            $from !== '' ? $from : '—',
            $transport_label !== '' && $transport_label !== '—' ? $transport_label : '—'
        )
    );
    echo '</p></div>';
}

/**
 * @return void
 */
function elementsell_render_gmail_smtp_settings() {
    if ( ! current_user_can( 'manage_options' ) ) {
        return;
    }

    $gmail_address              = sanitize_email( (string) get_option( 'elementsell_gmail_address', '' ) );
    $has_password               = elementsell_get_gmail_app_password() !== '';
    $is_connected               = $gmail_address !== '' && $has_password;
    $disable_paid_notifications = (int) get_option( 'elementsell_gmail_disable_paid_notifications', 0 );

    echo '<div class="elementsell-admin-card elementsell-admin-card--form" id="elementsell-gmail-smtp">';
    echo '<h2 class="elementsell-admin-section-title">Napoj svůj Gmail</h2>';

    elementsell_render_gmail_smtp_test_notices();

    echo '<form method="post" action="options.php" id="elementsell-gmail-settings-form">';
    settings_fields( 'elementsell_gmail_settings' );

    if ( $is_connected ) {
        echo '<div class="elementsell-gmail-connected" id="elementsell-gmail-connected">';
        echo '<p class="elementsell-gmail-connected-label">' . esc_html( 'Připojený účet' ) . '</p>';
        echo '<div class="elementsell-gmail-connected-row">';
        echo '<strong class="elementsell-gmail-connected-email">' . esc_html( $gmail_address ) . '</strong>';
        echo '<button type="button" class="button button-secondary" id="elementsell-gmail-change-btn">' . esc_html( 'Změnit Gmail' ) . '</button>';
        echo '</div>';
        echo '</div>';
    }

    echo '<div class="elementsell-gmail-settings' . ( $is_connected ? ' is-hidden' : '' ) . '" id="elementsell-gmail-edit-fields">';
    echo '<input type="email" id="elementsell_gmail_address" name="elementsell_gmail_address" value="' . esc_attr( $gmail_address ) . '" class="regular-text" autocomplete="email" placeholder="Gmail adresa"' . ( $is_connected ? ' data-locked="1"' : '' ) . '>';
    echo '<div class="elementsell-password-field">';
    echo '<input type="password" id="elementsell_gmail_app_password" name="elementsell_gmail_app_password" value="" class="regular-text" autocomplete="new-password" placeholder="' . esc_attr( $has_password ? '••••••••••••••••' : 'Heslo aplikace' ) . '">';
    echo '<button type="button" class="button button-secondary elementsell-toggle-password" aria-label="Zobrazit heslo" aria-pressed="false" data-target="elementsell_gmail_app_password" data-has-stored="' . esc_attr( $has_password ? '1' : '0' ) . '">';
    echo '<span class="dashicons dashicons-visibility" aria-hidden="true"></span>';
    echo '</button>';
    echo '</div>';
    echo '</div>';
    echo '<p class="description elementsell-gmail-app-password-hint' . ( $is_connected ? ' is-hidden' : '' ) . '" id="elementsell-gmail-app-password-hint">';
    echo esc_html( 'Heslo získáš zde: ' );
    echo '<a href="' . esc_url( 'https://myaccount.google.com/apppasswords' ) . '" target="_blank" rel="noopener noreferrer">myaccount.google.com/apppasswords</a>';
    echo esc_html( ' (dvoufázové ověření musí být zapnuté).' );
    echo '</p>';
    echo '<p class="description elementsell-gmail-change-hint is-hidden" id="elementsell-gmail-change-hint">';
    echo esc_html( 'Zadej novou Gmail adresu a nové heslo aplikace pro tento účet, pak ulož.' );
    echo '</p>';
    submit_button( 'Uložit Gmail nastavení' );
    echo '<p class="elementsell-gmail-notification-pref">';
    echo '<input type="hidden" name="elementsell_gmail_disable_paid_notifications" value="0">';
    echo '<label for="elementsell_gmail_disable_paid_notifications">';
    echo '<input type="checkbox" id="elementsell_gmail_disable_paid_notifications" name="elementsell_gmail_disable_paid_notifications" value="1" ' . checked( 1, $disable_paid_notifications, false ) . '> ';
    echo esc_html( 'Nechci dostávat upozornění o zaplacených objednávkách' );
    echo '</label>';
    echo '</p>';
    echo '</form>';

    echo '<form method="post" action="' . esc_url( admin_url( 'admin-post.php' ) ) . '" class="elementsell-gmail-test-form">';
    wp_nonce_field( 'elementsell_send_gmail_test_email' );
    echo '<input type="hidden" name="action" value="elementsell_send_gmail_test_email">';
    echo '<p class="description">Pošli si test, ať vidíš, jestli napojení funguje</p>';
    echo '<p class="elementsell-gmail-test-row">';
    echo '<label for="elementsell_gmail_test_email" class="screen-reader-text">E-mail příjemce</label>';
    echo '<input type="email" class="regular-text" id="elementsell_gmail_test_email" name="elementsell_gmail_test_email" value="" placeholder="' . esc_attr( 'Jiná e-mailová adresa' ) . '" required> ';
    submit_button( 'Odeslat test', 'secondary', 'submit', false );
    echo '</p>';
    echo '</form>';
    echo '</div>';

    elementsell_gmail_smtp_admin_scripts();
}

/**
 * @return void
 */
function elementsell_gmail_smtp_admin_scripts() {
    static $loaded = false;

    if ( $loaded ) {
        return;
    }

    $loaded = true;
    ?>
    <script>
        (function() {
            function elementsellUpdatePasswordToggleButton(button, isVisible) {
                button.setAttribute('aria-pressed', isVisible ? 'true' : 'false');
                button.setAttribute('aria-label', isVisible ? 'Skrýt heslo' : 'Zobrazit heslo');

                var icon = button.querySelector('.dashicons');
                if (!icon) {
                    return;
                }

                icon.classList.toggle('dashicons-visibility', !isVisible);
                icon.classList.toggle('dashicons-hidden', isVisible);
            }

            function elementsellShowGmailChangeForm() {
                var connected = document.getElementById('elementsell-gmail-connected');
                var editFields = document.getElementById('elementsell-gmail-edit-fields');
                var hint = document.getElementById('elementsell-gmail-app-password-hint');
                var changeHint = document.getElementById('elementsell-gmail-change-hint');
                var emailInput = document.getElementById('elementsell_gmail_address');
                var passwordInput = document.getElementById('elementsell_gmail_app_password');
                var toggleBtn = document.querySelector('.elementsell-toggle-password[data-target="elementsell_gmail_app_password"]');

                if (connected) {
                    connected.classList.add('is-hidden');
                }
                if (editFields) {
                    editFields.classList.remove('is-hidden');
                }
                if (hint) {
                    hint.classList.remove('is-hidden');
                }
                if (changeHint) {
                    changeHint.classList.remove('is-hidden');
                }
                if (emailInput) {
                    emailInput.removeAttribute('data-locked');
                    emailInput.readOnly = false;
                    emailInput.focus();
                    emailInput.select();
                }
                if (passwordInput) {
                    passwordInput.value = '';
                    passwordInput.type = 'password';
                    passwordInput.readOnly = false;
                    passwordInput.placeholder = 'Nové heslo aplikace';
                    delete passwordInput.dataset.elementsellStoredHint;
                }
                if (toggleBtn) {
                    toggleBtn.setAttribute('data-has-stored', '0');
                    elementsellUpdatePasswordToggleButton(toggleBtn, false);
                }
            }

            document.addEventListener('click', function(event) {
                if (event.target.closest('#elementsell-gmail-change-btn')) {
                    event.preventDefault();
                    elementsellShowGmailChangeForm();
                    return;
                }

                var button = event.target.closest('.elementsell-toggle-password');
                if (!button) {
                    return;
                }

                var inputId = button.getAttribute('data-target');
                var input = inputId ? document.getElementById(inputId) : null;
                if (!input) {
                    return;
                }

                var isVisible = input.type === 'text';
                var hasStored = button.getAttribute('data-has-stored') === '1';
                var isStoredHint = input.dataset.elementsellStoredHint === '1';

                if (!isVisible && input.value === '' && hasStored && !isStoredHint) {
                    input.type = 'text';
                    input.value = 'Heslo je uložené';
                    input.readOnly = true;
                    input.dataset.elementsellStoredHint = '1';
                    elementsellUpdatePasswordToggleButton(button, true);
                    return;
                }

                if (isVisible && isStoredHint) {
                    input.type = 'password';
                    input.value = '';
                    input.readOnly = false;
                    delete input.dataset.elementsellStoredHint;
                    elementsellUpdatePasswordToggleButton(button, false);
                    return;
                }

                input.readOnly = false;
                delete input.dataset.elementsellStoredHint;
                input.type = isVisible ? 'password' : 'text';
                elementsellUpdatePasswordToggleButton(button, !isVisible);
            });

            document.addEventListener('focus', function(event) {
                var input = event.target;
                if (!input || input.id !== 'elementsell_gmail_app_password') {
                    return;
                }

                if (input.dataset.elementsellStoredHint !== '1') {
                    return;
                }

                var button = document.querySelector('.elementsell-toggle-password[data-target="elementsell_gmail_app_password"]');
                input.type = 'password';
                input.value = '';
                input.readOnly = false;
                delete input.dataset.elementsellStoredHint;

                if (button) {
                    elementsellUpdatePasswordToggleButton(button, false);
                }
            }, true);
        })();
    </script>
    <?php
}

function elementsell_render_invoice_settings() {

    wp_enqueue_media();

    echo '<div class="elementsell-admin-card elementsell-admin-card--form" id="elementsell-invoice-settings">';
    echo '<h2 class="elementsell-admin-section-title">Tvé údaje na automaticky generovanou fakturu</h2>';

    echo '<form method="post" action="options.php">';

    settings_fields('elementsell_invoice_settings');

    echo '<table class="form-table elementsell-invoice-settings">';

    elementsell_invoice_checkbox_field('faktury_platce_dph', 'Plátce DPH');
    elementsell_invoice_vat_rate_field();

    elementsell_invoice_text_field('faktury_jmeno', 'Jméno dodavatele', 'Petr Kočiš');
    elementsell_invoice_textarea_field('faktury_adresa', 'Adresa', 'Elišky Přemyslovny 434, Praha');
    elementsell_invoice_text_field('faktury_ico', 'IČO', '14301440');
    elementsell_invoice_text_field('faktury_dic', 'DIČ', '');

    elementsell_invoice_upload_field('faktury_logo', 'Logo ve formátu jpg, png<br><span style="font-weight:400;">(nepovinné)</span>', 'Nahrát logo');
    elementsell_invoice_upload_field('faktury_podpis', 'Podpis ve formátu jpg, png<br><span style="font-weight:400;">(nepovinné)</span>', 'Nahrát podpis');

    echo '</table>';

    submit_button('Uložit změny');

    echo '</form>';
    echo '</div>';

    elementsell_invoice_admin_scripts();
}

function elementsell_invoice_text_field( $option_name, $label, $default = '' ) {
    $value = get_option($option_name, $default);

    echo '<tr>';
    echo '<th scope="row"><label for="' . esc_attr($option_name) . '">' . esc_html($label) . '</label></th>';
    echo '<td>';
    echo '<input type="text" id="' . esc_attr($option_name) . '" name="' . esc_attr($option_name) . '" value="' . esc_attr($value) . '" class="regular-text">';
    echo '</td>';
    echo '</tr>';
}

function elementsell_invoice_textarea_field( $option_name, $label, $default = '' ) {
    $value = get_option($option_name, $default);

    echo '<tr>';
    echo '<th scope="row"><label for="' . esc_attr($option_name) . '">' . esc_html($label) . '</label></th>';
    echo '<td>';
    echo '<textarea id="' . esc_attr($option_name) . '" name="' . esc_attr($option_name) . '" class="regular-text" rows="3">' . esc_textarea($value) . '</textarea>';
    echo '</td>';
    echo '</tr>';
}

function elementsell_invoice_vat_rate_field() {
    $value = elementsell_get_invoice_vat_rate_for_display();

    echo '<tr id="elementsell-vat-rate-row">';
    echo '<th scope="row"><label for="faktury_dph_sazba">Výše DPH (%)</label></th>';
    echo '<td>';
    echo '<input type="number" id="faktury_dph_sazba" name="faktury_dph_sazba" value="' . esc_attr($value) . '" class="small-text" min="0" max="100" step="0.01">';
    echo '</td>';
    echo '</tr>';
}

function elementsell_get_invoice_vat_rate_for_display() {
    if ( false === get_option( 'faktury_dph_sazba', false ) ) {
        return 21;
    }

    return get_option( 'faktury_dph_sazba' );
}

/**
 * Zda je dodavatel plátce DPH (pro budoucí generování faktur).
 *
 * @return bool
 */
function elementsell_is_invoice_vat_payer() {
    return (bool) (int) get_option( 'faktury_platce_dph', 0 );
}

/**
 * Uložená sazba DPH v procentech (pro budoucí generování faktur).
 * Výchozí 21, pokud hodnota nebyla nikdy uložena. Uložená 0 zůstane 0.
 *
 * @return float
 */
function elementsell_get_invoice_vat_rate() {
    if ( false === get_option( 'faktury_dph_sazba', false ) ) {
        return 21.0;
    }

    return floatval( get_option( 'faktury_dph_sazba' ) );
}

function elementsell_invoice_checkbox_field( $option_name, $label ) {
    $value = get_option($option_name, 0);

    echo '<tr>';
    echo '<th scope="row">' . esc_html($label) . '</th>';
    echo '<td>';
    echo '<label class="elementsell-switch">';
    echo '<input type="checkbox" name="' . esc_attr($option_name) . '" value="1" ' . checked(1, $value, false) . '>';
    echo '<span></span>';
    echo '</label>';
    echo '</td>';
    echo '</tr>';
}

function elementsell_invoice_upload_field( $option_name, $label, $button_text ) {
    $value = get_option($option_name, '');

    echo '<tr>';
    echo '<th scope="row"><label for="' . esc_attr($option_name) . '">' . wp_kses_post($label) . '</label></th>';
    echo '<td>';
    echo '<input type="text" id="' . esc_attr($option_name) . '" name="' . esc_attr($option_name) . '" value="' . esc_attr($value) . '" class="regular-text elementsell-upload-url"> ';
    echo '<button type="button" class="button elementsell-upload-button" data-target="' . esc_attr($option_name) . '">' . esc_html($button_text) . '</button>';

    if ( ! empty($value) ) {
        echo '<div style="margin-top:12px;">';
        echo '<img src="' . esc_url($value) . '" style="max-width:110px; max-height:90px; height:auto;">';
        echo '</div>';
    }

    echo '</td>';
    echo '</tr>';
}

function elementsell_invoice_admin_scripts() {
    ?>
    <style>
        .elementsell-invoice-settings th {
            width: 220px;
        }

        .elementsell-switch {
            position: relative;
            display: inline-block;
            width: 38px;
            height: 22px;
        }

        .elementsell-switch input {
            display: none;
        }

        .elementsell-switch span {
            position: absolute;
            cursor: pointer;
            inset: 0;
            background: #cfcfcf;
            border-radius: 30px;
            transition: .2s;
        }

        .elementsell-switch span:before {
            content: "";
            position: absolute;
            height: 16px;
            width: 16px;
            left: 3px;
            top: 3px;
            background: white;
            border-radius: 50%;
            transition: .2s;
        }

        .elementsell-switch input:checked + span {
            background: #2271b1;
        }

        .elementsell-switch input:checked + span:before {
            transform: translateX(16px);
        }
    </style>

    <script>
        jQuery(document).ready(function($) {
            function elementsellToggleVatRateRow() {
                var $row = $('#elementsell-vat-rate-row');
                var isVatPayer = $('input[name="faktury_platce_dph"]').is(':checked');

                if ( isVatPayer ) {
                    $row.show();
                } else {
                    $row.hide();
                }
            }

            $('input[name="faktury_platce_dph"]').on('change', elementsellToggleVatRateRow);
            elementsellToggleVatRateRow();

            $('.elementsell-upload-button').on('click', function(e) {
                e.preventDefault();

                const target = $('#' + $(this).data('target'));

                const frame = wp.media({
                    title: 'Vybrat obrázek',
                    button: {
                        text: 'Použít obrázek'
                    },
                    multiple: false
                });

                frame.on('select', function() {
                    const attachment = frame.state().get('selection').first().toJSON();
                    target.val(attachment.url);
                });

                frame.open();
            });
        });
    </script>
    <?php
}
