<?php
/*
Plugin Name: Auto Login After Registration
Plugin URI: http://www.netattingo.com/
Description: This plugin allows users to easily add a simple user registration form and login form  anywhere on their site using simple shortcode.
And provide setting to 'Auto Login After Registration'. 
Author: NetAttingo Technologies
Version: 1.0.0
Author URI: http://www.netattingo.com/
*/

//define('WP_DEBUG',true);
define('ALAR_REGISTRATION_PAGE_DIRECTORY', plugin_dir_path(__FILE__) . 'pages/');
define('ALAR_REGISTRATION_INCLUDE_URL', plugin_dir_url(__FILE__) . 'includes/');
ob_start();
//Include menu
function alar_auto_login_plugin_menu()
{
    add_menu_page("Auto Login after Register", "Auto Login after Register", "administrator", "auto_login_on_register_setting", "alar_logo_plugin_pages", '', 40);
    add_submenu_page("auto_login_on_register_setting", "About Us", "About Us", "administrator", "about-us", "alar_logo_plugin_pages");
}

add_action("admin_menu", "alar_auto_login_plugin_menu");
function alar_logo_plugin_pages()
{
    $itm = ALAR_REGISTRATION_PAGE_DIRECTORY . $_GET["page"] . '.php';
    include($itm);
}

//add admin css
function alar_admin_css()
{
    wp_register_style('admin_css', plugins_url('includes/admin-style.css', __FILE__));
    wp_enqueue_style('admin_css');
}

add_action('admin_init', 'alar_admin_css');


//add front end css and js
function alar_slider_trigger()
{
//    wp_enqueue_style('alar_caro_css_and_js', ALAR_REGISTRATION_INCLUDE_URL . "front-style.css");
//    wp_register_script('alar_caro_css_and_js', ALAR_REGISTRATION_INCLUDE_URL . "font-script.js");
    wp_enqueue_script('alar_caro_css_and_js');
}

add_action('wp_footer', 'alar_slider_trigger');
/*=================================================*/


// function to registration Shortcode
function alar_registration_shortcode($atts)
{
    global $wpdb, $user_ID;
    $username = '';
    $firstname = '';
    $lastname = '';
    $email = '';

    $usermobile = '';

    //if looged in rediret to home page
    if (is_user_logged_in()) {
        wp_redirect(get_option('home'));// redirect to home page
        exit;
    }
    if (isset($_POST['com_submit'])) {

        $username = sanitize_text_field($_REQUEST['com_username']);
        $firstname = sanitize_text_field($_REQUEST['com_firstname']);
        $lastname = sanitize_text_field($_REQUEST['com_lastname']);
        $email = sanitize_text_field($_REQUEST['com_email']);
        $usermobile = sanitize_text_field($_REQUEST['user_mobile']);
        $password = $wpdb->escape(sanitize_text_field($_REQUEST['current_password']));
        $password2 = $wpdb->escape(sanitize_text_field($_REQUEST['current_password2']));

        $status = wp_create_user($username, $password, $email);

        if ($password != $password2) {
            $error_msg = __('كلمة المرور غير متطابقة', 'm7md'); ?>
            <div class="alert alert-danger" role="alert">
                <?php echo $error_msg; ?>
            </div>

        <?php } else {
            // print_r($status);
            if (is_wp_error($status)) {
                $error_msg = __('اسم الدخول او البريد الالكتروني مسجل من قبل', 'm7md');
            } else {
                $user_id = $status;
                update_user_meta($user_id, 'com_username', $username);
                update_user_meta($user_id, 'first_name', $firstname);
                update_user_meta($user_id, 'last_name', $lastname);
                update_user_meta($user_id, 'user_mobile', $usermobile);

                //code to auto login start
                $alar_enable_auto_login = get_option('alar_enable_auto_login');
                if ($alar_enable_auto_login == '') {
                    $alar_enable_auto_login = 'true';
                }

                if ($alar_enable_auto_login == 'true') {
                    if (!is_user_logged_in()) {
                        $secure_cookie = is_ssl();
                        $secure_cookie = apply_filters('secure_signon_cookie', $secure_cookie, array());
                        global $auth_secure_cookie;
                        $auth_secure_cookie = $secure_cookie;
                        wp_set_auth_cookie($user_id, true, $secure_cookie);
                        $user_info = get_userdata($user_id);
                        do_action('wp_login', $user_info->user_login, $user_info);
                    }
                }


//$to =$email;
// $subject = 'رسالة تفعيل عضويتك علي  موقع';
// $body = 'اضغط علي الرابط لتفعيل عضويتك   <a href="'.site_url().'/confirm/?reg='.base64_encode($email).' ">اضغط هنا للتفعيل</a> ';
// $headers = array('Content-Type: text/html; charset=UTF-8');
// wp_mail( $to, $subject, $body, $headers );


                //code to auto login end
                wp_redirect(get_option('home'));// redirect to home page
                exit;
            }
        }
    }
    ?>
    <div class="alar-registration-form">

        <?php if ($error_msg != '') : ?>
            <div class="error"><?php $error_msg; ?></div>
        <?php endif; ?>

        <form name="form"
              id="registration"
              method="post">
            <div class="alert alert-warning" role="alert">
                <strong>
                    الرجاء فى خانه إسم المستخدم استخدام الحروف الإنجليزية وعدم وضع مسافات بينهم
                </strong>
            </div>
            <div class="form-group">
                <label for="com_username">
                    <?php _e("إسم المستخدم * :", 'm7md'); ?>
                </label>
                <input id="com_username"
                       name="com_username"
                       type="text"
                       class="form-control"
                       required>
            </div>
            <div class="form-group">
                <label for="com_firstname">
                    <?php _e("الأسم الأول:", 'm7md'); ?>
                </label>
                <input id="com_firstname"
                       name="com_firstname"
                       type="text"
                       class="form-control"
                       required>
            </div>
            <div class="form-group">
                <label for="com_lastname">
                    <?php _e("الأسم الأخير :", 'm7md'); ?>
                </label>
                <input id="com_lastname"
                       name="com_lastname"
                       type="text"
                       class="form-control"
                       required>
            </div>
            <div class="form-group">
                <label for="com_email">
                    <?php _e("البريد الألكترونى :", 'm7md'); ?>
                </label>
                <input id="com_email"
                       name="com_email"
                       type="email"
                       class="form-control"
                       required>
            </div>

            <div class="form-group">
                <label for="com_mobile">
                    <?php _e("الجوال * :", 'm7md'); ?>
                </label>
                <input id="com_mobile"
                       name="user_mobile"
                       type="tel"
                       class="form-control"
                       required>
            </div>


            <div class="form-group">
                <label for="password1">
                    <?php _e("كلمة المرور :", 'm7md'); ?>
                </label>
                <input id="password1"
                       name="current_password"
                       type="password"
                       required
                       class="form-control"/>
            </div>
            <div class="form-group">
                <label for="password2">
                    <?php _e("تاكيد كلمة المرور : ", 'm7md'); ?>
                </label>
                <input id="password2"
                       name="current_password2"
                       type="password"
                       class="form-control"/>
            </div>

            <button type="submit"
                    name='com_submit'
                    class="main-btn">
                <span><?php _e("تسجيل", 'm7md'); ?></span>
            </button>

        </form>
    </div>
    <?php
}

