<?php
if (!defined('ABSPATH')) exit; // Exit if accessed directly
if (is_array($convpfm_data) && array_key_exists("convpfm_microsoft_mail", $convpfm_data) && sanitize_email($convpfm_data["convpfm_microsoft_mail"]) && isset($_GET['subscription_id']) && sanitize_text_field(wp_unslash($_GET['subscription_id']))) {
    update_option('convpfm_microsoft_mail', sanitize_email($convpfm_data["convpfm_microsoft_mail"]));

    // $eeapidata['setting'] = $eeapidata_settings;
    // update_option('ee_api_data', serialize($eeapidata));
    //is not work for existing user && $ee_additional_data['con_created_at'] != "" 
    // if (isset($ee_additional_data['con_created_at'])) {
    //     $ee_additional_data = $TVC_Admin_Helper->get_ee_additional_data();
    //     $ee_additional_data['con_updated_at'] = gmdate('Y-m-d');
    //     $TVC_Admin_Helper->set_ee_additional_data($ee_additional_data);
    // } else {
    //     $ee_additional_data = $TVC_Admin_Helper->get_ee_additional_data();
    //     $ee_additional_data['con_created_at'] = gmdate('Y-m-d');
    //     $ee_additional_data['con_updated_at'] = gmdate('Y-m-d');
    //     $TVC_Admin_Helper->set_ee_additional_data($ee_additional_data);
    // }
}
$sub_page = (isset($_GET['subpage'])) ? sanitize_text_field(wp_unslash(filter_input(INPUT_GET, 'subpage'))) : "";
?>

<div class="convwiz_pixtitle mt-0 mb-3 d-flex justify-content-between align-items-center py-0">

    <div class="col-7">
        <?php if ($sub_page == "mmcsettings") { ?>
            <ul class="conv-green-checklis list-unstyled mt-3">
                <li class="d-flex">
                    <span class="material-symbols-outlined text-success md-18">
                        check_circle
                    </span>
                    <?php esc_html_e("Showcase your products on Bing Shopping", "enhanced-e-commerce-for-woocommerce-store"); ?>
                </li>
                <!-- Showcase your products on Microsoft Ads -->
            </ul>
        <?php } ?>
    </div>

    <div class="col convgauthcol">
        <div class="convpixsetting-inner-box ps-3" style="border-left: 3px solid #09bd83;">
            <?php
            $g_email = get_option('convpfm_microsoft_mail');
            ?>
            <?php if ($g_email != "") { ?>
                <h5 class="fw-normal mb-1">
                    <?php esc_html_e("Successfully signed in with account:", "enhanced-e-commerce-for-woocommerce-store"); ?>
                </h5>
                <span>
                    <?php echo ($g_email); ?>
                    <?php if (isset($_GET['subpage']) && $_GET['subpage'] == "mmcsettings") { ?>
                        <span class="conv-link-blue ps-0 tvc_microsoft_signinbtn">
                            <?php esc_html_e("Change", "enhanced-e-commerce-for-woocommerce-store"); ?>
                        </span>
                    <?php } ?>

                </span>
            <?php } else { ?>
                <div class="tvc_microsoft_signinbtn_box">
                    <div class="tvc_microsoft_signinbtn microsoft-btn d-flex align-items-center">
                        <div class="microsoft-icon-wrapper">
                            <img class="align-self-center"
                                src="<?php echo esc_url_raw(CONVPFM_ENHANCAD_PLUGIN_URL . '/admin/images/logos/ms-logo.png'); ?>" />
                        </div>
                        <div class="btn-text"><b><?php esc_html_e("Sign in with Microsoft", "enhanced-e-commerce-for-woocommerce-store"); ?></b></div>
                    </div>
                </div>
            <?php } ?>
        </div>
    </div>
</div>


