<?php

function salesloo_email_editor()
{
    if (!isset($_GET['action']) || $_GET['action'] != 'salesloo-email-editor') return;

    $target = 'customer';
    $targets = [
        'customer',
        'affiliate',
        'admin'
    ];

    if (isset($_GET['target']) && in_array($_GET['target'], $targets)) {
        $target = sanitize_text_field($_GET['target']);
    }

    $event = isset($_GET['event']) ? sanitize_text_field($_GET['event']) : '';
    $email = salesloo_email($target . '_' . $event);

    if (null === $email) {
        wp_die('Invalid email editor');
    }

?>
    <style>
        .wp-die-message,
        p {
            font-size: 14px;
        }
    </style>
    </head>

    <body class="wp-core-ui wp-customizer js">
        <div class="wp-full-overlay expanded">
            <form id="customize-controls" class="wrap wp-full-overlay-sidebar" method="post" action="">
                <div id="customize-header-actions" class="wp-full-overlay-header">
                    <div style="padding-left: 50px">
                        <?php _e('Go back to the email setting'); ?>
                    </div>
                    <a class="customize-controls-close" href="<?php echo esc_url(admin_url('admin.php?page=salesloo-settings&tab=notification&section=email&column=' . $target)); ?>">
                        <span class="screen-reader-text"><?php _e('Go back to the email setting'); ?></span>
                    </a>
                </div>

                <div id="widgets-right" class="wp-clearfix">
                    <div id="customize-notifications-area" class="customize-control-notifications-container">
                        <ul></ul>
                    </div>
                    <div class="wp-full-overlay-sidebar-content" tabindex="-1">
                        <div id="customize-info" class="accordion-section customize-info">
                            <div class="accordion-section-title">
                                <span class="preview-notice">
                                    <?php
                                    /* translators: %s: The site/panel title in the Customizer. */
                                    printf(__('Email for %s'), $email->target_title);
                                    ?>
                                    <div>
                                        <strong>on <?php echo $email->event_title; ?></strong>
                                    </div>
                                </span>
                            </div>
                            <div class="customize-panel-description" style="display:block;">
                                <div class="notice notice-info inline" style="font-style:italic">
                                    <p>
                                        <?php _e('Please save template first to apply preview', 'salesloo') ?>
                                    </p>
                                </div>
                            </div>
                            <div style="padding: 5px">
                                <?php $email->fields(); ?>
                            </div>
                        </div>
                    </div>
                </div>

                <div id="customize-footer-actions" class="wp-full-overlay-footer">
                    <button type="button" class="collapse-sidebar button" aria-expanded="true" aria-label="<?php echo esc_attr_x('Hide Controls', 'label for hide controls button without length constraints'); ?>">
                        <span class="collapse-sidebar-arrow"></span>
                        <span class="collapse-sidebar-label"><?php _ex('Hide Controls', 'short (~12 characters) label for hide controls button'); ?></span>
                    </button>
                    <div class="devices-wrapper" style="height: 100%;padding-right:10px;">
                        <div class="devices" style="height: 100%;display:flex;align-items: center;">
                            <div class="customize-save-button-wrapper">
                                <?php submit_button('Save Template', 'primary save', 'salesloo_save_template', false); ?>
                            </div>
                        </div>
                    </div>
                </div>
                <?php wp_nonce_field('salesloo-email-editor', '_wpnonce', false, true); ?>
            </form>
            <div class="wp-full-overlay-main" style="overflow-y:auto;">
                <div>
                    <?php $email->preview(); ?>
                </div>
            </div>
            <?php

            /**
             * Prints templates, control scripts, and settings in the footer.
             *
             * @since 3.4.0
             */
            do_action('customize_controls_print_footer_scripts');
            ?>
        </div>
    </body>

    </html>
<?php
    exit;
}
add_action('customize_controls_head', 'salesloo_email_editor');

/**
 * salesloo_email_editor_save
 * 
 * @return void
 */
function salesloo_email_editor_save()
{

    if (!isset($_POST)) return;

    if (isset($_POST['_wpnonce']) && wp_verify_nonce($_POST['_wpnonce'], 'salesloo-email-editor')) {

        unset($_POST['salesloo_save_template']);
        unset($_POST['_wpnonce']);

        foreach ($_POST as $key => $val) {
            if (strpos($key, 'body') !== false) {
                update_option(sanitize_text_field($key), wp_kses_post(wpautop($val)));
            } else {
                update_option(sanitize_text_field($key), sanitize_text_field($val));
            }
        }

        $url = admin_url('customize.php');
        $redirect = add_query_arg($_GET, $url);
        wp_redirect($redirect);
        exit;
    }
}

add_action('customize_controls_init', 'salesloo_email_editor_save');


/**
 * salesloo_email_replace_shortcode
 *
 * @param  string $content
 * @param  array $args
 * @return string
 */
function salesloo_email_replace_shortcode($content, $args = array())
{
    $default = [
        'site_name' => get_bloginfo('name')
    ];

    $args = wp_parse_args($args, $default);

    preg_match_all('@\[([^<>&/\[\]\x00-\x20=]++)@', $content, $matches);

    foreach ($matches[1] as $key => $tag) {
        if (isset($args[$tag])) {
            $content = str_replace('[' . $tag . ']', $args[$tag], $content);
        }
    }

    return $content;
}

