<?php
/**
 *
 * @link       info@meteosales.com
 * @since      1.0.0
 *
 * @package    Meteosales
 * @subpackage Meteosales/admin/partials
 */
/*
Version: 1.0.16
*/
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
    wp_enqueue_style( 'meteosales-bootstrap-min-css' );
    wp_enqueue_style( 'meteosales-admin-css' );
if ( in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) ) {//if woocommerce is activated

    global $wpdb;
    $ok = false;
   $no_ok = false;
    if(isset($_POST["update_settings"])){
        $tk = sanitize_text_field($_POST["token"]);
        $syncro_type= sanitize_text_field($_POST["syncro_type"]);
        $array = array("token"=>$tk,"syncro_type"=>$syncro_type, "n"=>0);

        update_option( "MeteoCommerceProductsSetting", json_encode($array) );

        $api_key = 'https://my.meteosales.com/api/check';
        $server = $_SERVER["SERVER_NAME"];
        $response = wp_remote_post($api_key, array(
                'body' => array( 'token' => $tk, 'server_name' => $server )

            ));
            $output     = wp_remote_retrieve_body( $response );
            $data = json_decode($output, true);

            if($data["data"] == "ok"){
                $ok = true;

            }else{
                $no_ok = true;
            }


    }
    $sort = get_option("MeteoCommerceProductsSetting");

    if(!$sort){//if Get_Option does not exist
        $token  = "";
        $syncro_type = "manual";
    }
    else{
        $arr_sort = json_decode($sort, true);
        $token = $arr_sort["token"];
        $syncro_type = $arr_sort["syncro_type"];
        $n = $arr_sort["n"];
    }

    ?>
    <style>
        html body { background-color: #F1F1F1; }

        .bold{font-weight: bold}
        .switch {
            position: relative;
            display: inline-block;
            width: 60px;
            height: 34px;
        }

        .switch input {
            opacity: 0;
            width: 0;
            height: 0;
        }

        .slider {
            position: absolute;
            cursor: pointer;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: #2196F3;/**/
            -webkit-transition: .4s;
            transition: .4s;
        }

        .slider:before {
            position: absolute;
            content: "";
            height: 26px;
            width: 26px;
            left: 4px;
            bottom: 4px;
            background-color: white;
            -webkit-transition: .4s;
            transition: .4s;
        }

        input:focus + .slider { box-shadow: 0 0 1px #2196F3; }

        input:checked + .slider:before {
            -webkit-transform: translateX(26px);
            -ms-transform: translateX(26px);
              transform: translateX(26px);
        }
        .bold {font-weight: bold;}
        /* Rounded sliders */
        .slider.round { border-radius: 34px; }
        .slider.round:before { border-radius: 50%; }

        .overlay{
            display: none;
            position: fixed;
            width: 100%;
            height: 100%;
            top: 0;
            left: 0;
            z-index: 999;
            background: rgba(255,255,255,0.8)  center no-repeat;


        }
        .load_center{top: 50%; left: 30%; position: fixed; font-size: 30px; font-weight: bold;}
        body.loading{ overflow: hidden;  }
        body.loading .overlay{ display: block; }
        
        .lds-hourglass {
  display: inline-block;
  position: relative;
  width: 80px;
  height: 80px;
}
.lds-hourglass:after {
  content: " ";
  display: block;
  border-radius: 50%;
  width: 0;
  height: 0;
  margin: 8px;
  box-sizing: border-box;
  border: 32px solid #fff;
  border-color: #ff1e1e transparent #ff1e1e transparent;
  animation: lds-hourglass 1.2s infinite;
}
@keyframes lds-hourglass {
  0% {
    transform: rotate(0);
    animation-timing-function: cubic-bezier(0.55, 0.055, 0.675, 0.19);
  }
  50% {
    transform: rotate(900deg);
    animation-timing-function: cubic-bezier(0.215, 0.61, 0.355, 1);
  }
  100% {
    transform: rotate(1800deg);
  }
}

    </style>
    <div class="container">
        <div class="wrap">
            <div class="my-4">
                <img  src="<?php echo plugin_dir_url( dirname( __FILE__ ) ) . '/images/meteosales.svg'; ?>" style="width:350px"><br>
		    </div>
            <hr>
            <div class="pdgDisplayMessage">
                <div id="syn" class="alert alert-warning alert-dismissible" style="display:none;"></div>
                <div id="wait" class="alert alert-danger alert-dismissible" style="display:none;"></div>
                <?php if($ok){ ?>
                    <div class="alert alert-success alert-dismissible">
                        <?php echo _e( 'Settings Updated', 'meteosales' ); ?>
                    </div>
                <?php } ?>
                <?php if($no_ok){ ?>
                    <div class="alert alert-danger alert-dismissible">
                        <?php echo _e( 'API Key invalid!', 'meteosales' ); ?>
                    </div>
                <?php } ?>
            </div>
            <div id="poststuff">
            <div class="container postbox">
                <h3 class="wp-heading-inline h1-type" style="margin-top: 0.5rem;"><?php echo _e( 'Settings', 'meteosales' ); ?></h3>
                <div class="row">
                    <div class="col meta-box-sortables ui-sortable ">
                        <div class="row my-2">
                                <div class="col-6">
                                    <label class="mb-2"><strong><?= _e( 'Video 3: How to sync data', 'meteosales' ); ?></strong></label>
                                    <div class="embed-responsive embed-responsive-16by9">
                                        <iframe width="560" height="315" src="https://www.youtube.com/embed/0C5zIIJEJ90" title="<?= _e( 'How to sync data', 'meteosales' ); ?>" frameborder="0" allow="encrypted-media;" allowfullscreen></iframe>
                                    </div>
                                </div>
                                <div class="col-6">

                                </div>
                            </div>
                        <div id="surgery_info_box" style="padding:10px;">
                            <form name="Adds" id="Adds" method="POST" >
                                <div style="display:flex">
                                    <div>
                                        <label for="token"><strong><?php echo _e( 'API Key', 'meteosales' ); ?></strong></label>
                                        <input type="text" id="token" name="token" value="<?php echo $token ?>" size="50">
                                    </div>

                                </div>
                                <hr>
                                <div class="my-3">
                                    <label><strong><?php echo _e( 'Syncro Type ', 'meteosales' ); ?></strong></label>
                                    <label data-toggle="tooltip" data-placement="top" title="<?php echo _e( "Manual: Sync Data each time you click on button 'Synchro'. Automatic: Sync Data each time you update a Products", 'meteosales' ); ?>"><?php echo _e( '(?)', 'meteosales' ); ?></label>
                                    <br><br>
                                <div style="display: flex">
                                    <div>
                                        <label id="manual"for="d_type" style="padding-right: 20px;" <?php echo $syncro_type == "manual" ? "class='bold'" : ""; ?>><?php echo _e( 'Manual', 'meteosales' ); ?> </label>
                                        <label class="switch">
                                            <input id="d_type" type="checkbox" onchange="change(this)" <?php echo $syncro_type == "manual" ? "" : "checked"; ?> >
                                            <span class="slider round"></span>
                                        </label>
                                        <label for="d_type" id="automatic" style="padding-left: 20px;" <?php echo $syncro_type == "automatic" ? "class='bold'" : ""; ?>><?php echo _e( 'Automatic', 'meteosales' ); ?> </label>
                                        <input type="hidden" name="syncro_type" id="syncro_type" value ="<?php echo $syncro_type ?>">

                                    </div>
                                    <div style="margin-left:20px">
                                        <input type="submit" id="update_settings" name="update_settings" class="button button-primary button-large" value="<?php echo _e( 'Save', 'meteosales' ); ?>" />
                                    </div>
                                </div>
                                <?php if( $syncro_type == "manual"): ?>
                                    <div style="margin-top:20px; display:flex" id="div_syncro">
                                        <label><strong><?php echo _e( 'Click to start sync Data: ', 'meteosales' ); ?></strong></label><br>
                                        <div style="margin-left:10px;">
                                            <input type="button" id="sincronizza" name="sincronizza" class="button btn btn-success btn-lg" value="<?php echo _e( 'Sync Now', 'meteosales' ); ?>" onclick='Sincronizza()'/>
                                        </div>
                                        <div style="margin-left:20px;">
                                            <strong><p id="is_loading"></p></strong>
                                        </div>

                                    </div>
                                <?php else: ?>
                                    <div>
                                        <strong><p id="is_loading"></p></strong>
                                    </div>
                                <?php endif; ?>
                            </form>
                            <input type="hidden" id="syncro_type_hide" value ="<?php echo $syncro_type ?>">
                            <input type="hidden" id="n_hide" value ="<?php echo $n ?>">
                        </div>
                    </div>
                </div>
                <div class="overlay">
                    <div class="load_center">
                        <div style="display:flex">
                            <div class="lds-hourglass"></div>
                            <div style="text-align:center"><?php echo _e( 'Data Synchronization in progress... <br>Please don\'t close the page.', 'meteosales' ); ?><br> <?php echo _e( 'This can take some time...', 'meteosales' ); ?>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    </div>
    <script type="text/javascript">
    <?php if($ok){ ?>
        jQuery(document).ready(function(){
            var type  = jQuery("#syncro_type_hide").val();
            var n  = jQuery("#n_hide").val();

                if(type == "automatic" && n == 0){
                    goAjax();
                }

        });
         <?php } ?>
        <?php if( $syncro_type == "manual"): ?>
    		function Sincronizza(){

    			goAjax();
    		}
    	<?php endif; ?>


        function goAjax(){
            jQuery("body").addClass("loading");
             jQuery("#sincronizza").prop("disabled",true);
             jQuery("#update_settings").prop("disabled",true);
             jQuery('#syn').text('<?php echo esc_js( 'Data Synchronization in progress... Please don\'t close the page.', 'meteosales' ); ?>');
             jQuery('#syn').show();
             jQuery('#wait').text('<?php echo esc_js( 'This can take some time... Please wait.', 'meteosales' ); ?>');
             jQuery('#wait').show();

            var token  = jQuery("#token").val();
    		if(token != ""){
    		    jQuery.post(ajaxurl,{'action': 'synchro'},
                function (msg) {
                    console.log("ok 1");
                    jQuery("#is_loading").text("");

                    goAjax2(msg);

                }).fail(function(xhr, status, error) {
                    alert('<?php echo esc_js( 'Something went wrong :( Please contact support at info@meteosales.com', 'meteosales' ); ?>');
                    jQuery('#wait').html('<strong><?php echo esc_js( 'Something went wrong :( Please contact support at info@meteosales.com', 'meteosales' ); ?></strong>');
                    jQuery('#syn').hide();
                    jQuery("body").removeClass("loading");
                }, "json");
            }
            else{
                jQuery("#is_loading").text("");
                alert("<?php echo esc_js( 'API Key not valid. Please Check.', 'meteosales' ); ?>");
                jQuery("#sincronizza").prop("disabled",false);
                jQuery("#update_settings").prop("disabled",false);
                jQuery("body").removeClass("loading");
            }
        }

        function goAjax2(msg1){

            jQuery("#sincronizza").prop("disabled",true);
            jQuery("#update_settings").prop("disabled",true);

            var token  = jQuery("#token").val();

    		jQuery.post(ajaxurl,{'action': 'synchroOrders'},
                function (msg) {
                     console.log("ok 2");
                    jQuery("#is_loading").text("");
                    jQuery('#syn').hide();
                    jQuery('#wait').hide();
                    alert('<?php echo esc_js( 'Synchronization Successful!', 'meteosales' ); ?>' + "\n"+ msg1+ "\n"+msg);

                    jQuery("#sincronizza").prop("disabled",false);
                    jQuery("#update_settings").prop("disabled",false);
                    jQuery("body").removeClass("loading");
                }).fail(function(xhr, status, error) {
                    alert('<?php echo esc_js( 'Something went wrong :( Please contact support at info@meteosales.com', 'meteosales' ); ?>');
                    jQuery('#wait').html('<strong><?php echo esc_js( 'Something went wrong :( Please contact support at info@meteosales.com', 'meteosales' ); ?></strong>');
                    jQuery('#syn').hide();
                    jQuery("body").removeClass("loading");
                }, "json");
        }

    	function change(checkboxElem) {
            if (checkboxElem.checked) {
                jQuery('#syncro_type').val("automatic");
                jQuery("#manual").removeClass('bold');
                jQuery("#automatic").addClass('bold');
            }
            else {
               jQuery('#syncro_type').val("manual");
                jQuery("#automatic").removeClass('bold');
                jQuery("#manual").addClass('bold');
            }
        }
    </script>
     <?php
}else{ ?>
    <style>
        html body { background-color: #F1F1F1; }
    </style>
    <div class="container">
        <div class="wrap">
            <div class="my-4">
                <img  src="<?php echo plugin_dir_url( dirname( __FILE__ ) ) . '/images/meteosales.svg'; ?>" style="width:350px"><br>
                <h3 class="wp-heading-inline h1-type"><?php echo _e( 'Settings', 'meteosales' ); ?></h3>
		    </div>
            <hr>
            <div class="pdgDisplayMessage">
                <div class="alert alert-danger alert-dismissible">
                    <?php echo _e( 'Sorry! This plugin works only with Woocommerce', 'meteosales' ); ?>
                </div>
            </div>
        </div>
    </div><?php
}

$plugin_data = get_plugin_data( __FILE__  );

echo '<script type="text/javascript">
        jQuery(document).ready(function(){
            document.getElementById("footer-left").innerHTML = "";
            document.getElementById("footer-upgrade").innerHTML = "'.__( 'v ', 'meteosales' ) .  $plugin_data['Version'].'";

        });
</script>';?>