<!-- Microsoft signin -->
<div class="pp-modal onbrd-popupwrp" id="tvc_microsoft_signin" tabindex="-1" role="dialog">
    <div class="onbrdppmain" role="document">
        <div class="onbrdnpp-cntner acccretppcntnr">
            <div class="onbrdnpp-hdr">
                <div class="ppclsbtn clsbtntrgr">
                    <img class="align-self-center"
                        src="<?php echo esc_url_raw(CONVPFM_ENHANCAD_PLUGIN_URL . '/admin/images/close-icon.png'); ?>" />
                </div>
            </div>
            <div class="onbrdpp-body">
                <div class="h6 py-2 px-1" style="background: #d7ffd7;">Please use Chrome browser to configure the plugin if you face any issues during setup.</div>
                <div class="microsoft_signin_sec_left">
                    <?php
                    $woo_currency = get_option('woocommerce_currency');
                    $timezone = get_option('timezone_string');
                    $ms_redirect_uri = CONVPFM_API_CALL_URL_TEMP . '/auth/microsoft/callback';
                    $confirm_url = urlencode("admin.php?page=conversiospfm&subpage=mmcsettings"); // final decided, if not working redirect url to our plugin then need to decode in middleware.
                    $state = ['confirm_url' => admin_url() . $confirm_url, 'subscription_id' => $subscriptionId, 'ms_redirect_uri' => $ms_redirect_uri];
                    $microsoft_auth_url = "https://login.microsoftonline.com/common/oauth2/v2.0/authorize?client_id=892127ea-3496-4e25-8909-12705e629eae&response_type=code&redirect_uri=https://connect.conversios.io/laravelapi/public/auth/microsoft/callback&response_mode=query&tenant=d6545bb5-03a2-461a-880a-14ce7ce63143&scope=openid email profile offline_access https://ads.microsoft.com/msads.manage User.Read&state=" . urlencode(wp_json_encode($state));

                    ?>
                    <?php if (!isset($convpfm_data['convpfm_microsoft_mail']) || $convpfm_data['convpfm_microsoft_mail'] == "" || $subscriptionId == "") { ?>
                        <div class="microsoft_connect_url microsoft-btn d-flex align-items-center" onclick='window.open("<?php echo esc_js(esc_url($microsoft_auth_url)); ?>","MyWindow","width=800,height=700,left=300, top=150"); return false;'>
                            <?php if (isset($ee_options['microsoft_ads_manager_id']) || isset($_GET['subscription_id'])) { ?>
                                <span>Change</span>
                            <?php } else { ?>
                                <div class="microsoft-icon-wrapper">
                                    <img class="align-self-center"
                                        src="<?php echo esc_url_raw(CONVPFM_ENHANCAD_PLUGIN_URL . '/admin/images/logos/ms-logo.png'); ?>" />
                                </div>
                                <div class="btn-text"><b><?php esc_html_e("Sign in with Microsoft", "enhanced-e-commerce-for-woocommerce-store"); ?></b></div>
                            <?php } ?>
                        </div>
                    <?php } else { ?>
                        <?php if ($is_refresh_token_expire == true) { ?>
                            <p class="alert alert-primary"><?php esc_html_e("It seems the token to access your Microsoft accounts is expired. Sign in again to continue.", "enhanced-e-commerce-for-woocommerce-store"); ?></p>
                            <div class="microsoft_connect_url microsoft-btn d-flex align-items-center" onclick='window.open("<?php echo esc_js(esc_url($microsoft_auth_url)); ?>","MyWindow","width=800,height=700,left=300, top=150"); return false;'>
                                <div class="microsoft-icon-wrapper">
                                    <img class="align-self-center"
                                        src="<?php echo esc_url_raw(CONVPFM_ENHANCAD_PLUGIN_URL . '/admin/images/close-icon.png'); ?>" />
                                </div>
                                <div class="btn-text"><b><?php esc_html_e("Sign in with Microsoft", "enhanced-e-commerce-for-woocommerce-store"); ?></b></div>
                            </div>
                        <?php } else { ?>
                            <div class="microsoft_connect_url microsoft-btn d-flex align-items-center" onclick='window.open("<?php echo esc_js(esc_url($microsoft_auth_url)); ?>","MyWindow","width=800,height=700,left=300, top=150"); return false;'>
                                <div class="microsoft-icon-wrapper">
                                    <img class="align-self-center"
                                        src="<?php echo esc_url_raw(CONVPFM_ENHANCAD_PLUGIN_URL . '/admin/images/close-icon.png'); ?>" />
                                </div>
                                <div class="btn-text"><b><?php esc_html_e("Reauthorize Microsoft", "enhanced-e-commerce-for-woocommerce-store"); ?></b></div>
                            </div>
                        <?php } ?>
                    <?php } ?>
                    <p class="p-0 pe-2 pt-2"><?php esc_html_e("Make sure you sign in with the Microsoft email account that has all privileges to access  Microsoft Advertising account that you want to configure for your store.", "enhanced-e-commerce-for-woocommerce-store"); ?></p>
                </div>
                <div class="microsoft_signin_sec_right">
                    <h6><?php esc_html_e("Why do I need to sign in with Microsoft?", "enhanced-e-commerce-for-woocommerce-store"); ?></h6>
                    <p><?php esc_html_e("When you sign in with Microsoft, we ask for limited programmatic access to your accounts in order to automate the following features for you:", "enhanced-e-commerce-for-woocommerce-store"); ?></p>
                    <p><strong><?php esc_html_e("1. Microsoft Ads:", "enhanced-e-commerce-for-woocommerce-store"); ?></strong><?php esc_html_e("To automate dynamic remarketing, conversion tracking, enhanced conversion tracking, and to create performance campaigns as required.", "enhanced-e-commerce-for-woocommerce-store"); ?></p>
                    <p><strong><?php esc_html_e("2. Microsoft Merchant Center:", "enhanced-e-commerce-for-woocommerce-store"); ?></strong><?php esc_html_e("To automate product feed submission using the Content API and to set up your Merchant Center account.", "enhanced-e-commerce-for-woocommerce-store"); ?></p>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    jQuery(function() {
        var convpfm_data = "<?php echo esc_js(wp_json_encode($convpfm_data)); ?>";
        var convpfm_ajax_url = '<?php echo esc_url(admin_url('admin-ajax.php')); ?>';
        let subscription_id = "<?php echo esc_attr($subscriptionId); ?>";
        let plan_id = "<?php echo (isset($plan_id)) ? esc_attr($plan_id) : ''; ?>";
        let app_id = "<?php echo esc_attr(CONVPFM_APP_ID); ?>";

        jQuery(".tvc_microsoft_signinbtn").on("click", function() {
            jQuery('#tvc_microsoft_signin').addClass('showpopup');
        });
        jQuery(".clsbtntrgr, .ppblubtn").on("click", function() {
            jQuery(this).closest('.onbrd-popupwrp').removeClass('showpopup');
        });
    });
</script>