function salesloo_email_classes()
{
    $classes = [
        'customer_register'                 => '\Salesloo\Email\Customer\Register',
        'customer_place_order'              => '\Salesloo\Email\Customer\Place_Order',
        'customer_invoice_checking_payment' => '\Salesloo\Email\Customer\Invoice_Checking_Payment',
        'customer_invoice_completed'        => '\Salesloo\Email\Customer\Invoice_Completed',
        'customer_invoice_refunded'         => '\Salesloo\Email\Customer\Invoice_Refunded',
        'customer_invoice_cancelled'        => '\Salesloo\Email\Customer\Invoice_Cancelled',
        'customer_invoice_unpaid_reminder'  => '\Salesloo\Email\Customer\Invoice_Unpaid_Reminder',
        'customer_order_expired_reminder'   => '\Salesloo\Email\Customer\Order_Expired_Reminder',
        'customer_order_expired'            => '\Salesloo\Email\Customer\Order_Expired',
        'affiliate_new_lead'                => '\Salesloo\Email\Affiliate\New_Lead',
        'affiliate_new_sales'               => '\Salesloo\Email\Affiliate\New_Sales',
        'affiliate_commission_paid'         => '\Salesloo\Email\Affiliate\Commission_Paid',
        'admin_register'                    => '\Salesloo\Email\Admin\Register',
        'admin_place_order'                 => '\Salesloo\Email\Admin\Place_Order',
        'admin_invoice_checking_payment'    => '\Salesloo\Email\Admin\Invoice_Checking_Payment',
        'admin_invoice_completed'           => '\Salesloo\Email\Admin\Invoice_Completed',
        'admin_affiliate_commission'        => '\Salesloo\Email\Admin\Affiliate_Commission',
    ];

    $classes = apply_filters('salesloo/email/classes', $classes);

    return $classes;
}

function salesloo_email($type)
{
    $classes = salesloo_email_classes();

    if (isset($classes[$type])) {
        return new $classes[$type];
    }

    return null;
}

function salesloo_email_default_content($default)
{
    $email_default_options = [];
    foreach (salesloo_email_classes() as $key => $class) {

        $class = new $class;
        $email_default_options['notification_email_' . $class->target . '_' . $class->event . '_subject'] = $class->default_subject();
        $email_default_options['notification_email_' . $class->target . '_' . $class->event . '_body'] = $class->default_body();
    }

    return wp_parse_args($email_default_options, $default);
}

add_filter('salesloo/options/default', 'salesloo_email_default_content', 10);



function salesloo_email_layout($content)
{
    ob_start();
?>
    <div bgcolor="#F0F2F8" style="border:0;margin:0;padding:0;min-width:100%;width:100%">


        <table bgcolor="#F0F2F8" border="0" cellpadding="0" cellspacing="0" width="100%" style="border:0;margin:0;padding:0">
            <tbody>
                <tr>
                    <td style="font-size:16px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td>
                    <td>
                        <table align="center" border="0" cellpadding="0" cellspacing="0" style="width:480px;min-width:480px;max-width:480px">
                            <tbody>
                                <tr>
                                    <td>
                                        <table border="0" cellpadding="0" cellspacing="0" width="100%">
                                            <tbody>
                                                <tr>
                                                    <td height="58" style="border:0;margin:0;padding:0;font-size:1px;line-height:1px;max-height:1px">
                                                        <div>&nbsp;</div>
                                                    </td>
                                                </tr>
                                            </tbody>
                                        </table>

                                        <table cellpadding="0" cellspacing="0">
                                            <tbody>

                                                <tr>

                                                    <td style="border:0;border-collapse:collapse;margin:0;padding:0">

                                                        <span style="font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,'Helvetica Neue',Ubuntu,sans-serif;text-decoration:none;font-weight:500;color:rgb(0,0,0);font-size:20px;line-height:24px">

                                                            <?php echo bloginfo('name'); ?>

                                                        </span>

                                                    </td>


                                                </tr>

                                            </tbody>
                                        </table>

                                        <table border="0" cellpadding="0" cellspacing="0" width="100%">
                                            <tbody>
                                                <tr>
                                                    <td height="32" style="border:0;margin:0;padding:0;font-size:1px;line-height:1px;max-height:1px">
                                                        <div>&nbsp;</div>
                                                    </td>
                                                </tr>
                                            </tbody>
                                        </table>
                                        <!--- body --->
                                        <?php echo $content; ?>
                                        <table border="0" cellpadding="0" cellspacing="0" width="100%">
                                            <tbody>
                                                <tr>
                                                    <td height="32" style="border:0;margin:0;padding:0;font-size:1px;line-height:1px;max-height:1px">
                                                        <div>&nbsp;</div>
                                                    </td>
                                                </tr>
                                            </tbody>
                                        </table>
                                        <table cellpadding="0" cellspacing="0" style="width:100%">
                                            <tbody>
                                                <tr>
                                                    <td style="border:0;border-collapse:collapse;margin:0;padding:0;width:100%;text-align:center;color:rgb(0,0,0);opacity:0.5">
                                                        <div style="font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,'Helvetica Neue',Ubuntu,sans-serif;text-decoration:none;font-size:12px;line-height:14px">
                                                            <?php echo \salesloo_get_option('notification_email_footer'); ?>
                                                        </div>
                                                    </td>
                                                </tr>
                                            </tbody>
                                        </table>
                                    </td>
                                </tr>
                            </tbody>
                        </table>


                    </td>
                    <td style="font-size:16px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td>
                </tr>
                <tr>
                    <td height="64" colspan="3" style="border:0;margin:0;padding:0;font-size:1px;line-height:1px">
                        <div>&nbsp;</div>
                    </td>
                </tr>
            </tbody>
        </table>
    </div>
<?php
    return apply_filters('salesloo/email/layout', ob_get_clean(), $content);
}