//add registration shortcode
add_shortcode('registration-form', 'alar_registration_shortcode');

/*=================================================*/
// function to login Shortcode
function alar_login_shortcode($atts)
{

    //if looged in rediret to home page
    if (is_user_logged_in()) {
        wp_redirect(get_option('home'));// redirect to home page
        exit;
    }

    global $wpdb;
    if (sanitize_text_field($_GET['login']) != '') {
        $login_fail_msg = sanitize_text_field($_GET['login']);
    }
    ?>
    <div class="alar-login-form">
        <?php if ($login_fail_msg == 'failed') { ?>
            <div class="error">
                <?php _e('إسم المستخدم أو كلمة المرور غير صحيحة', 'm7md'); ?>
            </div>
        <?php } ?>

        <form method="post"
              action="<?php echo get_option('home'); ?>/wp-login.php"
              class="mb-3"
              id="loginform"
              name="loginform">

            <input type="hidden"
                   value="<?php echo get_option('home'); ?>"
                   name="redirect_to">

            <div class="form-group">
                <label for="user_login">
                    <?php _e('إسم المستخدم أو البريد الإلكترونى :', 'm7md'); ?>
                </label>
                <input type="text"
                       class="form-control"
                       id="user_login"
                       required
                       name="log"/>
            </div>
            <div class="form-group">
                <label for="user_pass">
                    <?php _e('كلمة المرور :', 'm7md'); ?>
                </label>
                <input type="password"
                       class="form-control"
                       id="user_pass"
                       required
                       name="pwd"/>
            </div>

<div class="d-flex align-items-center justify-content-between">
    <button type="submit"
            class="main-btn"
            id="wp-submit"
            name="wp-submit">
        <span><?php _e('دخول', 'm7md'); ?></span>
    </button>

    <a class="main-btn"
       href="<?php echo get_page_link(151); ?>">
        <span><?php _e('إستعادة كلمة المرور', 'm7md'); ?></span>
    </a>
</div>
    </form>



    </div>
    <?php
}

//add login shortcoode
add_shortcode('login-form', 'alar_login_shortcode');


//redirect to front end ,when login is failed
add_action('wp_login_failed', 'my_front_end_login_fail');  // hook failed login

function my_front_end_login_fail($username)
{
    $referrer = $_SERVER['HTTP_REFERER'];
    // if there's a valid referrer, and it's not the default log-in screen
    if (!empty($referrer) && !strstr($referrer, 'wp-login') && !strstr($referrer, 'wp-admin')) {
        wp_redirect($referrer . '/?login=failed');  // let's append some information (login=failed) to the URL for the theme to use
        exit;
    }
}

?>
